text:
Q: Particle simulation: understanding mass I'm trying to understand how mass factors into forces acting on particles in a simulation.
For the sake of argument, imagine a 1-dimensional simulation of a particle, whose position is 0 on the x-axis of this hypothetical 1D world.
If I implement a force/mass model, the particle's acceleration will be inversely proportionate to its mass, so if I give the particle a mass of 100 and push it with a force of 15, the resulting position on the x-axis after a single time step would be 0.15 (0 + 15 * (1/100)).
That all makes sense to me....heavier objects take more force to push.
However, what I'm failing to understand is what happens if my particle has a small mass. Imagine instead of a mass of 100, it has a mass of .00001. Using the same formula, its new position along the x-axis would be 1500000 (0 + 15 * (1/.00001)). That seems....wrong?
In real life, it makes sense that pushing a 2kg object takes twice the force of a 1kg object to go the same distance (and plugging those values into my formula yields that intuitive result)...but if I push a mote of dust with a tiny mass it doesn't soar halfway across the universe like the previous formula would suggest. I'm sure my error is obvious but I can't figure it out.
Any insights are appreciated!

A: You just aren't using the right equations of motion.
With mass $m$, force $F$, initial position $x_0$ and position after some time interval is $x_1$, you are using the equation
$$x_1=\frac Fm\left(x_0+\frac Fm\right)$$
Issues with the equation:

*

*No reference to a time interval (you would expect a larger distance to be covered if the force is applied over a longer time interval)

*The units don't match up (both between the left and right side as well as with the math on the right side)

*The equation is just not how position evolves over time due to a constant force

What you really want is the kinematic equation taught in introductory physics:$^*$
$$x_1=v_0\Delta t+\frac12a\left(\Delta t\right)^2$$
Or, using Newton's second law
$$x_1=x_0+v_0\Delta t+\frac12\frac Fm\left(\Delta t\right)^2$$
where $v_0$ is the initial velocity and $\Delta t$ is a time interval. This is the correct way to incorporate the mass into your analysis.

I was implying a time step of 1 for simplicity. Your solution still doesn't answer my question....tiny masses will result in huge distances traveled.

This is exactly correct. For the same force applied over the same time, the acceleration $a=\frac Fm$ is larger for smaller masses. Based on the equation above this means that the term $\frac12\frac Fm\left (\Delta t\right)^2$ is larger for smaller masses, which results in a larger distance traveled.
As for the time step being $1$, your original equation cannot be fixed by putting in a time interval.

$^*$Note that this is technically true for just the initial conditions for position $x_0$ and velocity $v_0$. If you are wanting to do things with time steps, then you can't keep adding this onto the position. In other words,
$$x_2\neq x_0+2\left (v_0\Delta t+\frac12\frac Fm\left(\Delta t\right)^2\right)$$
You would either do
$$x_2=x_0+v_0\left(2\Delta t\right)+\frac12\frac Fm\left(2\Delta t\right)^2$$
or you could do
$$x_2=x_1+v_1\Delta t+\frac12\frac Fm\left(\Delta t\right)^2$$
where $v_1$ it's given by another kinematic equation
$$v_1=v_0+\frac Fm\Delta t$$


text:
Q: iOS ABAddressBookCopyArrayOfAllPeople not displaying all contacts This is the code that i am using to fetch all the contact details in my iphone.It is working allright,But not all the contacts are displayed here.any idea why it is happening ? By using addresspicker,i can see all those missing names and numbers.
 -(void)viewWillAppear:(BOOL)animated
    {
        ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);

    __block BOOL accessGranted = NO;

    if (ABAddressBookRequestAccessWithCompletion != NULL)
    { // We are on iOS 6
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
            accessGranted = granted;
            dispatch_semaphore_signal(semaphore);
        });

        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
            }

    else { // We are on iOS 5 or Older
        accessGranted = YES;
        [self getContactsWithAddressBook:addressBook];
    }

    if (accessGranted) {
        [self getContactsWithAddressBook:addressBook];
    }

}

// Get the contacts.
- (void)getContactsWithAddressBook:(ABAddressBookRef )addressBook {

    contactList = [[NSMutableArray alloc] init];
    CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
    CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);

    for (int i=0;i < nPeople;i++) {
        NSMutableDictionary *dOfPerson=[NSMutableDictionary dictionary];

        ABRecordRef ref = CFArrayGetValueAtIndex(allPeople,i);

        //For username and surname
        ABMultiValueRef phones =(__bridge ABMultiValueRef)((__bridge NSString*)ABRecordCopyValue(ref, kABPersonPhoneProperty));

        CFStringRef firstName, lastName;
        firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
        lastName  = ABRecordCopyValue(ref, kABPersonLastNameProperty);
        [dOfPerson setObject:[NSString stringWithFormat:@"%@ %@", firstName, lastName] forKey:@"name"];

        //For Email ids
        ABMutableMultiValueRef eMail  = ABRecordCopyValue(ref, kABPersonEmailProperty);
        if(ABMultiValueGetCount(eMail) > 0) {
            [dOfPerson setObject:(__bridge NSString *)ABMultiValueCopyValueAtIndex(eMail, 0) forKey:@"email"];

        }

        //For Phone number
        NSString* mobileLabel;

        for(CFIndex i = 0; i < ABMultiValueGetCount(phones); i++) {
            mobileLabel = (__bridge NSString*)ABMultiValueCopyLabelAtIndex(phones, i);
            if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel])
            {
                [dOfPerson setObject:(__bridge NSString*)ABMultiValueCopyValueAtIndex(phones, i) forKey:@"Phone"];
            }
            else if ([mobileLabel isEqualToString:(NSString*)kABPersonPhoneIPhoneLabel])
            {
                [dOfPerson setObject:(__bridge NSString*)ABMultiValueCopyValueAtIndex(phones, i) forKey:@"Phone"];
                break ;
            }

        }
        [contactList addObject:dOfPerson];

    }
    NSLog(@"Contacts = %@",contactList);
    [self.tableView reloadData];
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to detect corner of shapefile in python Is there any way to detect corner of each shapefile in python !? (not BBox)
Or somehow to detect the edges?

I want to detect each shapefile vertices to calculate the differences in latitude for my program.
I've got some idea for that:

*

*Loop over the points going round the polygon and count the number of times the sign of the difference in latitude between point i and i+1 changes.

*Calculate consecutive three points angle, then pick four sharpest angles

A: As many users stated this question has no distinct answer. The results of an analysis may incomplete or fetch the wrong points, dependent on the definition of what should be considered as a corner.
The simplest possibility would be the comparison of angles between adjacent points. As this question is familiar with this I will pick up this code fragment.
import shapefile
from math import atan2

# this is the most critical value, and it might be NOT possible to
# find a distinct value for all shapes; in radians
threshold = 0.5

# the input polygons
sf = shapefile.Reader(r'banana.shp')

# for identified corner points
pf = shapefile.Writer(shapefile.POINT)
pf.field('FID')

shapes = sf.shapeRecords()
for shp in shapes:
    x0, y0 = shp.shape.points[0]
    x1, y1 = shp.shape.points[1]
    az1 = atan2(y1 - y0, x1 - x0)

    for i in range(2, len(shp.shape.points)):
        xi, yi = shp.shape.points[i]
        azi = atan2(yi - y1, xi - x1)

        if abs(azi - az1) > threshold:
            pf.point(x1, y1)
            pf.record(i)

        az1 = azi
        x1, y1 = xi, yi

    xi, yi = shp.shape.points[1]
    azi = atan2(yi - y1, xi - x1)
    if abs(azi - az1) > threshold:
        pf.point(x1, y1)
        pf.record(1)

pf.save('corners')

Simple test case with threshold 0.5 radians (-1 < x, y < 1, EPSG: 4326):


text:
Q: How to calculate output length for PHP Mcrypt Rijndael 256 CBC I want to use a plug-in for cakephp to store encrypted data in the database. But I want to calculate how much length is necessary for database fields.
Here is the encryption code of the plugin:
return base64_encode(
     mcrypt_encrypt(
          MCRYPT_RIJNDAEL_256, md5($settings['key']
     ), $value, MCRYPT_MODE_CBC, md5(md5($settings['key']
))));

For instance how much field length is necessary for 2000 lengthed raw string input? VARCHAR(?)
If you need more details here is the
All Plug-in Code:
https://github.com/jmillerdesign/Cipher-Behavior-for-CakePHP/blob/master/Model/Behavior/CipherBehavior.php

A: I think the estimated answer is, source string length + 35% (of source str length).
I did a test like this to find the answer:
$key = 'really long key hello world';

// Source String
$str = '';
for ($i = 1; $i <= 2000; $i++) {
    $str .=  'x';
}
$slength = strlen($str);
echo 'source str length = '. $slength."
";
$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $str, MCRYPT_MODE_ECB));

$elength = strlen($encrypted);
echo 'encrypted str length = '. $elength."
";

echo 'diff = '. (($elength - $slength)/$slength) * 100 .'%';

Outputs:
source str length = 2000
encrypted str length = 2688
diff = 34.4%

source str length = 20000
encrypted str length = 26668
diff = 33.34%

Instead of using a fixed varchar, why don't you use the field type text?

A: Use CakePHP's Security::encrypt() method instead, as it is using Rijndael-256 out of the box. Rijndael ciphers are a variable length depending on the key used, so a VarChar will not work. The ciphertext is binary data and there's no need to encode it, so you would use a BLOB field instead.


text:
Q: How Can I Create a MySQL Function to Check JSON Validity? I'm fairly new to MySQL but I'd like to create a function to validate a JSON objects that are stored in my database tables.
I looked up information on creating a function, but must be missing something as I can't seem to get it to work. It doesn't seem like it would be overly complicated but perhaps I'm not using the appropriate syntax.
Here is my code:
DELIMITER //

CREATE FUNCTION CHECKJSON( DB_NAME varchar(255), TABLE_NAME varchar(255),    JSON_COLUMN varchar(255))
RETURNS varchar(300)
BEGIN
    DECLARE notNullCount int;
    DECLARE validJSONCount int;
    DECLARE result varchar(300);

    SET notNullCount = (SELECT count(*) FROM DB_NAME.TABLE_NAME WHERE JSON_COLUMN IS NOT NULL);
    set validJSONCount = (SELECT count(*) FROM DB_NAME.TABLE_NAME WHERE JSON_VALID(JSON_COLUMN) > 0);

    CASE
        WHEN (validJSONCount = notNullCount) THEN
            SET result = CONCAT('VALID JSON COUNT: ', validJSONCount)
        ELSE
            SET result = CONCAT('INVALID JSON COUNT: ', (notNullCount - validJSONCount))
    END;
    RETURN result;
END //

DELIMITER ;

When I try to run this code, I get the following error message:
"Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ELSE      SET result = CONCAT('INVALID JSON COUNT: ', (notNullCount - validJSONC' at line 14"
Any thoughts on how I might improve this code? Thanks!

A: Since MySQL 5.7 you have a pretty and simple function for this:

JSON_VALID(value)
Returns 0 or 1 to indicate whether a value is valid JSON. Returns NULL if the argument is NULL.

https://dev.mysql.com/doc/refman/5.7/en/json-attribute-functions.html#function_json-valid

A: You're missing a couple of ; and to end the case it should be END CASE.

DELIMITER //

CREATE FUNCTION CHECKJSON( DB_NAME varchar(255), TABLE_NAME varchar(255),    JSON_COLUMN varchar(255))
RETURNS varchar(300)
BEGIN
    DECLARE notNullCount int;
    DECLARE validJSONCount int;
    DECLARE result varchar(300);

    SET notNullCount = (SELECT count(*) FROM DB_NAME.TABLE_NAME WHERE JSON_COLUMN IS NOT NULL);
    set validJSONCount = (SELECT count(*) FROM DB_NAME.TABLE_NAME WHERE JSON_VALID(JSON_COLUMN) > 0);

    CASE
        WHEN (validJSONCount = notNullCount) THEN
            SET result = CONCAT('VALID JSON COUNT: ', validJSONCount) ;
        ELSE
            SET result = CONCAT('INVALID JSON COUNT: ', (notNullCount - validJSONCount)) ;
    END CASE;
    RETURN result;
