intl package and date formatting strange behaviour - internationalization

I start to use intl package in my dart project.
After start to use this package i use this code:
DateTime now = new DateTime.now();
var formatter = new DateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
String nowFormatted = formatter.format(now);
And it works correctly.
After i use intl i obtain this message in log:
Uncaught LocaleDataException: Locale data has not been initialized, call initializeDateFormatting(<locale>).
I cannot understand why i should pass locale in this code snippet

intl: ^0.15.7
I've the same issue to the current Intl version so I've solved with
these imports:
import 'package:intl/intl.dart';
import 'package:intl/date_symbol_data_local.dart';
and the code:
initializeDateFormatting();
DateTime now = DateTime.now();
var dateString = DateFormat('dd-MM-yyyy').format(now);
final String configFileName = 'lastConfig.$dateString.json';

Verify your imports:
import 'package:intl/date_symbol_data_local.dart';
import 'package:intl/intl.dart';
Set initializeDateFormatting according to your language, example:
initializeDateFormatting('pt_BR', null);

If you encounter this problem, write initializeDateFormatting('az'); top of "Material App". I searched for 1 hour and nobody wrote it clearly.
it is really solved.

I have solved this use in this way:
DateTime now = new DateTime.now();
var formatter = new DateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", 'en');
String nowFormatted = formatter.format(now);
But I have to make this to my dart file used to configure itnl support:
library translation_helper;
import 'dart:async';
import 'package:intl/date_symbol_data_local.dart';
import '../../resources/messages_all.dart';
void setupLanguage(){
//var germanDatesFuture = initializeDateFormatting('de_DE', null);
var enDatesFuture = initializeDateFormatting('en', null);
var germanMessagesFuture = initializeMessages('de');
var englishMessagesFuture = initializeMessages('en');
var italianMessagesFuture = initializeMessages('it');
var polishMessagesFuture = initializeMessages('pl');
Future
.wait([
enDatesFuture,
germanMessagesFuture,
englishMessagesFuture,
italianMessagesFuture,
polishMessagesFuture
]);
}
Before I was missing:
var enDatesFuture = initializeDateFormatting('en', null);
For more info I use:
dart 1.15.0
intl 0.12.7

Use this function in main
initializeDateFormatting();
and import like this
import 'package:intl/date_symbol_data_local.dart';

There's no need to call initializeDateFormatting directly from your code. Just call load method of app's localization delegates.
So you specify delegates like this:
final localizationsDelegates = <LocalizationsDelegate>[
AppLocalizationsDelegate(),
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
CupertinoLocalizationsDelegate()
];
...
MaterialApp(
localizationsDelegates: localizationsDelegates,
)
And pre-load them with system's locale:
import 'dart:ui' as ui;
...
for (final delegate in localizationsDelegates) {
await delegate.load(ui.Locale(ui.window.locale.languageCode));
}

In your pubspec.yaml, add this dependencie package: intl:
In your highest StatefulWidget (in your dart file), add these imports:
import 'package:intl/intl.dart';
import 'package:intl/date_symbol_data_local.dart';
In its State, override initState add :
#override
void initState() {
super.initState();
initializeDateFormatting(); //very important
}
And the code:
DateTime now = new DateTime.now();
var formatter = new DateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
String nowFormatted = formatter.format(now);

My issue was that I was getting error specifically for the "en_US" Locale even when I was not particularly using it. But I solved it by:
initializeDateFormatting('en', null);
initializeDateFormatting('en_US,', null);

In your class with MaterialApp add this code
import 'package:intl/date_symbol_data_local.dart';
#override
void initState() {
// TODO: implement initState
super.initState();`enter code here`
initializeDateFormatting();
}

To initialize the date format as per the system locale.
import 'package:intl/intl_standalone.dart'; // For standlone app
import 'package:intl/intl_browser.dart'; // For standlone app
import 'package:intl/date_symbol_data_local.dart';
...
await initializeDateFormatting(await findSystemLocale(), null);

I got the same error. But, only when switching between locales ('en' and 'si') within the app. None of the other solutions worked for me. So I just came up with this dumbest solution, and it worked. Just wrapped date-formatting in a try-catch block while initializeDateFormatting() is being called inside the catch block
String date(DateTime date, String _languageCode) {
try {
var formatter = new DateFormat.yMMMMd(_languageCode);
return formatter.format(date);
} catch(e) {
initializeDateFormatting();
var formatter = new DateFormat.yMMMMd(_languageCode);
return formatter.format(date);
}
}

Depending on intl: ^0.18.0
Just add this line in the method that listens to each time the locale changes
Intl.defaultLocale = languageCode;
package: https://pub.dev/packages/intl

Related

Unable to achieve expected transaction in karate-gatling for load testing [duplicate]

