I have the following function that I did in Java, it solves my problem, however I want to play with javascript as well. So I had the following problem: I only found functions that retrieve unique values, and I wanted a function similar to dataSnapshot.getChildren() that has in Java only that for JavaScript, if not, what would be the alternative?
To understand better, I'll leave the Java code here that works perfectly.
mRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
float okk = Float.valueOf(ds.child("value").getValue(String.class))/100000000;
prov += ds.child("wallet").getValue(String.class)+", "+String.format(Locale.US,"%.8f", okk)+"\n";
ds.getRef().removeValue();
}
tx_array.setText(prov);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
The output will have to look like this, the same is in java.
39Hs93m61zYCaiaNe8yzgrDcutVAz2Kgdc, 0.00151515
3QMTHAaYcQB8kJxF5nxxBwskyCFukCNH8t, 0.00151515
3AcNSeB9DX3ZKvGxMaec9uZ98rY2BJKuzW, 0.00153787
36SjF1MBm2DE6YimNYiy9T4ez6Z7UA4rpg, 0.001540903
AHr3GF12div1Kgf6DegeiHSGQYssvbmih, 0.00162121
19vR7xchAg1vUgGwATwBsz5NYrVWYKdSQ3, 0.00164545
3KmfDgW9RdWp7P2ns3tydXsiChR5U9XKdT, 0.00165757
1C8rxppQk8mRSWB8xPKZ5DsYVykJBLNhV3, 0.00166212
Database Struct
If you take this piece of Java code:
mRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
float okk = Float.valueOf(ds.child("value").getValue(String.class))/100000000;
prov += ds.child("wallet").getValue(String.class)+", "+String.format(Locale.US,"%.8f", okk)+"\n";
ds.getRef().removeValue();
The equivalent in JavaScript would be:
ref.once("value").then(function(snapshot) {
snapshot.forEach(function(ds) {
var okk = ds.child("value").val() / 100000000;
prov += ds.child("wallet").val()+ ", "...
ds.ref.remove();
});
});
If you run into this type of question more often, I highly recommend reading the Android documentation and Web documentation side by side. They both follow the exact same structure, so once you know how to do something in Android, you can easily map it to JavaScript.
Based on what I read and the user told me, I was able to solve my problem with the following code, which works perfectly as I wanted.
exports.showEvent = functions.https.onRequest((req, res) => {
let prov = "";
return admin.database().ref('requests').once('value', (snapshot) => {
snapshot.forEach(function(ds) {
var okk = ds.child("value").val() / 100000000;
prov += ds.child("wallet").val()+ ", " + parseFloat(okk).toFixed(8) + "\n";
ds.ref.remove();
});
res.send(prov);
});
});
Related
I have an ASP.NET Project, where I want to use the FileSystemWatcher. To do that I created an class "Watcher":
public class Watcher
{
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public static void Run()
{
Console.WriteLine("FileWatcherStarted");
using (FileSystemWatcher watcher = new FileSystemWatcher())
{
watcher.Path = #"C:\\FilesToWatch";
watcher.NotifyFilter = NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.FileName
| NotifyFilters.DirectoryName;
watcher.Filter = "*.txt";
watcher.Changed += OnChanged;
watcher.Created += OnChanged;
watcher.Deleted += OnChanged;
watcher.EnableRaisingEvents = true;
}
}
private static void OnChanged(object source, FileSystemEventArgs e) =>
Console.WriteLine($"{e.FullPath}, {e.ChangeType}");
}
Then I call this Run method in the IActionResult Index() method in the home controller with:
Watcher.Run();
Now when I want to run or debug my project i get no result from my file watcher. No error occurs. Theres just the message "Thread 0x123 ended with Code 0 (0x0)".
Anyone, who had the same problem or knows the solution?
Is there any way to get the version_name based on the version_code of an android package?
For example:
'com.nianticlabs.pokemongo'
version_code: 2017121800
=> version_name: 0.87.5
all I want is something like:
function getVersionName(version_code) {
// do smt with version_code
return version_name;
}
But I don't think you can get one depending on the other, those are two separate things: only a string and an int
In native java you have:
public static int getVersionCode(Context context) {
try {
PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
return pInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
return -1;
}
}
public static String getVersionName(Context context) {
try {
PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
return pInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
return "";
}
}
you could look for the equivalent in your javascript google API
Easiest way to get version name:
private String getVersionName() {
versionName = BuildConfig.VERSION_NAME;
return versionName;
}
No this is not possible in general. Every app is completely free to choose it's own version name (user readable string) and version code scheme. Many apps will have two APKs which have different version codes with exactly the same version name. See the docs.
Why I'm getting this error?
System.InvalidCastException was unhandled by user code
Message=Specified cast is not valid.
Source=System.Windows.Forms
StackTrace:
at System.Windows.Forms.UnsafeNativeMethods.IHTMLDocument2.GetLocation()
at System.Windows.Forms.WebBrowser.get_Document()
at System.Windows.Forms.WebBrowser.get_DocumentStream()
at System.Windows.Forms.WebBrowser.get_DocumentText()
at SiteBot.MainWindow.backgroundWorker1_DoWork(Object sender, DoWorkEventArgs e) in D:\Documents\Visual Studio 2010\Projects\SiteBot\MainWindow.cs:line 35
at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)
InnerException:
The following solves your cross thread issue.
public delegate string GetStringHandler();
public string GetDocumentText()
{
if (InvokeRequired)
return Invoke(new GetStringHandler(GetDocumentText)) as string;
else
return webBrowser.DocumentText;
}
if (regAddId.IsMatch(GetDocumentText()))
{
}
I get a threading exception with this test:
public class Test
{
private readonly WebBrowser wb;
public Test()
{
wb = new WebBrowser();
var bw = new BackgroundWorker();
bw.DoWork += DoWork;
bw.RunWorkerAsync();
while (bw.IsBusy)
{
Thread.Sleep(10);
Application.DoEvents();
}
}
private void DoWork(object sender, DoWorkEventArgs e)
{
wb.Navigate(#"www.clix-cents.com/pages/clickads");
Thread.Sleep(1000);
var regex = new Regex("onclick=\\'openad\\(\"([\\d\\w]+\"\\);");
regex.IsMatch(wb.DocumentText);
}
}
public class Program
{
[STAThread]
public static void Main(string[] args)
{
new Test();
}
}
The exception looks like this:
Since WebBrowser is really just a wrapper around IE's ActiveX control, you'll need to be careful about threading issues. I think what you really want to use here is a WebClient and not a WebBrowser, but I'm just guessing about your application.
[EDIT]
Like #Fun states you can just Invoke over to the GUI thread (assuming thats where the control was created. I'd still recommend using a WebClient.
i have some local html file and i want to show them with infinite scroll method.
NOTE: i cant change the html content, so please don't advice to add javascript to them. i must do it in run time.
so, i figured out that i can execute javascript in runtime via loadUrl("javascript: ....").
i overrided onOverScrolled() method of webView to find out when user reach the end of webView. (it acting carefully, so the problem is not here)
the problem is some times new content attached successfully and other times it didn't geting attached.
in the log i can see that the end of page method get triggered, retrieving new html body get called, executing javascript code get called, but it did not affect.
here is my code, may be something went wrong and i can not see it:
#Override
protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY)
{
super.onOverScrolled(scrollX, scrollY, clampedX, clampedY);
if(clampedY & reloadFlag) //for first time realodFlag is false, when the WebViewClient.onPageFinished() get called it turn to ture
{
if (!(isVerticalScrollPossible(SCROLL_DOWN)))
{
reloadFlag = false;
currUri = nextResource(currUri); //findout next page
appendNextPage();
}
}
}
private final int SCROLL_DOWN = 1;
private final int SCROLL_UP = -1;
private boolean isVerticalScrollPossible(int direction)
{
final int offset = computeVerticalScrollOffset();
final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
if (range == 0) return false;
if (direction < 0) {
return offset > 0;
} else {
return offset < range - 1;
}
}
public String getNextPageJS(Uri currPage)
{
String body = getNextPageBody(currPage);
//Log.d("myTAG", body);
String jsResult = "javascript:(function() { document.body.innerHTML += '<div id=\"separator\" style=\"height:10px; margin-top:10px; margin-bottom:10px; background-color:#000000;\"></div>" + body + "';})()";
return jsResult;
}
private void appendNextPage()
{
reloadFlag = false;
Thread appendThread = new Thread(null, doAppend, "backgroundAppend");
appendThread.start();
Log.i("appendNextPage", "get called");
}
public String rs = "";
private Runnable doAppend = new Runnable()
{
#Override
public void run()
{
Log.i("doAppend", "get called + currUri: " + currUri);
rs = getNextPageJS(currUri);
//loadUrl(rs);
appendHandler.sendEmptyMessage(0);
}
};
private Handler appendHandler = new Handler()
{
public void handleMessage(Message msg)
{
loadUrl(rs);
reloadFlag = true;
Log.i("appendHandler", "get called");
}
};
NOTE: sometimes i get this in the emulator log (not in real device):
I/chromium(1339): [INFO:CONSOLE(1)] "Uncaught SyntaxError: An invalid or illegal string was specified.", source: http://localhost:1025/OEBPS/Text/Section0042.xhtml (1)
the number of page is different from time to time, may be it's for bad javasccript code, i don't know.
hints:
1) i'm not javascript coder, so may be the javascript code is not good
2) or maybe calling javascript code several times cause this problem
3) i know that javascript code must execute after page loading completely, so maybe the code called too soon, the problem for this is that onPageFinished() getting called just for first page and it does not called when new content attached via javascript code, i tried to solve this problem using thread, and i think it worked.
UPDATE: i figured out that this code works fine when the html body is small, but when i try to attach large body it didn't work. is loadUrl() method has char limit? or any other idea?
OK, i found the problem, if anyone wants to know.
the problem is that the loadUri() (at least in my case) can not load too many html tag at once (in javascript code i written)
so, the solution is easy, load tags one by one.
here is the code i used:
public ArrayList<String> getNextPageBody(Uri currAddress)
{
String html = getHtml(currAddress); // this is the all html tags in the next file
//get body elements as arrayList, using jsoup
Document doc = Jsoup.parse(html);
Elements elements = doc.select("body").first().children();
ArrayList<String> chuncks = new ArrayList<String>();
for (org.jsoup.nodes.Element el : elements)
{
chuncks.add(el.toString());
}
return chuncks;
}
public void loadBodyChunk(ArrayList<String> bodyChunks)
{
//show a separator for each page
bodyChunks.add(0, "javascript:(function() { document.body.innerHTML += '<div id=\"separator\" style=\"height:10px; margin-top:10px; margin-bottom:10px; background-color:#000000;\"></div>';}())");
loadUrl(bodyChunks.get(0));
for(int i = 1; i < bodyChunks.size(); i++)
{
String jsResult = "javascript:(function() { document.body.innerHTML += '" + bodyChunks.get(i) + "';}())";
loadUrl(jsResult);
}
reloadFlag = true;
}
EDIT:
also:
first the 's in String should be replaced with \' :
body = body.replace("'", "\\'");
then all newline char should be eliminated:
body = body.replaceAll(System.getProperty("line.separator"), " ");
all problem solved.
What are the best practices to build an app's database schema on first execution?
In other words what I am trying to find out is:
SQLite does not support comma separated queries to be executed as a one statement batch. How to replace that so that the code stays future proof? (I don't see myself putting all the create statements in tx.executeSQL("") chained sequentially it would turn my code into a horrible piece of cr*p).
What I do, in native code as well as in Sencha/Phonegap is to use a DatabaseHelper Class that I refer to. In that class you can see the version of the Database with :
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 2);
this.myContext = context;
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
openDataBase();
int cVersion = myDataBase.getVersion();
if(cVersion != 2){
onUpgrade(myDataBase, myDataBase.getVersion(), 2);}
close();
} ....}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
this.getReadableDatabase();
try{
db.execSQL("ADD SQL QUERY HERE TO ADD TABLE");
}
catch(Exception e){}
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
Although this is tedious it keeps your database future proof and the query is called at run time. This covers both your needs.
I hope this helps :)