END //

DELIMITER ;


text:
Q: iOS UIActivityViewController using UIActivityItemProvider "forgets" items I have a larger app that should be able to share multiple images.
I implemented this using UIActivityViewController and UIActivityItemProvider to have asynchronous usage of the items (so that i only have to prepare one image at a time and not have to fill the memory with all of them at once to share them).
I was "inspired" by the Apple Airdrop example:
AirdropSample download
However when using my app to share e.g. 9 images (to camera Roll == "Save 9 images") only 4 to 7 images end up being in the camera roll, no error messages whatsoever.
If i repeat it over and over sometimes i get 5 images or 6 seemingly random.
I cannot post my app here, but i modified the above sample in a way that it will also randomly "fail" with delivering all images to the camera Roll...
If you download above sample and replace 4 files with these, it shows the problem:
APLAsyncImageViewController.h:
#import <UIKit/UIKit.h>
#import "APLAsyncImageActivityItemProvider.h"

@interface APLAsyncImageViewController : UIViewController
@end

APLAsyncImageViewController.m:
#import "APLAsyncImageViewController.h"
#import "APLProgressAlertViewController.h"

NSString * const kProgressAlertViewControllerIdentifier = @"APLProgressAlertViewController";

@interface APLAsyncImageViewController ()

@property (strong, nonatomic) UIWindow *alertWindow;
@property (strong, nonatomic) APLProgressAlertViewController *alertViewController;
@property (strong, nonatomic) UIPopoverController *activityPopover;

@property (weak, nonatomic) IBOutlet UIButton *shareImageButton;

- (IBAction)openActivitySheet:(id)sender;

@end

@implementation APLAsyncImageViewController

- (IBAction)openActivitySheet:(id)sender
{
    NSMutableArray *itemArray = [[NSMutableArray alloc] init];
    for( int i = 0; i < 9;i++)
    {
        APLAsyncImageActivityItemProvider *aiImageItemProvider = [[APLAsyncImageActivityItemProvider alloc] init];
        [itemArray addObject: aiImageItemProvider];
    }

    //Create an activity view controller with the activity provider item. UIActivityItemProvider (AsyncImageActivityItemProvider's superclass) conforms to the UIActivityItemSource protocol
    UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:itemArray applicationActivities:nil];

    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        //iPhone, present activity view controller as is
        [self presentViewController:activityViewController animated:YES completion:nil];
    }
    else
    {
        //iPad, present the view controller inside a popover
        if (![self.activityPopover isPopoverVisible]) {
            self.activityPopover = [[UIPopoverController alloc] initWithContentViewController:activityViewController];
            [self.activityPopover presentPopoverFromRect:[self.shareImageButton frame] inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
        }
        else
        {
            //Dismiss if the button is tapped while pop over is visible
            [self.activityPopover dismissPopoverAnimated:YES];
        }
    }
}
@end

APLAsyncImageActivityItemProvider.h:
#import <UIKit/UIKit.h>
@interface APLAsyncImageActivityItemProvider : UIActivityItemProvider
@end

APLAsyncImageActivityItemProvider.m:
#import "APLAsyncImageActivityItemProvider.h"
#import "UIImage+Resize.h"

@implementation APLAsyncImageActivityItemProvider

- (id)activityViewControllerPlaceholderItem:(UIActivityViewController *)activityViewController
{
    return [[UIImage alloc] init];
}

- (id)item
{
    UIImage *image = [UIImage imageNamed:@"Flower.png"];

    //CGSize imageSize;
    //imageSize.height = 1000;
    //imageSize.width = 1000;
    //image = [UIImage imageWithImage:image scaledToFitToSize:imageSize];

    return image;
}

- (UIImage *)activityViewController:(UIActivityViewController *)activityViewController thumbnailImageForActivityType:(NSString *)activityType suggestedSize:(CGSize)size
{
    //The filtered image is the image to display on the other side.
    return [[UIImage alloc] init];
}

@end

If you execute the sample like this (Use menu item "Send Image After Preprocessing", press "SHARE" Button) it will often or mostly fail to deliver all 9 images to the camera roll.
IF you uncomment the 4 lines in "APLAsyncImageActivityItemProvider.m" that basically just scale the output image THEN it will work ALWAYS.
Can you tell me why ? I feel that if i know the answer to that riddle i can also fix my app.
Thank you,
Nils

A: The reason for this issue is pretty simple.
There are limited number of writer threads available to use by the app, so writing too many images simulteneously may fail due to "Write Busy" error. You can verify that by trying to manually write these images using UIImageWriteToSavedPhotosAlbum (or corresponding Asset/Photos framework counterparts).
So, resizing images just hides the real problem because writing a smaller image takes less time.
The problem can be solved by liming the number of writers and/or retrying in case of error.
Also note that -[UIActivityItemProvider item] is a blocking call, but there are no synchronous ways to write to the gallery out of the box. This can be handled with dispatch_semaphore_wait , NSCondition, etc.
Or, in case you're using ReactiveCocoa, by simply calling waitUntilCompleted.

A: I would go to say that the [UIImage imageWithImage:image scaledToFitToSize:imageSize] image created is GC before saved to camera roll, but I don't know what is going on in that method without the code.  That method is not a normal UIImage method, a category maybe?
EDIT
Replace your for loop code adding to your item array with this code, and then uncomment your resize lines, and see if that works.
NSMutableArray *itemArray = [[NSMutableArray alloc] init];
for( int i = 0; i < 9;i++)
{
    UIImage *aiImage = [[[APLAsyncImageActivityItemProvider alloc] init] image];
    [itemArray addObject:aiImage];
}


text:
Q: Agent Analyst - Arc 10.5 Refresh has stopped working, config file issue? I'm going through the Agent Analyst EsriPress exercises and cannot get the model to change the ArcGIS agent layer (positions) during a simulation run through the updateDisplay() function within Agent Analyst. I'm using ArcGis 10.5.
I've attempted the fixes described in Agent Analyst tool interface will not open on ArcGIS for Desktop?
but have not had any success getting past exercise 2f (moving agents). Tool will run once and then I get a popup saying "Refresh has stopped working." When I change the Refresh.exe.config file to 10.5.0.0, Refresh appears once. I tried changing it to 10.5.0.6491 (my current version), the refresh error flashes quickly.
Steps Executed:

*

*Created Refresh.exe.config file with a text editor and saved it along with Refresh.exe (in C:\Repast 3\Agent Analyst\Refresh). The Refresh.exe.config contents are identical to the contents of the configuration file described here ArcGIS 10.1 using Repast's Agent Analyst Extension - refresh.exe does not work.  Replaced newVersion="10.1.0.0" with newVersion="10.5.0.0"

*Edited the agent_analyst.bat and agent_analyst_run.bat files in the installation folder (C:\Repast 3\Agent Analyst) so that the folder paths contain Desktop10.5 in the folder path strings.

*Edited Environment Variables to make sure that ARC_JAVA, ARC_JAVAW, and ARCOBJECTS_JAR have a fully specified paths entered for each variable.

*In my Environment Variables, I moved ARC_JAVA (C:\Program Files (x86)\ArcGIS\Desktop10.5\java\jre\bin\java), ARC_JAVAW (C:\Program Files (x86)\ArcGIS\Desktop10.5\java\jre\bin\javaw), ARCOBJECTS_JAR (C:\Program Files (x86)\ArcGIS\Desktop10.5\java\lib\arcobjects.jar), AGENT_ANALYST (C:\Repast 3\Agent Analyst), and AGENT_ANALYST_VOL (C:) from my User Variables to my System Variables.


text:
Q: Determinant of a portioned matrix If $A$ and $B$ are $n\times n$ matrices and $C$ is defined to be
$$
C=\begin{pmatrix}
O&A\\
B&O
\end{pmatrix}
$$
Where $O$ denotes the zero matrix.
Can I conclude that $O$ needs to be only square matrix of size $n\times n$ because if $O$ has any other size, then it does not make sense?
Can I also then say that $\det(C)=-\det(A)\det(B)$?
If I am wrong, then can you explain why?

A: Consider the example where $A$ and $B$ are both the $2\times2$ identity matrix.  Then you may calculate that $\det(C)$ is $1$, which is not $-\det(A)\det(B)$.  In fact we have in general
$$\det(C)=(-1)^n\det(A)\det(B)\ .$$
Reason: use row-reduction.  If we interchange rows $n$ times we get
$$\det(C)=(-1)^n\det\pmatrix{B&O\cr O&A\cr}\ ,$$
and it's not too hard to show that the matrix on the RHS has determinant $\det(A)\det(B)$.

A: Yes, in your situation $O$ has to be $n\times n$. As for the determinant,
$$
\det C=(-1)^n\,\det(A)\,\det(B).
$$
This is because
$$
\begin{bmatrix}O&A\\ B& O\end{bmatrix}=\begin{bmatrix}O&I\\  I& O\end{bmatrix}\,\begin{bmatrix}B&O\\ O&A\end{bmatrix}
$$


text:
Q: Jetpack compose deep link into nested navigation according to the recommendation of Android developers it is recommended to use nested navigation for the growing project
NavHost(navController, startDestination = "home") {
    ...
    loginGraph(navController)
    ...
}

fun NavGraphBuilder.loginGraph(navController: NavController) {
    navigation(startDestination = "username", route = "login") {
        composable("username") { ... }
        composable("password") { ... }
        composable("registration") { ... }
    }
}

but what should i do to be able to deep link into the navigation within navigation like in this example in order to go to the "username" composable
I've already managed to do the normal deep link like what is shown in the developer page
would it be better to surround the within nested navigation with a composable and put the deep link in there?
NavHost(navController, startDestination = "home") {
    ...
    val deeplinkuri = "..."
    composable(
        route="loginGraphScreen",
        deepLinks = listOf(navDeepLink {
                    uriPattern = deeplinkuri
                }),
    ){
        loginGraph(navController)
    }
    ...
}

A: I can't do a nested graph with deep link, so i just make it like an extension of the NavGraphBuilder
it still does the job of making the code more easier to managed while having deep link
fun NavGraphBuilder.loginGraph(navController: NavController) {
    composable("username", deepLinks= ....) { ... }
    composable("password") { ... }
    composable("registration") { ... }
}


text:
Q: Flutter RequestNode The last days I tried to implement fixes I found here on stackoverflow, but they all do not work. I think this is caused of the unnormal storyline:

*

*I have a screen with Textfields

*By click on the FloatingActionButton a popup appears, where the user can click on buttons

*With click on a button I set a bool to true (for example: textfield1 = true)