I am trying to reuse karate scripts and perform load testing using gatling. The scenario defined is to load constant 50 users per second for 10 seconds. (To load test 500 users) However the number of requests per second does not exceed 20 requests per second in the gatling report. Please let me know if i am doing anything wrong.
ExampleTest.java code which executes Karate scripts
//package examples;
import com.intuit.karate.Results;
import com.intuit.karate.Runner;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import net.masterthought.cucumber.Configuration;
import net.masterthought.cucumber.ReportBuilder;
import org.apache.commons.io.FileUtils;
class ExamplesTest {
#Test
void testParallel() {
//System.setProperty("karate.env", "demo"); // ensure reset if other tests (e.g. mock) had set env in CI
Results results = Runner.path("classpath:examples").tags("~#ignore").parallel(10);
generateReport(results.getReportDir());
assertEquals(0, results.getFailCount(), results.getErrorMessages());
}
public static void generateReport(String karateOutputPath) {
Collection<File> jsonFiles = FileUtils.listFiles(new File(karateOutputPath), new String[] {"json"}, true);
List<String> jsonPaths = new ArrayList<String>(jsonFiles.size());
jsonFiles.forEach(file -> jsonPaths.add(file.getAbsolutePath()));
Configuration config = new Configuration(new File("target"), "demo");
ReportBuilder reportBuilder = new ReportBuilder(jsonPaths, config);
reportBuilder.generateReports();
}
}
Scala Code to define load test scenarios.
package perf
import com.intuit.karate.gatling.PreDef._
import io.gatling.core.Predef._
import scala.concurrent.duration._
class KarateSimulate extends Simulation {
val protocol = karateProtocol(
"/v2/" -> Nil,
"/v2/" -> pauseFor("get" -> 0, "post" -> 25)
)
val userfeeder = csv("data/Token.csv").circular
val getScores = scenario("Get Scores for Students").feed(userfeeder).exec(karateFeature("classpath:examples/scores/student.feature"))
setUp(
getScores.inject(constantUsersPerSec(50) during (10 seconds)).protocols(protocol)
)
}
We updated the docs (in the develop branch) with tips on how to increase the thread-pool size if needed: https://github.com/intuit/karate/tree/develop/karate-gatling#increasing-thread-pool-size
Add a file called gatling-akka.conf to the root of the classpath (typically src/test/resources). Here is an example:
akka {
actor {
default-dispatcher {
type = Dispatcher
executor = "thread-pool-executor"
thread-pool-executor {
fixed-pool-size = 100
}
throughput = 1
}
}
}
Since we made some fixes recently, please try to build from source if the above does not work for 0.9.6.RC4, it is easy, here are the instructions: https://github.com/intuit/karate/wiki/Developer-Guide
If that does not work, it is important that you follow this process so that we can replicate: https://github.com/intuit/karate/wiki/How-to-Submit-an-Issue
Please see these links below for good examples of how others have worked with the Karate project team to replicate issues so that they can be fixed:
https://github.com/intuit/karate/issues/1668
https://github.com/intuit/karate/issues/845

Log all methods called in an app by Xposed