*This triggers a TextField on my screen ( if (textfield1== true) {TextField()}
This all works fine, the problem is, that I want to change the focus on this new TextField:

So I added this:
textfield1=true; _focusTextField1();

with
void _focusTextField1() { FocusScope.of(context).requestFocus(textfield1Node);}

Now the TextField has the focus (the border gets blue), but the textmarker doesn't appear (I hope textmarker is the right word, I mean this " | " which also triggers the keyboard.)
I have to click on the button (FloatingActionButton--> Popup-->Button) twice, to trigger this textmarker / keyboard.
Than I found this solution:
   void initState() {
super.initState();
  WidgetsBinding.instance.addPostFrameCallback((_) => _focusTextField1());

This also doesn't work. The next problem would be, that I have to implement this addPostFrameCallback for every possible new TextField the user can create, but in the description of the addPostFrameCallback it says that only the last callback will be triggerd, means: Everytime I create a new TextField the TextField which has the last Callback in may initState() will be focused.
Thanks for your help!
(I provided all relevant code, I think if I provide all the code this would be confusing)

A: I think what you need is FocusNode:
https://flutter.dev/docs/cookbook/forms/focus
U can create:
  FocusNode myFocusNode;

  @override
  void initState() {
    super.initState();

    myFocusNode = FocusNode();
  }

and add this to your TextField:
  TextField(
    focusNode: myFocusNode,
  ),

So, when u need to request focus, call: myFocusNode.requestFocus()


text:
Q: Static website note showing up on google cloud platform I have followed the instructions given on https://cloud.google.com/storage/docs/hosting-static-website, yet my domain name still lands on the page with this error:

This site can't be reached
  afrikincm.com's server IP address could not be found.
  Search Google for afrikincm
  ERR_NAME_NOT_RESOLVED

My doamin registrar is goDaddy.com and  all i did there was:
see godaddy dashboard
All objects added to my bucket on Google Cloud Platform have been made public yet something still doesn't seem to be working right.
I really will appreciate some help here guys.
Thanks

A: It seems that something is wrong and somewhere down the line and the DNS record is not resolving to the content of your gcs bucket.
First of all, be sure that the bucket name is exactly the value that you are specifying as CNAME.
Then review and re-take the steps suggested in the documentation.

*

*Make sure that billing is enabled

*Verify that you own and manage the domain that you'll be using: webmaster central

*Create a CNAME record that points to c.storage.googleapis.com

*Create a bucket whose name matches the CNAME you created for your domain

*put files in your bucket (like an index.html)

*make all object public with gsutil iam ch allUsers:objectViewer gs://[BUCKET_NAME]

*setup index + error page with: gsutil web set -m index.html -e 404.html gs://[BUCKET_NAME]

Judging from the error, it seems that something is wrong with the godaddy records or the bucket name or the verification step :)


text:
Q: jQuery Uncaught TypeError but works on different page I'm getting the following error message in my console:

This is from this webpage: http://mylzh.net/isaacBingo.php?seed=2jrxjc
However on the original page it works: http://mylzh.net/bingo/bindingofisaac/index.html?seed=2jrxjc

A: It is because of the following code
$("#bingo tr td:not(.bingo_select), #selected td").toggle(function () {
    $(this).addClass("greensquare");
}, function () {
    $(this).addClass("redsquare").removeClass("greensquare");
}, function () {
    $(this).removeClass("redsquare");
});

This version of .toggle() was removed in jQuery 1.9.
While executing this code jQuery assumes it to be the version that takes 3 params like .toggle( duration [, easing ] [, complete ] ), so it considers the second argument(a function) as easing value and uses it internally like
return this.pos = b = this.options.duration ? o.easing[this.easing](a, this.options.duration * a, 0, 1, this.options.duration) : a, this.now = (this.end - this.start) * b + this.start, this.options.step && this.options.step.call(this.elem, this.now, this), c && c.set ? c.set(this) : Kb.propHooks._default.set(this), this

As a solution look at the toggleClick() plugin


text:
Q: Question related to formulas for $f_a(s)=(2\ a)^{-s} \left(\zeta\left(s,\frac{1}{2\ a}\right)-\zeta\left(s,\frac{1}{2\ a}+\frac{1}{2}\right)\right)$ This question is related to the function $f_a(s)$ defined in formula (1) below with the infinite series representation defined in formula (2) below where $a$ is a positive integer. Note that $a=1$ corresponds to the Dirichlet eta function $\eta(s)$, and $a=2$ corresponds to the Dirichlet beta function $\beta(s)$.

(1) $\quad f_a(s)=(2\ a)^{-s} \left(\zeta\left(s,\frac{1}{2\ a}\right)-\zeta\left(s,\frac{1}{2\ a}+\frac{1}{2}\right)\right)$
(2) $\quad f_a(s)=\underset{K\to\infty}{\text{lim}}\left(\sum\limits_{n=0}^K \frac{(-1)^n}{(a\ n+1)^s}\right)\ ,\quad\Re(s)>0$

I believe the infinite series defined in formula (3) below is valid for all $s$, and the finite series defined in formula (4) below is valid at $s=-K$ where $K$ is a non-negative integer. Formulas (3) and (4) below are based on a conjectured formula for the Dirichlet eta function $\eta(s)$ which I previously defined in formula (1) of this question.

(3) $\quad f_a(s)=\underset{K\to\infty}{\text{lim}}\left(\frac{1}{2^{K+1}}\sum\limits_{n=0}^K \frac{(-1)^n }{(a\ n+1)^s}\sum\limits_{k=0}^{K-n} \binom{K+1}{K-n-k}\right)$
(4) $\quad f_a(-K)=\frac{1}{2^{K+1}}\sum\limits_{n=0}^K (-1)^n (a\ n+1)^K \sum\limits_{k=0}^{K-n} \binom{K+1}{K-n-k}\ ,\quad K\in\mathbb{Z}\land K\ge 0$

I believe formula (3) above is exactly equivalent to formula (5) below for all values of $s$, all non-negative integer values of $K$, and all positive integer values of $a$; and also formula (4) above is exactly equivalent to formula (6) below. Formulas (5) and (6) below are based on this well-known formula  for the Dirichlet eta function $\eta(s)$.

(5) $\quad f_a(s)=\underset{K\to\infty}{\text{lim}}\left(\sum\limits_{n=0}^K \frac{1}{2^{n+1}}\sum\limits_{k=0}^n \frac{(-1)^k\ \binom{n}{k}}{(a\ k+1)^s}\right)$
(6) $\quad f_a(-K)=\sum\limits_{n=0}^K \frac{1}{2^{n+1}}\sum\limits_{k=0}^n (-1)^k\ \binom{n}{k}\ (a\ k+1)^K\ ,\quad K\in\mathbb{Z}\land K\ge 0$

Note formulas (3) and (4) above have the exponentiation operation in the outer sum whereas formulas (5) and (6) above have the exponentiation operation in the inner nested sum which leads to formulas (3) and (4) having fewer exponentiation operations and faster evaluation times.

Question: Is it true formula (3) above is a globally convergent infinite series representation of the function $f_a(s)$ defined in formula (1) above for all positive integer values of $a$, and formula (3) above is exactly equivalent to formula (5) above for all values of $s$, all integer values of $K\ge 0$, and all integer values of $a>0$?

Side-note:

I've read arithmetic statements can be encoded in terms of Binomial coefficients (see Encodings of arithmetic (by different operations)). This observation along with Godel's first incompleteness theorem seems to imply there may be some true statements involving Binomial coefficients that are impossible to prove, and I'm wondering whether the equivalence of formulas (3) and (5) above is perhaps an example.

The following figures illustrate formula (3) above for $f_a(s)$ for several values of $a$ in orange overlaid on the reference function $f_a(s)$ defined in formula (1) above in blue where formula (3) is evaluated at $K=100$.

Figure (1): Illustration of formula (3) for $f_1(s)=\eta(s)$ in orange overlaid on the blue reference function

Figure (2): Illustration of formula (3) for $f_2(s)=\beta(s)$ in orange overlaid on the blue reference function

Figure (3): Illustration of formula (3) for $f_3(s)=6^{-s} \left(\zeta \left(s,\frac{1}{6}\right)-\zeta \left(s,\frac{2}{3}\right)\right)$ in orange overlaid on the blue reference function


text:
Q: Let $E$ be a normed space, $(X,d)$ a metric space and $A \subset E$ a convex bounded set. Show that $f(A)$ is bounded.
Let $E$ be a normed space, $(X,d)$ a metric space and  $A \subset E$ a convex bounded set. Let $f : A \to X$ be uniformly continuous. Show that $f(A)$ is bounded.

I'm trying to find the right definitions to use here. If $A$ is bounded then for every $x,y \in A$ we have that $[x,y] \in A$. Also  if $A$ is bounded then $d(A) = \sup\{d(x,y) \mid x,y \in A \} < \infty$. So  what I want to show is that $d(f(A)) = \sup\{d(x,y), \mid x,y \in f(A) \} < \infty$? I'm not sure what I should do with the fact that $A$ is convex? From uniform continuity I get that all close points stay close to each other, but not sure that is of help?

A: Hint: Fix a point $x_0\in A$. Then we have for all $x\in A$ and all $N\in \mathbb{N}_{>0}$
$$ d(f(x_0), f(x)) \leq \sum_{j=1}^N d\left( f(x_0+\frac{j-1}{N}(x-x_0)), f(x_0+\frac{j}{N}(x-x_0)) \right).$$
Now use the fact that $\vert x -x_0 \vert \leq C<\infty$ and the uniform continuity to get an estimate for $N$ sufficiently large.
Here I used the convexity to connect $x_0$ to $x$ by a straight line, which lies completely in $A$.
For general bounded sets this will not work. Take $E=\ell^2(\mathbb{N}, \mathbb{R})$ and $A= \{ e_j : \ j\in \mathbb{N} \}$, where $e_j=(0, \dots, 0, 1, 0, \dots)$ (the $1$ is the $j$th entry). Then any map is uniformly continuous (simply, because $\Vert e_j - e_k\Vert = \sqrt{2}$ for $j\neq k$). Clearly there are unbounded maps $f: A \rightarrow X$ if $X$ is unbounded (pick your favourite one to get a counterexample). Note that this is kind of the easiest example one can get as for finite dimensional normed spaces we have that bounded & closed sets are compact. In that setting we can continuously extend $f$ to the closure of $A$, however, as continous functions map compact sets to compact sets and in metric spaces compact sets are bounded, we get that $f(A) \subseteq f(\overline{A})$ is bounded.


text:
Q: Replacing existing layer's data with new geojson in Carto? I try to use CartoDB (https://carto.com/).
I created a layer with geojson file, but if the file is updated, how can I replace existing layer's data by new geojson?
I know, creating new layer and load new geojson, copying all styles and template settings from old layer to new and deleting old layer, is exactly same with replacing data.
But, "copying all styles and template settings from old layer to new" is very complicated task, so I want to replace just data only...
Do anyone know about how to do this?

A: If I understood you correctly, you have a map with a layer, and you want to replace the data of the current layer for data from a different dataset.
You can do this by going to the SQL tab of the layer in the map (in the right sided menu) and change the default query that calls the data in the layer:
SELECT * FROM tableA
And replace it for:
SELECT * FROM tableB
The data of tableB must be similar to data of tableA so there won't be problems in the styles.


text:
Q: how do i programaticly delete duplicate images? in magento I manage a big web store with alot of products, and some of the products weren't correctly imported and the images got duplicated.
the products just have 2 of the same images.
i know that you can delete them by hand but that would take up all my life of time.
i have searched the internet for some of the codes that can do it but they dont work for me.
is there anybody who know a solution for this?
I have tried to examine the codes that i got from the internet but i really can make them work.
this is one of the solutions that didn't work for me:
http://dltr.org/blog/magento/556/Magento-product-images-duplicate-issue-with-CSV-product-importer
i have tried to test this query in the sql database but that does not give any result:
SELECT * FROM `catalog_product_entity_media_gallery` WHERE value_id != value_id AND value=value

A: Here is a little script to find and delete all duplicate images in Magento.

//Mage::App('default');
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

error_reporting(E_ALL | E_STRICT);
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
ob_implicit_flush (1);

$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$_products = Mage::getModel('catalog/product')->getCollection();
$i =0;
$total = count($_products);
$count = 0;

foreach($_products as $_prod)
{
    $_product = Mage::getModel('catalog/product')->load($_prod->getId());
    $_md5_values = array();

    //protect base image
    $base_image = $_product->getImage();
    if($base_image != 'no_selection')
    {
        $filepath = Mage::getBaseDir('media') .'/catalog/product' . $base_image ;
        if(file_exists($filepath))
            $_md5_values[] = md5(file_get_contents($filepath));
    }

    $i ++;
    echo "\r\n processing product $i of $total ";

    // Loop through product images
    $_images = $_product->getMediaGalleryImages();

    if($_images)
    {
        foreach($_images as $_image)
        {
            //protected base image
            if($_image->getFile() == $base_image)
                continue;

        $filepath = Mage::getBaseDir('media') .'/catalog/product' . $_image->getFile();

            if(file_exists($filepath))
                $md5 = md5(file_get_contents($filepath));
            else
                continue;

            if( in_array( $md5, $_md5_values ))
            {
                $mediaApi->remove($_product->getId(), $_image->getFile());
                echo "\r\n removed duplicate image from ".$_product->getSku();
                $count++;
            }
            else
            {
                $_md5_values[] = $md5;
            }
        }
    }
}

http://www.aadil.co/how-to-delete-duplicate-product-images-in-magento/

A: Below is a snippet I have used earlier, this works like a charm
Actual link : http://blueclawecommerce.co.uk/blog/removing-duplicate-product-images-in-magento/
    include('app/Mage.php');
//Mage::App('default');
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
error_reporting(E_ALL | E_STRICT);
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
ob_implicit_flush (1);

$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$_products = Mage::getModel('catalog/product')->getCollection();
$i =0;
$total = count($_products);
$count = 0;
foreach($_products as $_prod)
{
    $_product = Mage::getModel('catalog/product')->load($_prod->getId());
    $_md5_values = array();

    //protected base image
    $base_image = $_product->getImage();
    if($base_image != 'no_selection')
    {
        $filepath =  Mage::getBaseDir('media') .'/catalog/product' . $base_image  ;
        if(file_exists($filepath))
            $_md5_values[] = md5(file_get_contents($filepath));
    }

    $i ++;
    echo "\r\n processing product $i of $total ";

    // Loop through product images
    $_images = $_product->getMediaGalleryImages();
    if($_images){
        foreach($_images as $_image){
            //protected base image
            if($_image->getFile() == $base_image)
                continue;

            $filepath =  Mage::getBaseDir('media') .'/catalog/product' . $_image->getFile()  ;
            if(file_exists($filepath))
                $md5 = md5(file_get_contents($filepath));
            else
                continue;

            if(in_array($md5, $_md5_values))
            {
                $mediaApi->remove($_product->getId(),  $_image->getFile());
                echo "\r\n removed duplicate image from ".$_product->getSku();
                $count++;
            } else {
                $_md5_values[] = $md5;
            }

        }
    }

}
echo "\r\n\r\n finished removed $count duplicated images";

A: I have a solution that you can adapt.
To delete them physically you need to run it with an import to be sure to have the good images at the end.
$_images = $product->getMediaGalleryImages();
if($_images){
    foreach($_images as $_image){
       $filepath =  Mage::getBaseDir('media') .'/catalog/product' . $_image->getFile()  ;
       check if the both images (the one to import and the one that is present on the server) have the same size else
    }
}

To delete from the database the image linked to a product (still during an import).
$query = "select value_id from catalog_product_entity_media_gallery where entity_id = ?";
$st = $cnx->prepare($query);
$st->execute(array($productId));
$row = $st->fetch();
while ($row !== false) {
    $values2delete[] = $row['value_id'];
    $row = $st->fetch();
}
$query = "delete from catalog_product_entity_media_gallery where value_id IN (". implode(',',$values2delete).")";
$st = $cnx->prepare($query);
$st->execute();

I do not use this two things in the same import so you need to marry them together. You can also fill the values2delete array during the check of the bad files.
I hope it helps


text: Q: Mongodb compass is not connecting with connection string from atlas I copied the connection string from atlas and input it in my mongodb compass but it is showing bad auth : Authentication failed. What could be happening and how do i fix this error?


text:
Q: Math in Uniswap UQ112xUQ112 library Can anyone explain how the math in this contract works?
    pragma solidity =0.5.16;

// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))

// range: [0, 2**112 - 1]
// resolution: 1 / 2**112

library UQ112x112 {
    uint224 constant Q112 = 2**112;

    // encode a uint112 as a UQ112x112
    function encode(uint112 y) internal pure returns (uint224 z) {
        z = uint224(y) * Q112; //never overflows
    }

    // divide a UQ112x112 by a uint112, returning a UQ112x112
    function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
        z = x / uint224(y);
    }
}

I am not able to understand how these two functions helps with fractions.
Thank you.

A: I converted the library to a contract and make the functions public to be able to interact in Remix
contract UQ112x112 {
    uint224 constant Q112 = 2**112;

    function encode(uint112 y) public pure returns (uint224 z) {
        z = uint224(y) * Q112; //never overflows
    }
    function uqdiv(uint224 x, uint112 y) public pure returns (uint224 z) {
        z = x / uint224(y);
    }
}

*

*encode function
function encode(uint112 y) internal pure returns (uint224 z) {
      z = uint224(y) * Q112; //never overflows
  }

This will shift the input value y by 112 bits to the left, effectively encoding it as a uint224 value. 1 bit shifting is equal to multiplying the number by 2. If I call encode(1)

If you convert the return int value to binary here, you get this
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

We are storing our input in uint224 without losing precision. In uniswap, prices are stored in uint224 so we are converting price input into the uin224

*

*uqdiv function just a simple division operation
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
   z = x / uint224(y);
}


text:
Q: Casting to a Generic Primitive class. Method runs without any exception, how and why? Here is a method in which I am casting an Object to a primitive type.
@SuppressWarnings("unchecked")
public <T> T fetchPrimitive(Object object, Class<T> clazz) {
    return (T)object;
}

It works fine as long as my Object is of same class as T (which is a primitive class like int, double etc.).
But, this method also runs without any exception when I provide wrong class to cast. Say if I provide the object as boolean (true/false) and clazz as int.class, then also this method runs and return (true/false) the actual Object.
I understand that Generics can not work on primitives. I just need to understand whats happening here when I am providing a primitive class as an argument and return type is Generic.
For example:
Object object = true;
Class clazz = int.class;

Object result = fetchPrimitive(object,clazz);
//result = true and result.getClass() is Boolean.
//I asked it to convert a boolean to int expecting an exception but seems that it simply ignored the casting?

From running the code, I understand that it's simply ignoring the casting when its a primitive class and returning whatever Object it is. I do not want it to be this way, I want it to throw an exception (ClassCastException) if wrong class is provided.

A: Since you've provided the clazz you can use Class::cast to get what you want:
public static <T> T fetchPrimitive(Object object, Class<T> clazz) {
    return clazz.cast(object);
}

If you only do a cast type erasure will transform your code into something like this:
public static Object fetchPrimitive(Object object, Class<Object> clazz) {
  return (Object) object;
}

This is absolutely valid.

A: This simply won't work for primitives due to the way JVM works. Since your return type is T, it gets erased to Object (as seen in Flown's answer) and even if you return a primitive it will be boxed back to Integer/Boolean/etc.
If you want the method to be able to return a primitive, it has to be specified in the return type, and there is no way for a method to return different primitives depending on the arguments. You'll have to have separate methods for each primitive, unfortunately, or live with boxing.


text:
Q: Replicate light effects with transparency as a medium of learning I try to replicate some things I see in the Internet. A friend of mine that knows what am I doing, saw a template and asked me to replicate part of it for his web page, I already have most of what I needed from the template, but the thing he liked the most I tried and failed and I am not understanding  what is the magic involved in this template...
What I need is to replicate the main sheet transparency and the light effect behind it, the transparency I made was with a black 1x1 png made on the GIMP(I can't buy the Photoshop) I also have a nice pattern like in the template since it is one of the things my friend asked...

this is the effect I want, I tried messing around with shadows, but didn't get what i wanted I ended up deleting the code, now all I have is this:
HTML:

CSS:
#light{
border:solid 0px white;
height:550px;
width:800px;
left:50%;
margin-top:130px;
margin-left:-400px;
z-index:-1000;
position:absolute;
box-shadow: 0px 0px 300px #929292;
border-radius:100px;
background-color:#929292;
opacity:0.4;
}
#box{
background-image:url(../images/shtr.png);
margin:0px auto 0px;
width:1060px;
height:auto;
border:solid 0px white;
}

i don't know if i need to use jquery or javascript, or if that would help in the page performance...

A: There are some CSS3 things you can do here.
The first thing you need to do is setup the divs with the texture and highlights. The div with the highlight should ideally be a child of the textured div.
HTML:

Next you need to apply the effects and backgrounds to the correct elements:
CSS:
.wrap
{
  background: url(http://wallpoper.com/images/00/35/83/02/pattern-patterns_00358302.jpg);
  height: 500px;
  width: 500px;
}

.transp
{
  position: relative;
  top: 20px;
  left: 30px;
  background: rgba(0, 0, 0, .7);
  height: 100px;
  width: 100px;
    box-shadow: 0px 0px 30px #fff;
}

http://jsfiddle.net/7fTAH/

A: I managed to get it done, i created a new div that casts a shadow, placed it outside of the screen(left:100%;) and the shadow is casted to the center with the color #CECECE the HTML code:

    ( ... content ... )

in the CSS :
#light{
position: absolute;
background: rgba(0, 0, 0, 0);
height: 800px;
width: 840px;
z-index:-1000;
opacity:0.15;
}

#box{
background-image:url(../images/shtr.png);/*black 50-60% transparent 1x1 image*/
margin:0px auto 0px;
width:1060px;
height:auto;
border:solid 0px white;
}

and to cast the shadow I used a jQuery script, via only css it wasn't working i don't know exactly why... the code:
$(document).ready(function() {
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;

    var A = -myWidth - 49.5*myWidth/60
    $("#brilho_grande").css("box-shadow", A+"px 0px 10000px 100px #CECECE");
    $("#brilho_grande").css("left", 2*myWidth+"px");
    $("#brilho_grande").css("top", "339px");
});


text:
Q: Updating BIOS File Build Date I am in the process of updating my laptop's BIOS to add support for a CPU however I ran into an issue when I tried to adjust the build date of the BIOS file. After adjusting the file from built in 2011 to 2012, just so it recognizes as new BIOS, MMTool says it is invalid. PLEASE HELP!

A: Thanks for the help but after many hours of searching I finally found what i was looking for and it did solve this. Instead of having to patch the BIOS's build date I had to disable Asus's date check in WinFlash with then correctly flashed the new BIOS. Thanks again.


text:
Q: Different Data Sources for RepositoryItemReader and RepositoryItemWriter I desperately need to know if I can use RepositoryItemReader and RepositoryItemWriter to accomplish for example transfer data from one database to another?
I can probably do it using JdbcPagingItemReader and JdbcBatchItemWriter since both have methods for setting dataSource (probably).
Please help.


text:
Q: Strange Update clause error (VB.NET) I'm experiencing a really strange error. I have a table with only two columns (User and pass , both with text type).
The program asks first, what column I want to modify. With a radio button , I point which column I want to modify.
By pressing any radio button, two text boxes appear . You have to enter the password and the new data to modify it.
The problem is that when making the modification , if I want to change the user column , all is work well... But if I want to change a thing of the Password column , release "update error clause".
Honestly, I do not see any error in this code:
Protected Friend Sub modificarAcesso(ByVal column As String, ByVal dato As String)
    Dim cmd As String = "Update Login SET " & column & "=@dato"
    Try
        con.Open()
        comando = New OleDbCommand(cmd, con)
        comando.Parameters.AddWithValue("@dato", dato)
        comando.ExecuteNonQuery()
        comando.Dispose()
        con.Close()
    Catch ex As Exception
        con.Close()
        MsgBox("Problemas en la consulta: " + ex.Message(), MsgBoxStyle.Critical)
    End Try