As title said, I want to use xposed to log all methods called in an app from it start till I stop it. I only want to log Class name, Method name, don't want to hook all method.
I try this code, but get error getMethod not found.
findAndHookMethod("java.lang.Class", lpparam.classLoader, "getMethod", String.class, Object.class, new XC_MethodHook()
Thanks in advance!
There is no one line solution like what you seem to be searching.
Hooking all methods will let log what methods were called by app from it start till stop (sort of - see below), but if (for some reason) you don't want to hook all methods, the only solution I can think of is modifying the java VM itself (NOT something I would recommend.)
A solution that (sort of) works
What I did was first use apktool to decompile my apk and get the names of all the methods in all the classes.
Then I used xposed to hook into every single method of every class and print to the dlog the current function name.
Why it only sort of works
Xposed has an overhead whenever it hook a methods. For general usage of xposed apps, it isnt much. But when you start hooking each and every methods of an app, the overhead very quickly becomes ridiculously large - So much so that while the above methods works for small apps, for any large app it very quickly causes the app to hang and then crash.
An alternative that also sort-of works
FRIDA is a way to inject javascript to native apps. Here they show you how to log all function calls. While in the above link they log all function calls in a piece of python code, the same code also works for Android.
There is a way to log all Java methods.Modify XposedBridge.
Xposed hook java method through XposedBridge.java's method
"handleHookedMethod(Member method, int originalMethodId, Object additionalInfoObj, thisObject, Object[] args)"
Log.v(TAG, "className " + method.getClass().getName() + ",methodName " + method.getName());
As mentioned before Xposed is not the way to go in this situation due to its overhead.
The simplest solution is just to use dmtracedump as provided by Google. Most x86 Android images and emulator come with the debuggable flag on (ro.debuggable) so you can even use it for closed source apps.
Additionally other tools such as Emma are known to work with Android as well, but these might need modifications to the source code.
I found a solution.
See this code snippet below.
package com.kyunggi.logcalls;
import android.content.pm.*;
import android.util.*;
import dalvik.system.*;
import de.robv.android.xposed.*;
import de.robv.android.xposed.callbacks.XC_LoadPackage.*;
import java.io.*;
import java.lang.reflect.*;
import java.util.*;
import static de.robv.android.xposed.XposedHelpers.findAndHookMethod;
import android.app.*;
public class Main implements IXposedHookLoadPackage {
private String TAG = "LogCall";
public void handleLoadPackage(final LoadPackageParam lpparam) throws Throwable {
if (!lpparam.packageName.equals("com.android.bluetooth")) {
Log.i(TAG, "Not: " + lpparam.packageName);
return;
}
Log.i(TAG, "Yes " + lpparam.packageName);
//Modified https://d3adend.org/blog/?p=589
ApplicationInfo applicationInfo = AndroidAppHelper.currentApplicationInfo();
if (applicationInfo.processName.equals("com.android.bluetooth")) {
Set<String> classes = new HashSet<>();
DexFile dex;
try {
dex = new DexFile(applicationInfo.sourceDir);
Enumeration entries = dex.entries();
while (entries.hasMoreElements()) {
String entry = (String) entries.nextElement();
classes.add(entry);
}
dex.close();
} catch (IOException e) {
Log.e("HookDetection", e.toString());
}
for (String className : classes) {
boolean obex = false;
if (className.startsWith("com.android.bluetooth") || (obex = className.startsWith("javax.obex"))) {
try {
final Class clazz = lpparam.classLoader.loadClass(className);
for (final Method method : clazz.getDeclaredMethods()) {
if (obex) {
if (!Modifier.isPublic(method.getModifiers())) {
continue; //on javax.obex package, hook only public APIs
}
}
XposedBridge.hookMethod(method, new XC_MethodHook() {
final String methodNam = method.getName();
final String classNam = clazz.getName();
final StringBuilder sb = new StringBuilder("[");
final String logstr = "className " + classNam + ",methodName " + methodNam;
#Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
//Method method=(Method)param.args[0];
sb.setLength(0);
sb.append(logstr);
//Log.v(TAG,logstr);
for (Object o : param.args) {
String typnam = "";
String value = "null";
if (o != null) {
typnam = o.getClass().getName();
value = o.toString();
}
sb.append(typnam).append(" ").append(value).append(", ");
}
sb.append("]");
Log.v(TAG, sb.toString());
}
});
}
} catch (ClassNotFoundException e) {
Log.wtf("HookDetection", e.toString());
}
}
}
}
// ClassLoader rootcl=lpparam.classLoader.getSystemClassLoader();
//findAndHookMethod("de.robv.android.xposed.XposedBridge", rootcl, "handleHookedMethod", Member.class, int.class, Object.class, Object.class, Object[].class, );
}
}

Key Input using GtkD