End Sub

A: Password is a keyword, so you must put it in brackets.  You should do this anyway if a column name has a space in it, too:
Dim cmd As String = "Update Login SET [" & column & "] = @dato"


text:
Q: How to compress directory using LZ4Net I need to compress a directory and its sub directories and files. First I tried with the native ZipFile.CreateFromDirectory but its slow. So I found LZ4 is the fast compression algorithm also found c# port lz4net. But I can't hardly find any tutorials for compress and decompress using lz4net.
Compression using LZ4Net (This is the only useful one I found on SO)
So how can I compress a directory using lz4net?


text:
Q: error NG6002: Appears in the NgModule.imports of AppModule, but itself has errors AppRoutingModule When I make: ionic cap build android --prod --release , I have this error :
Error: src/app/app-routing.module.ts:60:14 - error NG6002: Appears in the NgModule.imports of AppModule, but itself has errors

export class AppRoutingModule {}

I don't have this error when I just do : ionic cap build android. I try different proposition on forums but no one work
app-routing.module.ts :
    import { NgModule } from '@angular/core';
    import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
    import { TranslateService } from '@ngx-translate/core';

    const routes: Routes = [
    {
        path: 'HomePage',
        loadChildren: () => import('./pages/home/home.module').then(m => m.HomePageModule)
    },
    {
        path: 'IntroPage',
        loadChildren: () => import('./pages/intro/intro.module').then(m => m.IntroPageModule)
    },
    {
        path: 'HowPage',
        loadChildren: () => import('./pages/how/how.module').then(m => m.HowPageModule)
    },
    {
        path: 'AboutPage',
        loadChildren: () => import('./pages/about/about.module').then(m => m.AboutPageModule)
    },
    {
        path: 'SettingsPage',
        loadChildren: () => import('./pages/settings/settings.module').then(m => m.SettingsPageModule)
    },
    {
        path: 'ModalPage',
        loadChildren: () => import('./pages/modal/modal.module').then(m => m.ModalPageModule)
    },
    {
        path: '',
        redirectTo: 'HomePage',
        pathMatch: 'full'
    },
    ];

    @NgModule({
        imports: [
            RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
      ],
        exports: [RouterModule, TranslateService]
    })
    export class AppRoutingModule {}

app.module.ts :
    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { RouteReuseStrategy } from '@angular/router';
    import { HttpClientModule, HttpClient } from '@angular/common/http';

    import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
    import { IonicStorageModule } from '@ionic/storage-angular';

    import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
    import { TranslateHttpLoader } from '@ngx-translate/http-loader';

    import { AppComponent } from './app.component';
    import { AppRoutingModule } from './app-routing.module';

    import { GlobalProvider } from './providers/global/global';

    import { CMHPlugin } from '@ionic-native/cmh-plugin/ngx';

    export function createTranslateLoader(http: HttpClient) {
        return new TranslateHttpLoader(http, './assets/i18n/', '.json');
    }

    @NgModule({
        declarations: [AppComponent],
        imports: [
            HttpClientModule,
            BrowserModule,
            IonicModule.forRoot(),
            IonicStorageModule.forRoot(),
            AppRoutingModule,
            TranslateModule.forRoot({
                loader: {
                    provide: TranslateLoader,
                    useFactory: (createTranslateLoader),
                    deps: [HttpClient]
                },
                defaultLanguage: 'en',
            })
        ],
        providers: [GlobalProvider, CMHPlugin, { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }],
        bootstrap: [AppComponent]
    })
    export class AppModule {}

I use Ionic 6 and Angular 13. I can give more information/code if you need.

A: I remove TranslateService in export [] in app-routing.module.ts and it' works !


text:
Q: Could not reuse a function correctly on JavaScript I have a task to make a form validation, and all went seamlessly except for this one weird thing.
Basically, I have to show an error message below each input field if an error happened. The style for this error message has been made in the CSS file, so I just add necessary attribute when an error happened, like this:
//form validation onblur
//valid condition
var valid = true;
var message = "";

//function to add attribute to show error message
function showError(index) {
    formDataArr[index].setAttribute("data-error", message);
    formDataArr[index].setAttribute("data-error-visible", true);
};

//function to hide error when input is valid
function hideError(index) {
    formDataArr[index].removeAttribute("data-error");
    formDataArr[index].removeAttribute("data-error-visible");
};

So my idea is to use this function to show the error, and it works fine except for the last two elements for which the validation only happened when the submit button is clicked. Here is my validation on click code:
//function to validate form onsubmit
function validateForm () {
    valid = true;
    message = "";
    //first name validation
    validateFirstName();
    //last name validation
    validateLastName();
    //email validation
    validateEmail();
    //birthdate validation
    validateBirthdate();
    //quantity validation
    validateQuantity();

    //location radio button validation
    //Change the checkboxInput NodeList into an array
    var checkboxArray = Array.from(checkboxInput);
    //filter the checked input
    var checkboxInputChecked = checkboxArray.filter(input => input.checked);

    //put condition to check if a choice has been chosen
    if (checkboxInputChecked.length < 1) {
        valid = false;
        message = "Veuillez choisir une ville.";
        showError(5);
    } else {
        valid;
        hideError(5);
    };

    //T&C checkbox validation
    if (!checkbox1.checked) {
        valid = false;
        message = "Veuillez accepter les conditions d'utilisations."
        formDataArr[6].setAttribute("data-error", message);
        formDataArr[6].setAttribute("data-error-visible", true);
    } else {
        valid;
        hideError(6);
    };

    if (valid) {
        var successMessage = document.getElementById("formResult");
        var successMessageText = document.getElementById("formResultText");
        var message = "Merci ! Votre réservation a été reçu.";
        successMessageText.textContent = message;
        successMessage.style.display = "block";

    }
    return valid;
 };

You see in the location radio button validation (index 5), I tried to reuse the showError function, however, it wouldn't show the correct message, it will show the message from the index 4 instead. But, if I rewrite the whole code like on the index 6, it works fine. I failed to understand why is this happening and where do I do wrong with this function.
My github repo if you need further inspection: https://github.com/gndz07/GameOn-website-FR

A: It looks like you are using a global message variable, but I can't see if it is the same in the showError scope and in the validateForm scope. I suggest to NOT use the global variable, but to add an argument to showError.


text:
Q: Can't run WP e2e-test-utils because the browser exits on login? I'm trying to run e2e tests for my Gutenberg plugin. Here's my pertinent code
import {
  createNewPost,
  enablePageDialogAccept,
  insertBlock,
  clickButton,
} from "@wordpress/e2e-test-utils";

beforeAll(async () => {
  await enablePageDialogAccept();
});

describe("content editor basic functions", () => {
  test("ContentEditor shows up", async () => {
    await createNewPost();
    return true;
  });
});

I get the following stacktrace
Navigation failed because browser has disconnected!
    at /Users/nav/dev/wordpress-unified/plugins/my-plugin/node_modules/puppeteer/lib/cjs/puppeteer/common/LifecycleWatcher.js:51:147
    at /Users/nav/dev/wordpress-unified/plugins/my-plugin/node_modules/puppeteer/lib/cjs/vendor/mitt/src/index.js:51:62
    at Array.map (<anonymous>)
    at Object.emit (/Users/nav/dev/wordpress-unified/plugins/my-plugin/node_modules/puppeteer/lib/cjs/vendor/mitt/src/index.js:51:43)
    at CDPSession.emit (/Users/nav/dev/wordpress-unified/plugins/my-plugin/node_modules/puppeteer/lib/cjs/puppeteer/common/EventEmitter.js:72:22)
    at CDPSession._onClosed (/Users/nav/dev/wordpress-unified/plugins/my-plugin/node_modules/puppeteer/lib/cjs/puppeteer/common/Connection.js:247:14)
    at Connection._onMessage (/Users/nav/dev/wordpress-unified/plugins/my-plugin/node_modules/puppeteer/lib/cjs/puppeteer/common/Connection.js:94:25)
    at WebSocket.<anonymous> (/Users/nav/dev/wordpress-unified/plugins/my-plugin/node_modules/puppeteer/lib/cjs/puppeteer/node/NodeWebSocketTransport.js:13:32)
    at WebSocket.onMessage (/Users/nav/dev/wordpress-unified/plugins/my-plugin/node_modules/ws/lib/event-target.js:132:16)
    at WebSocket.emit (events.js:375:28)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:31025) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:31025) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I understand the browser is closed before the test can be run.. what can I do about it? I'm using @wordpress/e2e-test-utils@5.4.3


text:
Q: ERROR Appenders contains an invalid element or attribute "NoSql" I am getting ERROR Appenders contains an invalid element or attribute "NoSql", when I am trying to log message through log4j2 using NoSql appender. I have used below jar file in my classpath
log4j-core-2.9.1.jar
log4j-api-2.9.1.jar
mongo-java-driver-3.5.0.jar
log4j-nosql-2.9.1.jar
rpa-apis_1.0.jar
xercesImpl-2.9.0.jar
disruptor-3.3.7.jar
when I am running this java project with Eclipse, its working fine. But after creating runnable jar, I am getting error and no log going into MongoDB. I am using java -jar abc.jar to execute runnable jar. I have gone with Google, but not found something related. Providing Related Image file.
Please help to resolve the issue.

enter image description here

A: This error can happen when a Plugin cannot be found. From the sound of things you are building an uber jar. When building an uber jar with Log4j 2.x you need to mrege the Log4j2Plugins.dat files that are present in each jar. This [Stackoverflow question][1] provides a solution for that. You can also try Log4j2 3.0.0-SNAPSHOT. It packages the plugin descriptors in classes that are located using java.util.ServiceLoader. So long as the shading process supports merging multiple implementations of a service it should work fine.

A: This error can happen when a Plugin cannot be found. From the sound of things you are building an uber jar and either the plugin descriptor can't be found or the plugin class can't be located. When building an uber jar with Log4j 2.x you need to mrege the Log4j2Plugins.dat files that are present in each jar. This [Stackoverflow question][1] provides a solution for that. You can also try Log4j2 3.0.0-SNAPSHOT. It packages the plugin descriptors in classes that are located using java.util.ServiceLoader. So long as the shading process supports merging multiple implementations of a service it should work fine.
It should also be obvious but the relevant jars for the nosql and mongodb appender support would also be have to be included.

A: log4j2 doc Configuration Syntax, you can also add packages config to log4j2.xml.
Log4j – Configuring Log4j 2
enter link description here


text:
Q: How groovy closures work internally? A Java lambda can't modify variables in the surrounding scope (doesn't closes over). But how come Groovy closures can? What's its internal implementation?
For example, here, how come the closure can increment the outside variable i? Will an internal object be created for each iteration?
for (int i = 0; i < n;) {
    { -> i++ }.run()
}

A: In this case, i is boxed inside a mutable groovy reference. In Java, setting i would be changing a local variable of the method in which this loop resides. Which brings up a bunch of technical questions about what would happen if the function object leaves the method. But in groovy, i resides on the heap.
This explanation comes from the bytecode as I understand it, which you can get with the command:
javap -c <name of closure class>

Looking at the method doCall, first the CallSite object for the functor is looked up (since lambdas can share their classes, call sites are basically collections of captured local variables), and the specific i is retreived:
10: getfield      #29                 // Field i:Lgroovy/lang/Reference;

As you can see, the type of i is groovy.lang.Reference. Next, the number is incremented:
27: invokestatic  #51                 // Method org/codehaus/groovy/runtime/DefaultGroovyMethods.next:(Ljava/lang/Number;)Ljava/lang/Number;

After that, the result is loaded back into the groovy reference at:
42: invokevirtual #61                 // Method groovy/lang/Reference.set:(Ljava/lang/Object;)V

It would be similar to doing something like this in Java:
for (AtomicInteger i = new AtomicInteger(); i.get() < n;) {
    ((Runnable) () ->  System.out.println(i.getAndIncrement())).run();
}

Where I used AtomicInteger to represent a mutable int that resides on the heap, rather than in a local variable slot.


text:
Q: mean value theorem question I was trying to solve the following:
Given: $0 < a < b$ and $n>1$,
prove:
$$na^{n-1}(b-a) < b^n-a^n < nb^{n-1}(b-a)$$
I managed to get this far using the mean value theorem:
$$a^n(b-a)<b^n -a^n<b^n (b-a)$$
Any idea how to continue?

A: Here is a solution without the use of the mean value theorem:
All terms are divisible by $(b-a)$. For the middle term, this is seen by the following formula
$$
(b^{n-1}+ab^{n-2}+a^2b^{n-3}+\ldots+a^{n-3}b^2+a^{n-2}b+a^{n-1})(b-a)=b^n-a^n
$$
Since $b-a>0$, we can factor it out, and the inequalities become
$$
na^{n-1}<b^{n-1}+ab^{n-2}+a^2b^{n-3}+\ldots+a^{n-3}b^2+a^{n-2}b+a^{n-1}<nb^{n-1}.
$$
But this becomes almost trivial by using $a<b$ repeatedly on all terms in the expression in the middle.

A: Let $f(x)= x^n-a^n$ using the Mean Value Theorem
$$f'(c) = \frac{f(b)-f(a)}{b-a} = \frac{b^n - a^n}{b-a}$$ for some $c \in (a,b)$.
But $f'(c)= n \cdot c^{n-1}$ so
$$\frac{b^n - a^n}{b-a} = n \cdot c^{n-1}$$
Now note that $n \cdot a^{n-1} < n \cdot c^{n-1} < n \cdot b^{n-1}$ so
$$ n \cdot a^{n-1} < \frac{b^n - a^n}{b-a} < n \cdot b^{n-1}$$


text:
Q: Edit person.aspx? We have more than 1000 user profiles that need a customized person.aspx. We need to make quite big changes to person.aspx. What is best practice here ? Do we edit person.aspx via SharePoint designer or is it better to provision  a custom page layout and set it as welcome page ?
Is it possible to have features activate automatically when a new my site is created ?

A: The best practice is to

*

*Create a Visual Studio Solution.

*Then add your page layouts and other styling files.

*Create a feature receiver

*Use that to set the Page or create new page using the custom layout etc.

For existing site, you can deploy the solution and then use PowerShell to activate it on all the sites.


text:
Q: Detailed timings with Selenium and browermob proxy gives empty har file maybe someone can help me, I've searched for hours now and couldn't find a solution, on any site/blog/FAQ/...
I'm trying to get detailed timings for a page, with Selenium and Browsermob proxy. But the HAR file generated has always empty pageTitle, pageTimings and entries, like:

{"log":{"version":"1.2","creator":{"name":"BrowserMob Proxy","version":"2.0"},"pages":[{"id":"assertselenium.com","startedDateTime":"2014-08-26T15:45:49.134+0000","title":"","pageTimings":{}}],"entries":[]}}

When I see the tutorials, it looks sooo easy! But not for me.
I'm behind a corporate proxy, maybe that's what causes the issues...
My code is (modified a hundred times...):
import java.io.File;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import net.lightbody.bmp.proxy.ProxyServer;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;

public class Example {

    public static void main(String[] args) throws Exception {

        ProxyServer server = new ProxyServer(4444);

        HashMap<String, String> options = new HashMap<String, String>();

        server.start();
        server.setOptions(options);
        server.setCaptureHeaders(true);
        server.setCaptureContent(true);

        Proxy proxy = new Proxy();

        // configure it as a desired capability
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability(CapabilityType.PROXY, proxy);

        FirefoxProfile profile = new FirefoxProfile();
        profile.setAcceptUntrustedCertificates(true);
        profile.setAssumeUntrustedCertificateIssuer(true);
        profile.setPreference("network.proxy.http", "[MY_PROXY_HERE]");
        profile.setPreference("network.proxy.http_port", 8080);
        profile.setPreference("network.proxy.ssl", "[MY_PROXY_HERE]");
        profile.setPreference("network.proxy.ssl_port", 8080);
        profile.setPreference("network.proxy.type", 1);
        profile.setPreference("network.proxy.no_proxies_on", "");
        capabilities.setCapability(FirefoxDriver.PROFILE, profile);

        // start the browser up
        WebDriver driver = new FirefoxDriver(capabilities);
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        // create a new HAR with the label "apple.com"
        server.newHar("assertselenium.com");

        // open yahoo.com
        driver.get("http://assertselenium.com");
        // driver.get("http://assertselenium.com/2012/10/30/transformation-from-manual-tester-to-a-selenium-webdriver-automation-specialist/");

        driver.findElement(By.id("searchform"))
                .findElement(By.className("field"))
                .sendKeys(new String[] { "test selenium!" });

        driver.findElement(By.id("searchform"))
                .findElement(By.className("submit")).click();

        // new PerformanceTiming((JavascriptExecutor) driver, server.getHar());

        ((JavascriptExecutor) driver)
                .executeScript("var performance = window.performance || {};"
                        + "var timings = performance.timing || {};"
                        + "return timings;");

        server.getHar().writeTo(
                new File("C:/prj/SeleniumTest/harfiles/har.txt"));

        server.stop();
        driver.quit();

    }

}

(of course the [MY_PROXY_HERE] is only not to give the real name :))
Thank you !

A: Still don't have 50 rep so answer rather than comment ....
Just wondering what it is you're after from the performance timing? As you can retrieve data from the Navigation Timing API directly from your browser instance? This gives you a detailed breakdown of the page load performance times. If your dev team are willing to insert marks, you can also use it to capture timings for embedded AJAX calls and suchlike. (Which is what I'm doing)
Getting the data back is just a simple JavaScript injection. In my case (Python - with 'driver' being my webdriver instance) - driver.execute_script('return window.performance.timing'). Which returns a dictionary object with the full page load timing breakdown.
Just asking as it seems a lot simpler than messing around with proxies ...


text:
Q: How to do Winrar in a batch file In the actual UI of WinRAR you can create an sfx file and have the following sfx options:
Under General Tab:
Path to extract: Create in current folder
Under Modes Tab:
Silent mode: Hide all
Under Text And Icon Tab:
Load the SFX Icon from the file: Choose the certain file
How would I do this using batch files?
Also, how would I add a directory, rather than just a single file using the batch method?
I'm not too good with batch files, heck - I ain't ever done batch files - I was just looking at the switches and I couldn't figure out how I would do it. Please, if someone could tell me or even guide me, it will be much appreciated.
Thanks in advance.

A: You would need to use the winrar command line, A GUI is not conducive to manipulation via a batch file.
E.g;
winrar a -sfx -z"XXX.INI" OUTPUT.EXE

XXX.INI is a text file that contains the sfx options as shown under "SFX Commands" in the WinRar help file, e.g. silent=1.
(There is also a SFX commands: script sample)


text:
Q: Ruby: parsing string with backslash string = "{:name=>\"2012 Honda Civic EX-L\", :price=>\"23100\", :dealer_name=>\"T AND T HOND\", :dealer_website=>\"http://autocatch.com/dealer/t-and-t-honda/index.htm\", :phone=>\"(888) 364-1858\", :ad=>\"1167269\", :stock=>\" 2120054N\", :year=>\"2012\", :make=>\"Honda\", :model=>\"Model Civic\", :trim=>\"EXL\", :mileage=>\"4629\", :body_style=>\"Coupe\", :transmission=>\"Automatic\", :ext_colour=>\"White\", :int_colour=>\"Grey\", :doors=>\"2Door\", :passengers=>\"Passengers \", :drive_train=>\"Front Wheel Drive\", :engine=>\"1.80\", :cylinders=>\"4Cylinder\", :fuel_type=>\"Type Gas\", :certified=>\"\", :e_tested=>\"\"}\n"

How do I parse it?
It keeps giving me error.

A: The backslashes are just escaping the quotation marks; they aren't actually in the string. As for parsing it, use eval and let Ruby parse it, if it's from a trusted source.

A: With ruby-2.0.0-p0:
string = "{:name=>\"2012 Honda Civic EX-L\", :price=>\"23100\", :dealer_name=>\"T AND T HOND\", :dealer_website=>\"http://autocatch.com/dealer/t-and-t-honda/index.htm\", :phone=>\"(888) 364-1858\", :ad=>\"1167269\", :stock=>\" 2120054N\", :year=>\"2012\", :make=>\"Honda\", :model=>\"Model Civic\", :trim=>\"EXL\", :mileage=>\"4629\", :body_style=>\"Coupe\", :transmission=>\"Automatic\", :ext_colour=>\"White\", :int_colour=>\"Grey\", :doors=>\"2Door\", :passengers=>\"Passengers \", :drive_train=>\"Front Wheel Drive\", :engine=>\"1.80\", :cylinders=>\"4Cylinder\", :fuel_type=>\"Type Gas\", :certified=>\"\", :e_tested=>\"\"}\n"
hash = eval(string)
hash[:name] # => "2012 Honda Civic EX-L"

What errors do you get exactly?


text:
Q: c# bind morris.js with datatable code not working I have a code to bind morris.js bar chart to datatable but it's not working.. the graph doesn't display. It souhld be like this : I have a textbox to make research by keywords. The graph should show how many time the keyword appears in the datatable depending on the date so : abscissa = date and ordinate = number of times keyword appears.
what I want to display :
bar chart graph
So here is my code not working(im using ajax with webmethod) :
js code :
<script src="morris.js"></script>
<script src="raphael-min.js"></script>
<script>
    $(document).ready(function () {
        var word = "{'word':'" + $("#tbSearch").val() + "'}";
        Morris.Bar
            ({
            element: 'bar-chart',
            data: $.parseJSON(Graph()) + word,
            xkey: 'value',
            ykeys: ['value'],
            labels: ["nombre d'occurence"],
            fillOpacity: 0.6,
            hideHover: 'auto',
            behaveLikeLine: true,
            resize: true,
            pointFillColors: ['#ffffff'],
            pointStrokeColors: ['black'],
            lineColors: ['yellow', 'pink'],
            resize: true

        });
    });

    function Graph() {
        var data = "";

        $.ajax({
            type: 'POST',
            url: 'WelcomDigitalHelpDesk.aspx/GetBarchartData',
            dataType: 'json',
            async: false,
            contentType: "application/json; charset=utf-8",
            data: {},
            success: function (result) {

                data = result.d;

            },
            error: function (xhr, status, error) {
                alert(error);
            }
        });

        return data;
    }
</script>

c# code :
public class GraphData
        {
            public string label { get; set; }
            public string value { get; set; }
        }
    public class GraphDataList
    {
        public List<GraphData> ListOfGraphData { get; set; }
    }

    [WebMethod]
    public static string GetBarchartData(string word)
    {

        string sqlQuery = @"SELECT DateDescription, COUNT(DescriptionDemande) FROM cfao_DigiHelp_index.DigiHelpData WHERE DescriptionDemande like '" + word + "' GROUP BY DateDescription";

        DataTable DTGraph = DataBaseCacheDigitalHepDeskConnection.SqlDataTable(sqlQuery, "DIGIHELP_DB");

        List<GraphData> dataList = new List<GraphData>();

        foreach (DataRow dtrow in DTGraph.Rows)
        {
            GraphData graphData = new GraphData();
            graphData.label = Convert.ToString(dtrow["DateDescription"].ToString());
            graphData.label = Convert.ToString(dtrow["DescriptionDemande"].ToString());

            dataList.Add(graphData);
        }

        //oper = null which means its first load.
        var jsonSerializer = new JavaScriptSerializer();
        string data = jsonSerializer.Serialize(dataList);
        return data;

    }