I'm a beginner of both gtk and GtkD.
Now, I'm trying to get input from keyboard with reference to this .
But, It seems that three years have made some changes in Toolkits.
I wrote code below. However, I got strange values of ev in callback function.
I could not see any prospect of resolution with going alone.
So, could you show me where to modify?
I appreciate you in advance, and also your patient with my poor English.
I'm using gtkD-2.1.1 and gtk+3.2.3.
this is the full code:
import std.stdio;
import gtkc.gdktypes;
import gtk.MainWindow;
import gtk.Widget;
import gdk.Event;
import gtk.Main;
class Window : MainWindow{
immutable width = 200;
immutable height = 200;
this(){
super("input test");
setDefaultSize(width,height);
setEvents(EventMask.KEY_PRESS_MASK); // Actually I don't know how this works
auto callback_func = cast(bool delegate(Event,Widget))&get_key; // I doubt this cast
this.addOnKeyPress(callback_func);
showAll();
}
bool get_key(GdkEventKey* ev, Widget widget){
writefln("sender %s", widget);
writefln("type %x",ev.type);
writefln("window* %x",ev.window);
writefln("send_event %x",ev.sendEvent);
writefln("time %x",ev.time);
writefln("state %x",ev.state);
writefln("keyval %x",ev.keyval);
writefln("length %x",ev.length);
writefln("gchar* %x",ev.string);
writefln("hardware_keycode %x",ev.hardwareKeycode);
writefln("group %x",ev.group);
writefln("is_modifier %x\n",ev.bitfield0);
return true;
}
}
void main(string[] args){
Main.init(args);
auto win = new Window();
Main.run();
}
Yes, that cast is wrong. I guess that Signature with GdkEventKey* is outdated. Change your get_key to take an Event and you should get proper results:
...
auto call = &get_key;
...
bool get_key(Event e, Widget widget){
GdkEventKey* ev = e.key();
...
I have never done anything with GtkD, and this is just the result of some glances over the docs. So, it's probably not best practice, but it should get you back on the road.

Call a method of a web component and respond to events

I'm working on a Dart project where I have created a custom element with the Web_ui package that has some animation. What I was hoping to do is to have within the dart code for the element something like this....
class MyElement extends WebComponent {
...
void StartAnimation() { ... }
...
}
and then in the main() function of the dart app itself I have something like this...
void main() {
MyElement elm = new MyElement();
elm.StartAnimation(); // Kicks off the animation
}
The Dart editor tells me that Directly constructing a web component is not currently supported. It then says to use WebComponent.forElement -- but I'm not clear on how to use that to achieve my goal.
While you can't yet import web components into a Dart file, you can access them via query() and .xtag. xtag gives you a reference the web component instance that the element is associated with. You do have to be careful that you allow the Web UI setup to complete so that xtag is given a value.
Here's an example:
import 'dart:async';
import 'dart:html';
import 'package:web_ui/web_ui.dart';
main() {
Timer.run(() {
var myElement = query('#my-element').xtag;
myElement.startAnimation();
});
}
This will get better with the ability to import components, directly subclass Element and maybe some lifecycle events that guarantee that you get the correct class back from a query(). This is what the exemple should look like in the future:
import 'dart:async';
import 'dart:html';
import 'package:web_ui/web_ui.dart';
import 'package:my_app/my_element.dart';
main() {
MyElement myElement = query('#my-element');
myElement.startAnimation();
}

Record Actions using Selenium

I have a semi-vague question to ask about Selenium. I've discovered a few different ways to perform actions using the FirefoxDriver. What I need to do is repeat actions that a user performs on a web page (clicking a link, checking a checkbox, etc.). Is there any method or combination of methods that allows me to "record" the user's actions? Here is what I have so far to perform actions (you'll notice I've tried using the WebDriverBackedSelenium and Actions classes to perform actions)
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriverBackedSelenium;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.interactions.Action;
public class MyReplayer {
public static void main(String[] args) throws Exception {
// The Firefox driver supports javascript
FirefoxDriver driver = new FirefoxDriver();
driver.get("http://www.cs.umd.edu");
List<WebElement> elements = driver.findElements(By.tagName("a"));
//WebDriverBackedSelenium driverBacked = new WebDriverBackedSelenium(driver, "http://www.cs.umd.edu");
Actions builder = new Actions(driver);
Action clickLink = builder.click(elements.get(100)).build();
clickLink.perform();
//driverBacked.click("document.getElementsByTagName('a')[100]");
}
}
I came across Huxley. It allows recording and playback of user actions. I found this question in search of how they did it, but had to resort to source code.
Lines 98-154 of huxley/run.py define the record function. It uses webdirvier to execute some js on the page which adds some event listeners. It also adds a function to return the events.
(function() {
var events = [];
window.addEventListener('click', function (e) { events.push([Date.now(), 'click', [e.clientX, e.clientY]]); }, true);
window.addEventListener('keyup', function (e) { events.push([Date.now(), 'keyup', String.fromCharCode(e.keyCode)]); }, true);
window._getHuxleyEvents = function() { return events; };
})();
To read the events the js function is called
events = d.execute_script('return window._getHuxleyEvents();')
Then the events are stored in a way that seems application specific.
Sorry, I do not have Java code. I hope this helps.
You can use the Selenium IDE Addon for Firefox and export the generated test for Webdriver. It doesn't specifically say FirefoxDriver, but the methods of the interface look similar to what you posted. I hope this helps.
I am currently working on a project that does something like this: https://github.com/hristo-vrigazov/selenium-record-replay
It works by putting a proxy between the browser and the application, and injecting javascript which listens for actions that you have defined. See for example https://github.com/hristo-vrigazov/selenium-record-replay/blob/master/terminator-cli/src/main/java/browser/Main.java#L74
RecordBrowserBase recordBrowserBase = new ChromeRecordBrowser(pathToChromedriver, pathToJSInjectionFile);
try {
recordBrowserBase.record(baseUrl);
System.out.println("Press Enter when finished recording");
System.in.read();
recordBrowserBase.dumpActions(outputFile);
} catch (IOException | InterruptedException | URISyntaxException e) {
e.printStackTrace();
}
recordBrowserBase.cleanUp();
System.exit(0);
The project is still in a very early stage, but it can be used even now. Currently only Chrome is supported, but I will soon add other browsers as well.
Disclaimer: I am the creator and maintainer of the project

Resources