Can someone tell me what I am doing wrong ?

A: Do you load jQuery anywhere? It is a dependency.
Also, try loading Raphael before Morris. Your full dependency list should look something like this:
<script src="jquery/1.9.0/jquery.min.js"></script>
<script src="raphael-min.js"></script>
<script src="morris.js"></script>

A: I made it worked so here is the answer working for me :
code js :
function buildChartGraph(data) {
    $('#bar-chart').html('');

    Morris.Bar
        ({
            element: 'bar-chart',
            data: JSON.parse(data),
            xkey: 'label',
            ykeys: ['value'],
            labels: ['value'],
            fillOpacity: 0.6,
            hideHover: 'auto',
            behaveLikeLine: true,
            resize: true,
            pointFillColors: ['blue'],
            pointStrokeColors: ['darkblue'],
            lineColors: ['skyblue', 'orange'],
            resize: true

        });
}

function GetOccurence() {
    var data = "";

    $.ajax({
        type: "POST",

        contentType: "application/json; charset=utf-8",

        url: "WelcomDigitalHelpDesk.aspx/GetBarchartData",

        data: "{'word':'" + $("#tbSearch").val() + "'}",

        dataType: "json",

        success: function (result) {

            buildChartGraph(result.d);

        },
        error: function (xhr, status, error) {
            alert(error);
        }
    });
}

Code c# :
[WebMethod]
    public static string GetBarchartData(string word)
    {

    string sqlQuery = @"SELECT TOP 40 DateDescription, COUNT(DescriptionDemande) FROM TableName WHERE DescriptionDemande like '%" + word + "%' GROUP BY DateDescription";

    DataTable DTGraph = DataBaseCacheDigitalHepDeskConnection.SqlDataTable(sqlQuery, "DbName");

    List<GraphData> dataList = new List<GraphData>();

    foreach (DataRow dtrow in DTGraph.Rows)
    {
        GraphData graphData = new GraphData();

        graphData.value = Convert.ToString(dtrow[1].ToString());
        graphData.label = Convert.ToString(DateTime.Parse( dtrow[0].ToString()).ToShortDateString());

        dataList.Add(graphData);
    }

    var jsonSerializer = new JavaScriptSerializer();
    string data = jsonSerializer.Serialize(dataList);
    return data;

}

}

public class GraphData
{
    public string label { get; set; }
    public string value { get; set; }
}

public class GraphDataList
{
    public List<GraphData> ListOfGraphData { get; set; }
}


text:
Q: 'Error While Encoding with Hub.KerasLayer' while using TFF An error is being generated while training a federated model that uses hub.KerasLayer. The details of error and stack trace is given below. The complete code is available of gist https://gist.github.com/aksingh2411/60796ee58c88e0c3f074c8909b17b5a1. Help and suggestion in this regard would be appreciated. Thanks.
from tensorflow import keras

def create_keras_model():
 encoder = hub.load("https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1")
 return tf.keras.models.Sequential([
  hub.KerasLayer(encoder, input_shape=[],dtype=tf.string,trainable=True),
  keras.layers.Dense(32, activation='relu'),
  keras.layers.Dense(16, activation='relu'),
  keras.layers.Dense(1, activation='sigmoid'),
])

def model_fn():
# We _must_ create a new model here, and _not_ capture it from an external
# scope. TFF will call this within different graph contexts.
keras_model = create_keras_model()
return tff.learning.from_keras_model(
  keras_model,
  input_spec=preprocessed_example_dataset.element_spec,
  loss=tf.keras.losses.BinaryCrossentropy(),
  metrics=[tf.keras.metrics.Accuracy()])

# Building the Federated Averaging Process
iterative_process = tff.learning.build_federated_averaging_process(
 model_fn,
 client_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=0.02),
 server_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=1.0))

str(iterative_process.initialize.type_signature)
state = iterative_process.initialize()

state, metrics = iterative_process.next(state, federated_train_data)
print('round  1, metrics={}'.format(metrics))

UnimplementedError                        Traceback (most recent call last)
<ipython-input-80-39d62fa827ea> in <module>()
----> 1 state, metrics = iterative_process.next(state, federated_train_data)
  2 print('round  1, metrics={}'.format(metrics))

119 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/eager/execute.py in
quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
 58     ctx.ensure_initialized()
 59     tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
---> 60                                         inputs, attrs, num_outputs)
 61   except core._NotOkStatusException as e:
 62     if name is not None:

UnimplementedError:    Cast string to float is not supported
 [[{{node StatefulPartitionedCall_1/StatefulPartitionedCall/Cast_1}}]]
 [[StatefulPartitionedCall_1]]
 [[import/StatefulPartitionedCall_3/ReduceDataset]] [Op:__inference_wrapped_function_65986]

Function call stack:
wrapped_function -> wrapped_function -> wrapped_function

A: The issues has now been resolved. The error was thrown because 'label' was getting passed as tf.string instead of tf.int32. Explicit casting resolved this.


text:
Q: Excel VBA :: Copying values using a loop & run time error 9 I'm pretty new to VBA, so the following question should not be too difficult. But since I spent about one and a half hour about the code, I think I simply lack some basic understanding how it should look like so I thought it's worth posting it here.
What the code is doing is basically copying values from one range in one sheet to another range in another sheet in the same active workbook containing some kind of a schedule.
I get a "run-time error '9' subscript out of range" error message already in the very first run through the loop in the section
'Subject
Morning = Worksheets("ExamSchedule").Cells(Weeknr + 2, Day)

I tried out the code in a blank workbook so the error should not be due to formatting (in case this might have been the cause). But if you need more information about the context etc. I can provide of course more details.
Thank you for your answers!
Patrick
Sub SetData_new()
' SubModule to copy the data from 'Master_Plan' to particular sheets

Dim CurrWS As Long, StartWS As Long, EndWS As Long
StartWS = Sheets("W_1").Index
EndWS = Sheets("L_1").Index
Dim Weeknr As Integer
Weeknr = 5
Dim Day As Long
Dim Morning As Range, Afternoon As Range, Noon As Range

For CurrWS = StartWS To EndWS

   'Set updated ranges
   Set Morning = Worksheets(CurrWS).Cells(4, 4)
   Set Afternoon = Worksheets(CurrWS).Cells(8, 4)
   Set Noon = Worksheets(CurrWS).Cells(12, 4)

    For Day = 3 To 21 Step 3
    'Subject
       Morning = Worksheets("ExamSchedule").Cells(Weeknr + 2, Day)
       Afternoon = Worksheets("ExamSchedule").Cells(Weeknr + 4, Day)
       Noon = Worksheets("ExamSchedule").Cells(Weeknr + 6, Day)

     'Category
       Morning.Offset(0, 1) = Worksheets("ExamSchedule").Cells(Weeknr + 2, Day + 1)
       Afternoon.Offset(0, 1).Value = Worksheets("ExamSchedule").Cells(Weeknr + 4, Day + 1)
       Noon.Offset(0, 1).Value = Worksheets("ExamSchedule").Cells(Weeknr + 6, Day + 1)

     'Type
       Morning.Offset(0, 2) = Worksheets("ExamSchedule").Cells(Weeknr + 2, Day + 2)
       Afternoon.Offset(0, 2).Value = Worksheets("ExamSchedule").Cells(Weeknr + 4, Day + 2)
   Noon.Offset(0, 2).Value = Worksheets("ExamSchedule").Cells(Weeknr + 6, Day + 2)

     'Specifications
       Morning.Offset(0, 3) = Worksheets("ExamSchedule").Cells(Weeknr + 3, Day)
       Afternoon.Offset(0, 3).Value = Worksheets("ExamSchedule").Cells(Weeknr + 5, Day)
       Noon.Offset(0, 3).Value = Worksheets("ExamSchedule").Cells(Weeknr + 7, Day)

     'Increment
       Morning = Morning.Offset(12, 0)
       Afternoon = Afternoon.Offset(12, 0)
       Noon = Noon.Offset(12, 0)
     Next Day

    Wochennummer = Wochennummer + 9
Next CurrWS

Worksheets("ExamSchedule").Activate

End Sub

A: The error is due to the default Variant type for the unqualifies Dim
What happens is the line
Morning = Worksheets("ExamSchedule").Cells(Weeknr + 2, Day)

puts the value from ExamSchedule into Morning and sets its type to whatever the cell value type is.
When the line
Morning.Offset(0, 1) = Worksheets("ExamSchedule").Cells(Weeknr + 2, Day + 1)

is run, Morning is not of type Range, so it has no Offset property and errors
Using
Dim Morning as Range

etc should solve your problems.
Edit
to simplify a bit, try this
Use a variable for the worksheet
Be explicit with Value references
Sub SetData_new()
    ' SubModule to copy the data from 'Master_Plan' to particular sheets
    Dim Wochennummer As Long ' unless this is a global variable?
    Dim CurrWS As Long, StartWS As Long, EndWS As Long
    StartWS = Sheets("W_1").Index
    EndWS = Sheets("L_1").Index
    Dim Weeknr As Long
    Weeknr = 5
    Dim Day  As Long
    Dim Morning As Range, Afternoon As Range, Noon As Range

    Dim ws As Worksheet
    Set ws = Worksheets("ExamSchedule")

    For CurrWS = StartWS To EndWS

       'Set updated ranges
       Set Morning = Worksheets(CurrWS).Cells(4, 4)
       Set Afternoon = Worksheets(CurrWS).Cells(8, 4)
       Set Noon = Worksheets(CurrWS).Cells(12, 4)

        For Day = 3 To 21 Step 3
        'Subject
           Morning.Value = ws.Cells(Weeknr + 2, Day).Value
           Afternoon.Value = ws.Cells(Weeknr + 4, Day).Value
           Noon.Value = ws.Cells(Weeknr + 6, Day).Value

         'Category
           Morning.Offset(0, 1).Value = ws.Cells(Weeknr + 2, Day + 1).Value
           Afternoon.Offset(0, 1).Value = ws.Cells(Weeknr + 4, Day + 1).Value
           Noon.Offset(0, 1).Value = ws.Cells(Weeknr + 6, Day + 1).Value

         'Type
           Morning.Offset(0, 2) = ws.Cells(Weeknr + 2, Day + 2)
           Afternoon.Offset(0, 2).Value = ws.Cells(Weeknr + 4, Day + 2)
           Noon.Offset(0, 2).Value = ws.Cells(Weeknr + 6, Day + 2)

         'Specifications
           Morning.Offset(0, 3).Value = ws.Cells(Weeknr + 3, Day).Value
           Afternoon.Offset(0, 3).Value = ws.Cells(Weeknr + 5, Day).Value
           Noon.Offset(0, 3).Value = ws.Cells(Weeknr + 7, Day).Value

         'Increment
           Morning.Value = Morning.Offset(12, 0).Value
           Afternoon.Value = Afternoon.Offset(12, 0).Value
           Noon.Value = Noon.Offset(12, 0).Value
         Next Day

        Wochennummer = Wochennummer + 9
    Next CurrWS

    ws.Activate
End Sub

A: For everyone interested, the version I finally implemented looks as below. It works definitely fine on Windows and should work on Mac as well:
Sub SetData_new_my()
' SubModule to copy the data from 'Master_Plan' to particular sheets

Dim CurrWS As Long, StartWS As Long, EndWS As Long, ScheduleWS As Long
StartWS = Sheets("W_1").Index
EndWS = Sheets("L_1").Index

Dim Weeknr As Long
Weeknr = 5
Dim Day As Long

Dim Morning As Range, Afternoon As Range, Noon As Range
Dim ExamSchedule As Worksheet
Set ExamSchedule = Worksheets("ExamSchedule")

For CurrWS = StartWS To EndWS
   'Set updated ranges
   Set Morning = Worksheets(CurrWS).Cells(4, 4)
   Set Afternoon = Worksheets(CurrWS).Cells(8, 4)
   Set Noon = Worksheets(CurrWS).Cells(12, 4)

    For Day = 3 To 21 Step 3
    'Subject
       Morning.Value = ExamSchedule.Cells(Weeknr + 2, Day).Value
       Afternoon.Value = ExamSchedule.Cells(Weeknr + 4, Day).Value
       Noon.Value = ExamSchedule.Cells(Weeknr + 6, Day).Value

     'Category
       Morning.Offset(0, 1).Value = ExamSchedule.Cells(Weeknr + 4, Day + 1).Value
       Afternoon.Offset(0, 1).Value = ExamSchedule.Cells(Weeknr + 4, Day + 1).Value
       Noon.Offset(0, 1).Value = ExamSchedule.Cells(Weeknr + 6, Day + 1).Value

     'Type
       Morning.Offset(0, 2).Value = ExamSchedule.Cells(Weeknr + 1, Day + 2).Value
       Afternoon.Offset(0, 2).Value = ExamSchedule.Cells(Weeknr + 4, Day + 2).Value
       Noon.Offset(0, 2).Value = ExamSchedule.Cells(Weeknr + 6, Day + 2).Value

     'Specifications
       Morning.Offset(0, 3).Value = ExamSchedule.Cells(Weeknr + 3, Day).Value
       Afternoon.Offset(0, 3).Value = ExamSchedule.Cells(Weeknr + 5, Day).Value
       Noon.Offset(0, 3).Value = ExamSchedule.Cells(Weeknr + 7, Day).Value

     'Increment
       Set Morning = Morning.Offset(12, 0)
       Set Afternoon = Afternoon.Offset(12, 0)
       Set Noon = Noon.Offset(12, 0)
     Next Day

    Weeknr = Weeknr + 9
Next CurrWS

ExamSchedule.Activate

End Sub


text:
Q: Search files with UNICODE names I have tried to compile this program after the compilation success it print on the console windows the current directory of the program.
But the job of the program is to show me all the files with .doc extension, also it works fine when i don't use the wide string wstring()  .So this is the problem i want to compile this program with wstring functionality .
UPDATE:
THIS CODE WORK PROPERLY:
#define UNICODE
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <windows.h>
#include <conio.h>

using namespace std;
/*
#define UNICODE
#define _UNICODE

typedef std::string UTF8String;
*/
int SearchDirectory(std::vector<std::string> &refvecFiles,
                    const std::string         &refcstrRootDirectory,
                    const std::string         &refcstrExtension,
                    bool                     bSearchSubdirectories = true)
{
  std::string      strFilePath;             // Filepath
  std::string      strPattern;              // Pattern
  std::string      strExtension;            // Extension
  HANDLE          hFile;                   // Handle to file
  WIN32_FIND_DATA FileInformation;         // File information

  strPattern = refcstrRootDirectory + "\\*.*";

  hFile = ::FindFirstFile(strPattern.c_str(), &FileInformation);
  if(hFile != INVALID_HANDLE_VALUE)
  {
    do
    {
      if(FileInformation.cFileName[0] != '.')
      {
        strFilePath.erase();
        strFilePath = refcstrRootDirectory + "\\" + FileInformation.cFileName;

        if(FileInformation.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        {
          if(bSearchSubdirectories)
          {
            // Search subdirectory
            int iRC = SearchDirectory(refvecFiles,
                                      strFilePath,
                                      refcstrExtension,
                                      bSearchSubdirectories);
            if(iRC)
              return iRC;
          }
        }
        else
        {
          // Check extension
          strExtension = FileInformation.cFileName;
          strExtension = strExtension.substr(strExtension.rfind(".") + 1);

          if(strExtension == refcstrExtension)
          {
            // Save filename
            refvecFiles.push_back(strFilePath);
          }
        }
      }
    } while(::FindNextFile(hFile, &FileInformation) == TRUE);

    // Close handle
    ::FindClose(hFile);

    DWORD dwError = ::GetLastError();
    if(dwError != ERROR_NO_MORE_FILES)
      return dwError;
  }

  return 0;
}

// Prototype for conversion functions
std::wstring StringToWString(const std::string& s);
std::string WStringToString(const std::wstring& s);

std::wstring StringToWString(const std::string& s)
{
    std::wstring temp(s.length(),L' ');
    std::copy(s.begin(), s.end(), temp.begin());
    return temp;
}

std::string WStringToString(const std::wstring& s)
{
    std::string temp(s.length(), ' ');
    std::copy(s.begin(), s.end(), temp.begin());
    return temp;
}

int main()
{
  int                      iRC         = 0;
  std::vector<std::string > vecAviFiles;
  std::vector<std::string > vecTxtFiles;

  // Search 'c:' for '.avi' files including subdirectories
  iRC = SearchDirectory(vecAviFiles, "c:", "doc");
  if(iRC)
  {
    std::cout << "Error " << iRC << std::endl;
    return -1;
  }

// Print results
  for(std::vector<std::wstring>::iterator iterAvi = vecAviFiles.begin(); iterAvi != vecAviFiles.end(); ++iterAvi)
    std::wcout << *iterAvi << std::endl;

}

NOT WORKING CODE:
#include <string>
#include <vector>
#include <iostream>

#include <windows.h>
#include <conio.h>

int SearchDirectory(std::vector<std::wstring> &refvecFiles,
                    const std::wstring        &refcstrRootDirectory,
                    const std::wstring        &refcstrExtension,
                    bool                     bSearchSubdirectories = true)
{
  std::wstring     strFilePath;             // Filepath
  std::wstring     strPattern;              // Pattern
  std::wstring     strExtension;            // Extension
  HANDLE          hFile;                   // Handle to file
  WIN32_FIND_DATAW FileInformation;         // File information

  strPattern = refcstrRootDirectory + L"\\*.*";

  hFile = ::FindFirstFileW(strPattern.c_str(), &FileInformation);
  if(hFile != INVALID_HANDLE_VALUE)
  {
    do
    {
      if(FileInformation.cFileName[0] != '.')
      {
        strFilePath.erase();
        strFilePath = refcstrRootDirectory + L"\\" + FileInformation.cFileName;

        if(FileInformation.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        {
          if(bSearchSubdirectories)
          {
            // Search subdirectory
            int iRC = SearchDirectory(refvecFiles,
                                      strFilePath,
                                      refcstrExtension,
                                      bSearchSubdirectories);
            if(iRC)
              return iRC;
          }
        }
        else
        {
          // Check extension
          strExtension = FileInformation.cFileName;
          strExtension = strExtension.substr(strExtension.rfind(L".") + 1);

          if(strExtension == refcstrExtension)
          {
            // Save filename
            refvecFiles.push_back(strFilePath);
          }
        }
      }
    } while(::FindNextFileW(hFile, &FileInformation) == TRUE);

    // Close handle
    ::FindClose(hFile);

    DWORD dwError = ::GetLastError();
    if(dwError != ERROR_NO_MORE_FILES)
      return dwError;
  }

  return 0;
}

int main()
{
  int                      iRC         = 0;
  std::vector<std::wstring> vecAviFiles;

  // Search 'c:' for '.avi' files including subdirectories
  iRC = SearchDirectory(vecAviFiles, L"c:", L"doc");
  if(iRC)
  {
    std::cout << "Error " << iRC << std::endl;
    return -1;
  }

  // Print results
  for(std::vector<std::wstring>::iterator iterAvi = vecAviFiles.begin(); iterAvi != vecAviFiles.end(); ++iterAvi)
    std::wcout << *iterAvi << std::endl;
}

What I want to know is why the second program won't work?

A: You're Doing It Wrong™.
Consider strPattern = refcstrRootDirectory + L"\\*.*";. That *.* is there for a reason. It's where you specify the file pattern that you're looking for. If you want to look for *.doc files, say so: strPattern = refcstrRootDirectory + L"\\*." + refcstrExtension;
Also, some style notes:

*

*Drop the type prefixes. That's a convention used in weakly typed languages; C++ is strongly typed.

*Define variables where you need them, not earlier:

*

*std::wstring Pattern = RootDirectory + L"\\*.*";

*HFILE File = ::FindFirstFileW(Pattern.c_str(), &FileInformation);

*There's no need to erase a string if you're assigning a new value. E.g. this works fine.

*

*FilePath = RootDirectory + L"\\" + FileInformation.cFileName;

*Check what this does to files without extensions.

*You're leaking a file handle in if(iRC) return iRC;. (C++ objects are cleaned automatically, but this is a C API).


text:
Q: How to store sanitized user's input in database using InsertInto I want to store some user's input variables into mysql. However, they are stored as :username and :password instead of the user's input.
$username = $_POST['username'];
$password = $_POST["password"];

$conn = new PDO("mysql:host=localhost;dbname=nome", "nome", "password");
$sql = "SELECT * FROM users";
$query = $conn->query($sql);
$result = $query->fetchAll(PDO::FETCH_ASSOC);

$sql = "SELECT * FROM users WHERE username = :username AND password = :password";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":username", $_POST["username"]);
$stmt->bindParam(":password", $_POST["password"]);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_dump($result);

if($username && $password){
    $sql = "INSERT INTO users (username, password) VALUES (':username', ':password')";
    $stmt = $conn->prepare($sql);
    $stmt->bindParam(":username", $_POST["username"]);
    $stmt->bindParam(":password", $_POST["password"]);
    $stmt->execute();
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
  }else{
    print "Dati non corretti";
};

<h1> Login Form </h1>
  <form action="?" method="post"> Name
    <input name="username"  value="" />

    Password
    <input name="password"  value=""/>

    <input type="submit" name="my_form_submit_button"
           value="Login" />

    </form>

When I check the phpMyAdmin table, the variables are stored as :username and :password.
I would like to store them as the user's input. For example, if the user's username input is Mark, I would like to store it as Mark, instead of :username.
Thank you !

A: It's totally working now, save the following code as a php file and run it.
I changed the following things.

*

*The INSERT sql's values ':username' to :username and same to ':password' to :password because the ' single quote converts inside to string and bindValue can skip it.

*Removed ? from <form action"?" to <form action"", It's defines the request page is itself.

*At php code, I added if($_POST) statement to check if any POST request exist before the instering values to database table.

*And last change is at the bindParam, I added PDO::PARAM_STR as a last variable to send fuction to define the values type.

<?php

$conn = new PDO("mysql:host=localhost;dbname=nome", "nome", "password");
$sql = "SELECT * FROM users";
$query = $conn->query($sql);
$result = $query->fetchAll(PDO::FETCH_ASSOC);

var_dump($result);

if($_POST){
    $username = $_POST['username'];
    $password = $_POST["password"];

    $sql = "INSERT INTO users (username, password) VALUES (:username, :password)";
    $stmt = $conn->prepare($sql);
    $stmt->bindParam(":username", $_POST["username"], PDO::PARAM_STR);
    $stmt->bindParam(":password", $_POST["password"], PDO::PARAM_STR);
    $stmt->execute();
}

?>

<h1> Login Form </h1>
<form action="" method="post"> Name
<input name="username"  value="" />

Password
<input name="password"  value=""/>

<input type="submit" name="my_form_submit_button"
        value="Login" />

</form>


text:
Q: change color of first word I am working in wordpress. I want to set site name in two colors.
My html code is :

 Pal Enterprice

Here I want to set Pal color as red and Enterprice color as  blue. So what css have to write?

A: Please check this snippet code.

h1 {
  color: #00f;
}

h1 span {
  color: #f00;
}

 Pal Enterprice