问:
Create a plug and play plugin framework setup using Angular4
My application was in IBM WebSphere portal, where we have a centralized theme for all the portlets. We build individual portlets with the specific features which are then installed from a page into the portal like as shown below.

So altogether we build a portal with lots of portlets (individual web application). In the portal we creates pages and drag and drop each of these portlets as per the requirements.

Now the requirement was that we are moving everything to Micro service Architecture with Angular4 as the front-end. Currently I am having an angular4 application having many UI components and features. I am posting this question to get some ideas or possibility whether it is possible to create a portal like IBM WebSphere/ Liferay in Angular 4 with having the following basic features:

User/Team can create separate individual angular4 application, build and will be able to install/uninstall within the main application like porltets in portal (IBM WebSphere).

User will be able to view all the installed Angular4 application and can create pages, drag and drop those application within a newly created page.

Each separate Angular4 application (like portlets) installed will be using the main application theme.

Can anyone tell me whether this is doable. Do we have any framework setup in Angular4

答:
When re-designing a system, it is best to think about the problem you are trying to solve and solve for that use case. It feels like you're trying to recreate the same bad interface with Angular. The code may be new, but the user interface problems will still be there.

I would recommend ditching the portlet idea and creating 1 app with many modules. Angular was designed to be very modular so different teams can work on separate modules. You could then have some sort of settings page where you can turn the modules on and off.


来源: stackexchange

问:
How find last day of previous month on the basis of Month and year in SQL Server
I have a requirement where I have to find the closing balance of previous month
on the basis of month and year.

I have tried this code:

```<code>DECLARE @month NUMERIC = 11
DECLARE @Year NUMERIC = 2017

SELECT
    DATEADD(DAY, -1, DATEADD(MONTH, @Month, DATEADD(YEAR, @Year - 1900, 0)))
</code>```

but this is returning the value of last day of the current month '2017-11-30 00:00:00.000'.

Instead of this I want the last day of the previous month: '2017-10-31 00:00:00.000'

答:
or you can simplify a bit by only using 2 DATEADD()

```<code>SELECT  DATEADD(month, @Month - 1, DATEADD(year, @Year - 1900, -1))
</code>```

or convert the @Year to months and only use single DATEADD()

```<code>SELECT  DATEADD(month, (@Year - 1900) * 12 + @Month - 1, - 1)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a requirement where I have to find the closing balance of previous month
on the basis of month and year.

I have tried this code:

DECLARE @month NUMERIC = 11
DECLARE @Year NUMERIC = 2017

SELECT
    DATEADD(DAY, -1, DATEADD(MONTH, @Month, DATEADD(YEAR, @Year - 1900, 0)))

but this is returning the value of last day of the current month '2017-11-30 00:00:00.000'.

Instead of this I want the last day of the previous month: '2017-10-31 00:00:00.000'

Body:
or you can simplify a bit by only using 2 DATEADD()

SELECT  DATEADD(month, @Month - 1, DATEADD(year, @Year - 1900, -1))

or convert the @Year to months and only use single DATEADD()

SELECT  DATEADD(month, (@Year - 1900) * 12 + @Month - 1, - 1)


问:
Firebase handle sudden loss in connection
I want to know how I can control my firebase write requests when internet connection is lost suddenly. To explain my problem I will give this example:

Example

lets say I am doing 3 writes at a time:

1) WRITE 1 : represents uploading image to firebase storage.

2) WRITE 2 : represents uploading another image to firebase storage.

3) WRITE 3 : represents storing the url links of (WRITE 1) and (WRITE 2) in the real time database.

The reasonable approach to do the 3 writes at one time is to chain them according to the complete listener of each

something like this:

```<code> //WRITE 1

 storageref.putfile(image1).addOnCompleteListener(new OnCompleteListener{

     //get link of this write and do WRITE 2

      //WRITE 2

       storage ref.putfile(image2).addOnCompleteListener(new OnCompleteListener{

          //get the link of this write and do WRITE 3

         // WRITE 3
           Map links=new HashMap();
           links.put("image1", link1);
           links.put("image2", link2);
           databaseref.child("images").setValue(links).addOnCompleteListener(new OnCompleteListener{

             //show a message

        });

  });
  });
</code>```

As you can see the only way to accomplish this is to chain them together so when one write completes the other executes and so on.

The problem

case 1: if connection is lost on WRITE 1, then other writes won't finish.

case 2: if connection is lost on WRITE 2, then last write won't execute and I end up with useless files on storage. Because I won't be able to send them to the database.

case 3: if connection is lost on WRITE 3 , then I won't be able to show message.

Question

as it seems that this is the only way to go about that. Can you please give a method or a solution to go about this, I don't want to end up with my app crashing due to incomplete database structure.

答:
In the absence of transactions, you'll need to do a few things to ensure your apps work in unreliable conditions.

Write data in the order that makes it easiest to prevent or detect failures. You're writing the files first and only then update the database. Since it's likely that you trigger your other processes on the database record, they won't get triggered until step 3 completes. So you're already doing this.

Write your reading code to be robust against possible incomplete data. For example: don't assume that the files are correct, or even present, even when the URL has made it into the database. And when you're reading multiple nodes from the database in separate read actions, read them in the order that makes it easiest to detect incomplete or corrupt data and skip the item in such cases.

Run regular batch processes to clean up orphaned data. I'll admit that quite often this is not worth the cost, but it is a matter of good hygiene to keep the data as correct as possible.

Body:
I want to know how I can control my firebase write requests when internet connection is lost suddenly. To explain my problem I will give this example:

Example

lets say I am doing 3 writes at a time:

1) WRITE 1 : represents uploading image to firebase storage.

2) WRITE 2 : represents uploading another image to firebase storage.

3) WRITE 3 : represents storing the url links of (WRITE 1) and (WRITE 2) in the real time database.

The reasonable approach to do the 3 writes at one time is to chain them according to the complete listener of each

something like this:

 //WRITE 1

 storageref.putfile(image1).addOnCompleteListener(new OnCompleteListener{

     //get link of this write and do WRITE 2

      //WRITE 2

       storage ref.putfile(image2).addOnCompleteListener(new OnCompleteListener{

          //get the link of this write and do WRITE 3

         // WRITE 3
           Map links=new HashMap();
           links.put("image1", link1);
           links.put("image2", link2);
           databaseref.child("images").setValue(links).addOnCompleteListener(new OnCompleteListener{

             //show a message

        });

  });
  });

As you can see the only way to accomplish this is to chain them together so when one write completes the other executes and so on.

The problem

case 1: if connection is lost on WRITE 1, then other writes won't finish.

case 2: if connection is lost on WRITE 2, then last write won't execute and I end up with useless files on storage. Because I won't be able to send them to the database.

case 3: if connection is lost on WRITE 3 , then I won't be able to show message.

Question

as it seems that this is the only way to go about that. Can you please give a method or a solution to go about this, I don't want to end up with my app crashing due to incomplete database structure.


问:
Android: Same Image needs to be added in all drawable folders?
I am directly adding images in drawable folders and it is coming fine with ImageView tag android:src="@drawable/image_name" but I wonder what to do with the other drawable folders as shown below.

Do I need to add same image in all drawable folders or my way of adding images in drawable folders is wrong?

Please help me!

答:
All these drawable folders represent different android phone densities. The best folder to put your images is drawable-xxhdpi as android automatically downscale or upscale the images depending on your devices density and most phones these days are on xxhdpi density.

If you put a image in drawable folder only there are chances that image may get distorted(as it upscales) in xxxhdpi density.

If you are putting images in xxhdpi ,make sure you create your images acc. to xxhdpi resolution.

If you don't feel the image is looking right in some phones than check the density of that phone and put an image in that specific density folder acc. to it's size(reduced or increased).


问:
Initial configuration GSM Modem in Raspberry PI using NodeJS
I am a newbie in NodeJS framwork and currently i am working on a project where i want to establish connectivity to my cloud application and make some API calls.for that i want to make initial configuration to establish a connection on my gsm modem.

How to search for the presense of Sim card in gsm modem

How to receive the APN and configure the gsm sim card(APN,subnet,gateway etc)

答:
You can use WvDial to help you find the GSM Modem.  Here is tutorial for doing so with a USB Modem: https://www.thefanclub.co.za/how-to/how-setup-usb-3g-modem-raspberry-pi-using-usbmodeswitch-and-wvdial

WvDial helps configure the PPP connection.

The APN is dependent on your cellular provider.  You should review your provider's documentation or reach out to them for the necessary details.


问:
Firebase storage downloadURL partial apply forwarder for @nonobjc message
I am testing a upload image to Firebase storage, but i got the message:

```<code>partial apply forwarder for @nonobjc  at xxxViewController.swift
</code>```

Here is the code:

```<code>let storage = Storage.storage()
storage.reference().child("abc").putData(d, metadata: nil) { (metadata, error) in
    guard let metadata = metadata else {
         print("error")
         return
    }
    let downloadURL = metadata.downloadURL
    print(downloadURL)
}
</code>```

The output is just (Function) and with the message above.

答:
have a look at it I am here uploading a profile image to firebase storage </p>

```<code>if let uploadData = UIImagePNGRepresentation(self.profileImageView.image!) {

                storageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
                    if let error = error
                    {
                        print(error)
                        return
                    }
                    else
                    {
                        //get download url if upload is successful
                        let downloadURL = metadata?.downloadURL()?.absoluteString
                        print(downloadURL!)

                    }
                })
            }
</code>```

Body:
I am testing a upload image to Firebase storage, but i got the message:

partial apply forwarder for @nonobjc  at xxxViewController.swift

Here is the code:

let storage = Storage.storage()
storage.reference().child("abc").putData(d, metadata: nil) { (metadata, error) in
    guard let metadata = metadata else {
         print("error")
         return
    }
    let downloadURL = metadata.downloadURL
    print(downloadURL)
}

The output is just (Function) and with the message above.

Body:
have a look at it I am here uploading a profile image to firebase storage

if let uploadData = UIImagePNGRepresentation(self.profileImageView.image!) {

                storageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
                    if let error = error
                    {
                        print(error)
                        return
                    }
                    else
                    {
                        //get download url if upload is successful
                        let downloadURL = metadata?.downloadURL()?.absoluteString
                        print(downloadURL!)

                    }
                })
            }


问:
How to change Custom Font of Android Menu Item?
I have the following Android Java and XML code. I want to change the font of Menu Items of my app. I know only that we can change the font of TextView using setTypeface but not able to find anyway for Menu Item.

JAVA Code-:

```<code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
   switch (item.getItemId()) {
        case R.id.action_refresh1:
            Toast.makeText(this, "Item1 Selected", Toast.LENGTH_SHORT)
            .show();
        break;

        case R.id.action_refresh2:
            Toast.makeText(this, "Item2 Selected", Toast.LENGTH_SHORT)
            .show();
            break;

        default:
            break;
   }
}
</code>```

XML Code-:

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
    android:id="@+id/action_refresh1"
    android:orderInCategory="100"
    android:showAsAction="always"
    android:title="Item1"/>

<item
    android:id="@+id/action_refresh2"
    android:orderInCategory="100"
    android:showAsAction="always"
    android:title="Item2"/>
</menu>
</code>```

I want to change the font of two menu item , but don't know how to integrate settypface for Menu Item.

答:
I found this solution is usefull for me .hope it will help full new surfers.

your menu main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
  <item android:id="@+id/item1"
  android:title="User"
  android:orderInCategory="100"
  android:visible="true"
  app:showAsAction="always"
  app:actionViewClass="android.widget.Button"
/>
</menu>
</code>```

After you inflated the custom menu, you can make a reference to the item of the menu. When you obtain the reference to the menu item, you will be able to customize the item to show icon and Unicode text. Your icon image file has to be stored in the

res/drawable folder.

```<code>@Override
   public boolean onCreateOptionsMenu(Menu menu) {
     // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);

   //reference to the item of the menu
   MenuItem i=menu.findItem(R.id.item1);
   Button button_menu =(Button) i.getActionView();

   if(itemuser!=null){
   // Create Typeface object to use unicode font in assets folder
   Typeface font= Typeface.createFromAsset(getApplicationContext().getAssets(),"fonts/arial.ttf");
   // Set unicode font to menu item
   button_menu .setTypeface(font);
   // Set item text and color
   button_menu .setText(getResources().getString(R.string._text));
   button_menu .setTextColor(Color.WHITE);
   // Make item background transparent
   button_menu .setBackgroundColor(Color.TRANSPARENT);
   // Show icon next to the text
   Drawable icon=getApplicationContext().getResources().getDrawable( R.drawable.user);
   button_menu .setCompoundDrawablesWithIntrinsicBounds( icon, null, null, null );
}

return true;

   }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following Android Java and XML code. I want to change the font of Menu Items of my app. I know only that we can change the font of TextView using setTypeface but not able to find anyway for Menu Item.

JAVA Code-:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
   switch (item.getItemId()) {
        case R.id.action_refresh1:
            Toast.makeText(this, "Item1 Selected", Toast.LENGTH_SHORT)
            .show();
        break;

        case R.id.action_refresh2:
            Toast.makeText(this, "Item2 Selected", Toast.LENGTH_SHORT)
            .show();
            break;

        default:
            break;
   }
}

XML Code-:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
    android:id="@+id/action_refresh1"
    android:orderInCategory="100"
    android:showAsAction="always"
    android:title="Item1"/>

<item
    android:id="@+id/action_refresh2"
    android:orderInCategory="100"
    android:showAsAction="always"
    android:title="Item2"/>
</menu>

I want to change the font of two menu item , but don't know how to integrate settypface for Menu Item.

Body:
I found this solution is usefull for me .hope it will help full new surfers.

your menu main.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
  <item android:id="@+id/item1"
  android:title="User"
  android:orderInCategory="100"
  android:visible="true"
  app:showAsAction="always"
  app:actionViewClass="android.widget.Button"
/>
</menu>

After you inflated the custom menu, you can make a reference to the item of the menu. When you obtain the reference to the menu item, you will be able to customize the item to show icon and Unicode text. Your icon image file has to be stored in the

res/drawable folder.

@Override
   public boolean onCreateOptionsMenu(Menu menu) {
     // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);

   //reference to the item of the menu
   MenuItem i=menu.findItem(R.id.item1);
   Button button_menu =(Button) i.getActionView();

   if(itemuser!=null){
   // Create Typeface object to use unicode font in assets folder
   Typeface font= Typeface.createFromAsset(getApplicationContext().getAssets(),"fonts/arial.ttf");
   // Set unicode font to menu item
   button_menu .setTypeface(font);
   // Set item text and color
   button_menu .setText(getResources().getString(R.string._text));
   button_menu .setTextColor(Color.WHITE);
   // Make item background transparent
   button_menu .setBackgroundColor(Color.TRANSPARENT);
   // Show icon next to the text
   Drawable icon=getApplicationContext().getResources().getDrawable( R.drawable.user);
   button_menu .setCompoundDrawablesWithIntrinsicBounds( icon, null, null, null );
}

return true;

   }


问:
Sending log files to server after Android app crashed
I have an Android app, and I'm able to log the crash details in a text file. I want to show a message after an app crash, and I need to send the log file to the server. Any suggestions will be helpful.</p>

答:
I suggest Fabric.

Fabric is now free! It is famous crash log analytics service. It supports Crash report, Daily user amount statistics... so on.

Or, if you want your own log server, use ACRA

See this to setting your ACRA backend.
https://github.com/ACRA/acra/wiki/Backends


问:
Git push to another machine
```<code>[Remote GIT repo]----[Remote VM]----[Local Host]
</code>```

I have this setup where I have a remote VM which clones a GIT repo from remote GIT repo. I have my local machine which clones the repo cloned at remote VM.

The remote.origin.url for VM is the actual remote repository URL from which all users clone.

And the remote.origin.url for my Local Host is the remote VM URL. Like -

```<code>remote.origin.url=ssh://myusername@myremoteVMURL.net/path/to/cloned/repo
</code>```

My doubt is if I make some changes on my local machine and commit+push. Will that push the changes to the remote VM or the remote GIT repo? I hope it pushes to the remote VM and not the remote repo.

Basically I want to work on my local machine and synchronize whatever changes I make to Remote VM. That includes local branches and committed work. So I can start the build on Remote VM and push from there to the Remote Git repo.

答: A remote is an alias for a location. When you you pus from your local machine to origin, the objects you push will go to  myremoteVMURL.net/path/to/cloned/repo over ssh. What happens after that is upto the VM and the invocation of git on your local machine has no say in the matter.

Title: Git push to another machine

Body:
[Remote GIT repo]----[Remote VM]----[Local Host]

I have this setup where I have a remote VM which clones a GIT repo from remote GIT repo. I have my local machine which clones the repo cloned at remote VM.

The remote.origin.url for VM is the actual remote repository URL from which all users clone.

And the remote.origin.url for my Local Host is the remote VM URL. Like -

remote.origin.url=ssh://myusername@myremoteVMURL.net/path/to/cloned/repo

My doubt is if I make some changes on my local machine and commit+push. Will that push the changes to the remote VM or the remote GIT repo? I hope it pushes to the remote VM and not the remote repo.

Basically I want to work on my local machine and synchronize whatever changes I make to Remote VM. That includes local branches and committed work. So I can start the build on Remote VM and push from there to the Remote Git repo.


问:
Obj-C - Dismiss keyboard by tapping anywhere on screen from UITextView?
When my user taps on my UITextView (NOT uitextfield...), an animation occurs. However after the UITextView begins editing, no other UITapGesture seems to be recognized (e.g. if I add a tapGesture to my UIView to dismiss this animation, it doesn't execute at all). I've been trying to fix this for what feels like forever. Help is appreciated, I'm stumped.

ViewController.m

```<code> - (void)viewDidLoad
        {
            [super viewDidLoad];

         self.replyField.delegate = self;

        [self.replyField setUserInteractionEnabled:YES];

        UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textViewTapped)];
        [self.view addGestureRecognizer:gestureRecognizer];

        }

    -(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {

        return YES;

    }

    -(void)textViewTapped {
        NSLog(@"DISMISS PLEASE!");
        [self animateTextView:NO];

    }

       - (void)textViewDidBeginEditing:(UITextView *)textView
    {

        [self animateTextView: YES];
        self.replyField.gestureRecognizers = nil;

    }

    - (void)textViewDidEndEditing:(UITextView *)textView
    {
        [self animateTextView:NO];

    }

    - (void) animateTextView:(BOOL) up
    {
        const int movementDistance = 206;
        const float movementDuration = 0.3f;
        int movement= movement = (up ? -movementDistance : movementDistance);
        NSLog(@"%d",movement);

        [UIView beginAnimations: @"anim" context: nil];
        [UIView setAnimationBeginsFromCurrentState: YES];
        [UIView setAnimationDuration: movementDuration];
        self.view.frame = CGRectOffset(self.inputView.frame, 0, movement);
        [UIView commitAnimations];

    }

    - (void)textViewDidChange:(UITextView *)textView
    {

    }
</code>```

答:
I have encountered similar issues use follow below code to dismiss keyboard by tapping anywhere on screen view. Hope will helpful to you.

Objective c

```<code>- (void)viewDidLoad
{
    UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    [self.view addGestureRecognizer:gestureRecognizer];
    gestureRecognizer.cancelsTouchesInView = NO;

}
- (void)dismissKeyboard
{
     [self.view endEditing:YES];
}
</code>```

Swift 4

```<code>func viewDidLoad() {
    let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard))
    view.addGestureRecognizer(gestureRecognizer)
    gestureRecognizer.cancelsTouchesInView = false
 }

func dismissKeyboard() {
    view.endEditing(true)
}
</code>```

Body:
When my user taps on my UITextView (NOT uitextfield...), an animation occurs. However after the UITextView begins editing, no other UITapGesture seems to be recognized (e.g. if I add a tapGesture to my UIView to dismiss this animation, it doesn't execute at all). I've been trying to fix this for what feels like forever. Help is appreciated, I'm stumped.

ViewController.m

 - (void)viewDidLoad
        {
            [super viewDidLoad];

         self.replyField.delegate = self;

        [self.replyField setUserInteractionEnabled:YES];

        UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textViewTapped)];
        [self.view addGestureRecognizer:gestureRecognizer];

        }

    -(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {

        return YES;

    }

    -(void)textViewTapped {
        NSLog(@"DISMISS PLEASE!");
        [self animateTextView:NO];

    }

       - (void)textViewDidBeginEditing:(UITextView *)textView
    {

        [self animateTextView: YES];
        self.replyField.gestureRecognizers = nil;

    }

    - (void)textViewDidEndEditing:(UITextView *)textView
    {
        [self animateTextView:NO];

    }

    - (void) animateTextView:(BOOL) up
    {
        const int movementDistance = 206;
        const float movementDuration = 0.3f;
        int movement= movement = (up ? -movementDistance : movementDistance);
        NSLog(@"%d",movement);

        [UIView beginAnimations: @"anim" context: nil];
        [UIView setAnimationBeginsFromCurrentState: YES];
        [UIView setAnimationDuration: movementDuration];
        self.view.frame = CGRectOffset(self.inputView.frame, 0, movement);
        [UIView commitAnimations];

    }

    - (void)textViewDidChange:(UITextView *)textView
    {

    }

Body:
I have encountered similar issues use follow below code to dismiss keyboard by tapping anywhere on screen view. Hope will helpful to you.

Objective c

- (void)viewDidLoad
{
    UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    [self.view addGestureRecognizer:gestureRecognizer];
    gestureRecognizer.cancelsTouchesInView = NO;

}
- (void)dismissKeyboard
{
     [self.view endEditing:YES];
}

Swift 4

func viewDidLoad() {
    let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard))
    view.addGestureRecognizer(gestureRecognizer)
    gestureRecognizer.cancelsTouchesInView = false
 }

func dismissKeyboard() {
    view.endEditing(true)
}


问:
how connect to mssql named instance
I connected remote mssql default instance like

jdbc.url=jdbc:jtds:sqlserver://ip:port;databaseName=name

it succeed to connect and proceed in java source

I connected remote mssql named instance like

jdbc.url=jdbc:jtds:sqlserver://ip:port;databaseName=name

(surely I set port to instance in SQL server configuration management TCP/IP IPALL)

It succeed to connect, but not proceed well in java source like router error??

I think only reason is named instance

I don't write English well.. But, Help me..

答:
I solve this problem!! The reason is program installing error and than not build essential DB Data. So connect succeed but not proceed well in program.
However I don't know why cause the installing error. it seems to DB authority or named instance... So please you take care of install any program with connect mssql named instance DB. Thank you...</p>

Title: how connect to mssql named instance


问:
No public static parameters method with Galen
In a project in which I'm working, I'm trying to use Galen without TestNG (so, the JUnit based version).

This is the code that I have for the sample class that I've made:

```<code>import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import com.galenframework.support.GalenJavaTestBase;
import com.galenframework.testng.GalenTestNgTestBase;
import org.apache.xmlbeans.impl.tool.Extension;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import com.galenframework.junit.GalenJUnitTestBase;

public class GalenTesting extends GalenJUnitTestBase {

    @Override

    public WebDriver createDriver() {
        System.setProperty("webdriver.chrome.driver","C:/Drivers/chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        return driver;
    }

    @Test
    public void welcomePage_shouldLookGood_onDesktopDevice() throws IOException {
        super.load("http://www.google.com", 1024, 768);
        super.checkLayout("/specs/welcomePage.spec", Arrays.asList("mobile"));
    }
</code>```

Which is pretty much the code that can be found in the Galen doc for Java usage.
I am having an issue with running this code, because it states that:

```<code>java.lang.Exception: No public static parameters method on class it.automationTest.GalenTesting

    at org.junit.runners.Parameterized.getParametersMethod(Parameterized.java:299)
    at org.junit.runners.Parameterized.<init>(Parameterized.java:246)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
    at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:49)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=256m; support was removed in 8.0

Process finished with exit code -1
</code>```

At first, I thought it was referring to the methods' calls inside the "welcomePage_shouldLookGood_onDesktopDevice()" method, so I've inserted a super.methodName() to try fix that but it didn't work.
I've also tried to read the source code of all the superclasses but I couldn't find anything useful that could help me preventing this Exception.
Could someone point me in the right direction?

 EDIT

As requested, this is the updated version of the code.
It now contains an iterable method for the Test Devices (as kindly pointed out hypery2k).
The original question is solved, because there createDriver() method was annotated just with @Overriden, while it should have been only with a @Test annotation. Now I'm facing the following issue, for which first I'll put the new updated code, then the stack error.

```<code>import java.io.IOException;
import java.util.Arrays;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import com.galenframework.junit.GalenJUnitTestBase;

public class GalenTesting extends GalenJUnitTestBase {

WebDriver driver;

public GalenTesting() {
    super();

}

@Override
public WebDriver createDriver() {
    createDriverVoid();
    return driver;
}

@Test
public void createDriverVoid() {
    System.setProperty("webdriver.chrome.driver","C:/Drivers/chromedriver.exe");
    driver = new ChromeDriver();
}

@Test
public void welcomePage_shouldLookGood_onDesktopDevice() throws IOException {
    super.load("http://www.google.com", 1024, 768);
    super.checkLayout("/specs/welcomePage.spec", Arrays.asList("mobile"));
}

@Parameterized.Parameters
public static Iterable<Object[]> devices() {
    return Arrays.asList(new Object[][]{// @formatter:off
            {new TestDevice("desktop", new Dimension(1024, 800), Arrays.asList("normal", "desktop"))},
            {new TestDevice("fullhd", new Dimension(1920, 1080), Arrays.asList("fullhd", "desktop"))},// @formatter:on
    });
}

}
</code>```

The class is now giving the following error:

```<code>java.lang.Exception: No tests found matching createDriver with any parameter from org.junit.runner.Request$1@2d6a9952

    at org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:40)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:49)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=256m; support was removed in 8.0

Process finished with exit code -1
</code>```

I've been trying to mess around with some methods that I've added (like the constructor that calls the super()) but it still gives the same error. It returns the same error even with the original fixed code.

答:
your missing the Parameters for your test case, see here for my complete example:</p>

```<code>@Parameters
public static Iterable<Object[]> devices() {
    return Arrays.asList(new Object[][]{// @formatter:off
            {new TestDevice("small-phone", new Dimension(280, 800), asList("small-phone", "phone", "mobile"))},
            {new TestDevice("normal-phone", new Dimension(320, 800), asList("normal-phone", "phone", "mobile"))},
            {new TestDevice("big-phone", new Dimension(380, 800), asList("big-phone", "phone", "mobile"))},
            {new TestDevice("small-tablet", new Dimension(450, 800), asList("small-tablet", "tablet", "mobile"))},
            {new TestDevice("normal-tablet", new Dimension(450, 800), asList("normal-tablet", "tablet", "mobile"))},
            {new TestDevice("desktop", new Dimension(1024, 800), asList("normal", "desktop"))},
            {new TestDevice("fullhd", new Dimension(1920, 1080), asList("fullhd", "desktop"))},// @formatter:on
    });
}
</code>```

Body:
In a project in which I'm working, I'm trying to use Galen without TestNG (so, the JUnit based version).

This is the code that I have for the sample class that I've made:

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import com.galenframework.support.GalenJavaTestBase;
import com.galenframework.testng.GalenTestNgTestBase;
import org.apache.xmlbeans.impl.tool.Extension;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import com.galenframework.junit.GalenJUnitTestBase;

public class GalenTesting extends GalenJUnitTestBase {

    @Override

    public WebDriver createDriver() {
        System.setProperty("webdriver.chrome.driver","C:/Drivers/chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        return driver;
    }

    @Test
    public void welcomePage_shouldLookGood_onDesktopDevice() throws IOException {
        super.load("http://www.google.com", 1024, 768);
        super.checkLayout("/specs/welcomePage.spec", Arrays.asList("mobile"));
    }

Which is pretty much the code that can be found in the Galen doc for Java usage.
I am having an issue with running this code, because it states that:

java.lang.Exception: No public static parameters method on class it.automationTest.GalenTesting

    at org.junit.runners.Parameterized.getParametersMethod(Parameterized.java:299)
    at org.junit.runners.Parameterized.<init>(Parameterized.java:246)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
    at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:49)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=256m; support was removed in 8.0

Process finished with exit code -1

At first, I thought it was referring to the methods' calls inside the "welcomePage_shouldLookGood_onDesktopDevice()" method, so I've inserted a super.methodName() to try fix that but it didn't work.
I've also tried to read the source code of all the superclasses but I couldn't find anything useful that could help me preventing this Exception.
Could someone point me in the right direction?

 EDIT

As requested, this is the updated version of the code.
It now contains an iterable method for the Test Devices (as kindly pointed out hypery2k).
The original question is solved, because there createDriver() method was annotated just with @Overriden, while it should have been only with a @Test annotation. Now I'm facing the following issue, for which first I'll put the new updated code, then the stack error.

import java.io.IOException;
import java.util.Arrays;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import com.galenframework.junit.GalenJUnitTestBase;

public class GalenTesting extends GalenJUnitTestBase {

WebDriver driver;

public GalenTesting() {
    super();

}

@Override
public WebDriver createDriver() {
    createDriverVoid();
    return driver;
}

@Test
public void createDriverVoid() {
    System.setProperty("webdriver.chrome.driver","C:/Drivers/chromedriver.exe");
    driver = new ChromeDriver();
}

@Test
public void welcomePage_shouldLookGood_onDesktopDevice() throws IOException {
    super.load("http://www.google.com", 1024, 768);
    super.checkLayout("/specs/welcomePage.spec", Arrays.asList("mobile"));
}

@Parameterized.Parameters
public static Iterable<Object[]> devices() {
    return Arrays.asList(new Object[][]{// @formatter:off
            {new TestDevice("desktop", new Dimension(1024, 800), Arrays.asList("normal", "desktop"))},
            {new TestDevice("fullhd", new Dimension(1920, 1080), Arrays.asList("fullhd", "desktop"))},// @formatter:on
    });
}

}

The class is now giving the following error:

java.lang.Exception: No tests found matching createDriver with any parameter from org.junit.runner.Request$1@2d6a9952

    at org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:40)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:49)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=256m; support was removed in 8.0

Process finished with exit code -1

I've been trying to mess around with some methods that I've added (like the constructor that calls the super()) but it still gives the same error. It returns the same error even with the original fixed code.

Body:
your missing the Parameters for your test case, see here for my complete example:

@Parameters
public static Iterable<Object[]> devices() {
    return Arrays.asList(new Object[][]{// @formatter:off
            {new TestDevice("small-phone", new Dimension(280, 800), asList("small-phone", "phone", "mobile"))},
            {new TestDevice("normal-phone", new Dimension(320, 800), asList("normal-phone", "phone", "mobile"))},
            {new TestDevice("big-phone", new Dimension(380, 800), asList("big-phone", "phone", "mobile"))},
            {new TestDevice("small-tablet", new Dimension(450, 800), asList("small-tablet", "tablet", "mobile"))},
            {new TestDevice("normal-tablet", new Dimension(450, 800), asList("normal-tablet", "tablet", "mobile"))},
            {new TestDevice("desktop", new Dimension(1024, 800), asList("normal", "desktop"))},
            {new TestDevice("fullhd", new Dimension(1920, 1080), asList("fullhd", "desktop"))},// @formatter:on
    });
}


问:
How to configure iOs UITextViews and UILabels so that their height is determined by their content
I am basically trying to find the correct way to design a UITableViewCell that has two UITextViews and three UILabels inside it. The two UITextViews have dynamic content and their size cannot be determined until runtime.

I have tried various methods of recalculating the height of my UITextViews based on the content that is loaded in them at runtime, and though very laborious and inane, I have gotten that to work, but they then bleed over the UILabels positioned in the xib below them.

Do I really have to recalculate the y coordinates of every UILabel after calculating the new size of the UITextViews? Is there a way to simply have the elements in the xib 'push' the elements below them down based on their new size?

What is the correct approach to configuring a UITableViewCell with multiple dynamic text views so that my entire application is not comprised of code to calculate heights and coordinates?

Or is the answer that I should not be putting more than one dynamic UITextView in the same UITableViewCell ?

答:
iOS doesn't seem to have any sort of flow layout engine -- at least none that I can think of.
If, however, your labels are located at the bottom of your UITableViewCell, you might be able to get away with setting the UILabel's autoresizingMask mask property to UIViewAutoresizingFlexibleBottomMargin so that the UILabels will anchor itself at the bottom. This is assuming that you already adjusted the size of the UITableViewCell to fit the entire controls. Otherwise, I think the best way to handle this is to recalculate the y coordinates of the labels. </p>

ContentLicense: CC BY-SA 2.5


问:
POST multiple Node clones to array of objects
I have a mongodb model that looks like this:

```<code>ingredients: [
  quantity: Number,
  measurement: String,
  name: String
]
</code>```

These are being passed in with a single form where the user can add new ingredients by clicking a button which clones the input node and appends it to the parent node. So currently all of the name='' values are the same. As it is now, this is passing in a single array like this:

```<code>ingredients: [{
  quantity: ['1','2','3'],
  measurement: ['cup','tsp','tbsp'],
  name: ['rice','cumin','pepper']
}]
</code>```

Right now the form input is declaring name like name='recipe[ingredients][quantity]' (recipe is the parent object). How do I make this pass multiple objects into the ingredients string?

Relevent section of form:

```<code>div class='add-ingredient-form'>
              <input type='text' name='recipe.ingredients[quantity]' placeholder='1' class='form-control' style='width: 10%; display: inline-block;'></input>
              <select class='form-control' style='width: 15%; display: inline-block;' name='recipe.ingredients[measurement]'>
                <option>#</option>
                <option>tsp</option>
                <option>tbsp</option>
                <option>cup</option>
                <option>lb</option>
                <option>fl oz</option>
              </select>
              <input type='text' name='recipe.ingredients[name]' placeholder='Carrots' class='form-control' style='width: 60%; display: inline-block;'></input>
              <a class='btn btn-md btn-danger delete-ingredient-button' href='#' onclick='deleteIngredient(this)'><i class="fa fa-minus" aria-hidden="true"></i></a>
            </div>
</code>```

How recipe is being created on route:

```<code>Recipe.create(req.body.recipe, function(err, newRecipe) {}
</code>```

答:
Name inputs with ingredients as an array in this format recipe.ingredients[][name].

When the form is submitted to the server, the request body will contain the form data in this form:

```<code>recipe {
  ingredients: [
    { quantity: Number, measurement: String, name: String },
    { quantity: Number, measurement: String, name: String },
  ]
}
</code>```

Example:

$(document).ready(function() {
  $('#more_btn').on('click', function(e) {
     e.preventDefault();
     $entries = $('.add-ingredient-form');
     $entry = $entries.last();
     var clone = $entry.clone();
     var namePrefix = 'recipe.ingredients[';
     clone.find('input,select').each(function (i, el){
       el.value = '';
     });
     $entry.append(clone);
  });

  $('#submit_btn').on('click', function(e) {
     e.preventDefault();
     var form = $('#ingredient-form').serializeArray();
     console.log(form);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="ingredient-form">
  <div class='add-ingredient-form'>
    <input type='text' name='recipe.ingredients[][quantity]' placeholder='1' class='form-control' style='width: 10%; display: inline-block;' />
    <select class='form-control' style='width: 15%; display: inline-block;' name='recipe.ingredients[][measurement]'>
    <option>#</option>
    <option>tsp</option>
    <option>tbsp</option>
    <option>cup</option>
    <option>lb</option>
    <option>fl oz</option>
  </select>
    <input type='text' name='recipe.ingredients[][name]' placeholder='Carrots' class='form-control' style='width: 60%; display: inline-block;' />
    <i class="fa fa-minus" aria-hidden="true"></i>
  </div>
  <button id="more_btn">Add Ingredient</button>
  <button id="submit_btn">Submit Form</button>
</form></code>```

Note that:

cloned .add-ingredient-form may need to reset values of form controls to a default.

Body:
I have a mongodb model that looks like this:

ingredients: [
  quantity: Number,
  measurement: String,
  name: String
]

These are being passed in with a single form where the user can add new ingredients by clicking a button which clones the input node and appends it to the parent node. So currently all of the name='' values are the same. As it is now, this is passing in a single array like this:

ingredients: [{
  quantity: ['1','2','3'],
  measurement: ['cup','tsp','tbsp'],
  name: ['rice','cumin','pepper']
}]

Right now the form input is declaring name like name='recipe[ingredients][quantity]' (recipe is the parent object). How do I make this pass multiple objects into the ingredients string?

Relevent section of form:

div class='add-ingredient-form'>
              <input type='text' name='recipe.ingredients[quantity]' placeholder='1' class='form-control' style='width: 10%; display: inline-block;'></input>
              <select class='form-control' style='width: 15%; display: inline-block;' name='recipe.ingredients[measurement]'>
                <option>#</option>
                <option>tsp</option>
                <option>tbsp</option>
                <option>cup</option>
                <option>lb</option>
                <option>fl oz</option>
              </select>
              <input type='text' name='recipe.ingredients[name]' placeholder='Carrots' class='form-control' style='width: 60%; display: inline-block;'></input>

How recipe is being created on route:

Recipe.create(req.body.recipe, function(err, newRecipe) {}

Body:
Name inputs with ingredients as an array in this format recipe.ingredients[][name].

When the form is submitted to the server, the request body will contain the form data in this form:

recipe {
  ingredients: [
    { quantity: Number, measurement: String, name: String },
    { quantity: Number, measurement: String, name: String },
  ]
}

Example:

$(document).ready(function() {
  $('#more_btn').on('click', function(e) {
     e.preventDefault();
     $entries = $('.add-ingredient-form');
     $entry = $entries.last();
     var clone = $entry.clone();
     var namePrefix = 'recipe.ingredients[';
     clone.find('input,select').each(function (i, el){
       el.value = '';
     });
     $entry.append(clone);
  });

  $('#submit_btn').on('click', function(e) {
     e.preventDefault();
     var form = $('#ingredient-form').serializeArray();
     console.log(form);
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="ingredient-form">
  <div class='add-ingredient-form'>
    <input type='text' name='recipe.ingredients[][quantity]' placeholder='1' class='form-control' style='width: 10%; display: inline-block;' />
    <select class='form-control' style='width: 15%; display: inline-block;' name='recipe.ingredients[][measurement]'>
    <option>#</option>
    <option>tsp</option>
    <option>tbsp</option>
    <option>cup</option>
    <option>lb</option>
    <option>fl oz</option>
  </select>
    <input type='text' name='recipe.ingredients[][name]' placeholder='Carrots' class='form-control' style='width: 60%; display: inline-block;' />
    <a class='btn btn-md btn-danger delete-ingredient-button' href='#' onclick='deleteIngredient(this)'><i class="fa fa-minus" aria-hidden="true"></i></a>
  </div>
  <button id="more_btn">Add Ingredient</button>
  <button id="submit_btn">Submit Form</button>
</form>

Note that:

cloned .add-ingredient-form may need to reset values of form controls to a default.


答:
Yes, that is correct. </p>

<p>Your local machine git repo does not know anything about the "Remote Git Repo". When you push your commits from your local machine, it'll be pushed to your "Remote VM". </p>

Title: Git push to another machine

Body:
Yes, that is correct.

Your local machine git repo does not know anything about the "Remote Git Repo". When you push your commits from your local machine, it'll be pushed to your "Remote VM".


问:
Problems while applying a method to an stream of floating numbers array?
I have the following Predictor class, which implements a predict() method:

```<code>class Predictor {

    public static int predict(double[] atts) {
        if (atts.length != 3) {
            return -1;
        }
        int i, j;

        ;

        for (i = 0; i < 2; i++) {
            double sum = 0.;
            for (j = 0; j < 3; j++) {
                sum += Math.log(2. * Math.PI * sigmas[i][j]);
            }
            double nij = -0.5 * sum;
            sum = 0.;
            for (j = 0; j < 3; j++) {
                sum += Math.pow(atts[j] - thetas[i][j], 2.) / sigmas[i][j];
            }
            nij -= 0.5 * sum;
            likelihoods[i] = Math.log(priors[i]) + nij;
        }

        double highestLikeli = Double.NEGATIVE_INFINITY;
        int classIndex = -1;
        for (i = 0; i < 2; i++) {
            if (likelihoods[i] > highestLikeli) {
                highestLikeli = likelihoods[i];
                classIndex = i;
            }
        }
        return classIndex;
    }

    public static void main(String[] args) {
        if (args.length == 3) {
            double[] atts = new double[args.length];
            for (int i = 0, l = args.length; i < l; i++) {
                atts[i] = Double.parseDouble(args[i]);
            }
            System.out.println(Predictor.predict(atts));
        }
    }
}
</code>```

The predict method predicts a number label (i.e. int number 0 or 1). Which I am using inside an android app in order to given an array of floats predict the number label of such array of floats. Visually, this looks as follows:

```<code>arrayOfFloats -> predict_method -> Label(0/1)
</code>```

Note that, arrayOfFloats is a stream of data (consecutively I will have several of this arrays).

Here is the code:

```<code>public void run() { //stuff that updates ui
    finalValues = String.format("%s, %s, %s, %s, %s, %s\n", rollValue, pitchValue, yawValue, gxValue, gyValue, gzValue);
    //finalValues = String.format("%s, %s, %s\n",  rollValue, pitchValue, yawValue);

    Log.e("WalkingActivity", finalValues);

    WalkingLog.setText(finalValues);

    // Classifier
    values[0] = rollValue;
    values[1] = pitchValue;
    values[2] = yawValue;
    //values[3] = gxValue;
    //values[4] = gyValue;
    //values[5] = gzValue;

    int y_pred = Brain.predict(values);

    ClassifierLog.setText(Integer.toString(y_pred));

    System.out.println("pred: " + Integer.toString(y_pred));

    int counter = 0;

    //Simple threshold
    if (rollValue < -40 && rollValue > -80
      && pitchValue < 0 && yawValue > 0
      && gxValue < 1000 && gxValue > -2000
      && gyValue < 500 && gyValue > -1000
      && gzValue < 1000 && gzValue > -2000) {
        ClassifierLog.setText("N");
        System.out.println("COUNTER: " + counter);

    } else {
        counter++;
        ClassifierLog.setText("W");
        System.out.println("COUNTER: " + counter);
    }
}
</code>```

The problem with the above code is that I am always getting the same number label 1 (I am predicting the same number) instead of getting a different output 0 or 1. As far I understand I need to append all the float values in a single array. Although I try to pass such array to the predict method it is not working. However it is not working, which is the correct way to use the predict method from the Predictor class?,

答:
The best way to obtain a solution is to construct & present a very small java class that runs and only contains the bare essentials of the issue you wish to have solved (including the inputs). While it will take you a small amount of effort to do this, it will clearly convey what you are attempting to accomplish.  See my example below.

My best guess is that you are simply looking to pass in an array of three values and return a single result.  If that is the case, then your first code example shows that you are already doing that correctly.

Thus, your issue of always returning 1 is in the logic of the Predictor code itself; i.e. the sigma/theta logic (which you have not conveyed their values).  However, knowing you are passing the values in/out correctly, means you simply need to debug the sigma/theta logic.  For example, after the if statement in the highestLikeli loop, add a sysout:

```

    System.out.format("%d %f %f\n",classIndex,highestLikeli,likelihoods[i]);

```

For reference, here's a small java file showing the array values being passed in and the predictor value being passed out (which is what your question seems to be about).

```<code>

    public class Test {

        public static void main(String[] args) {
            String params[][] = { { "3.3", "4.4", "5.5" }, { "5.5", "3.3", "4.4" }, { "4.4", "5.5", "3.3" } };
            for (int i = 0; i &lt params[0].length; i++) {
                System.out.format("%d: %s, %s, %s =&gt ", i, params[i][0], params[i][1], params[i][2]);
                Predictor.main(params[i]);
            }
        }

        static class Predictor {

            // Simplistic example taking 3 values and returning the index of the largest.
            public static int predict(double[] atts) {
                double highestLikeli = Double.NEGATIVE_INFINITY;
                int classIndex = -1;
                for (int i = 0; i &lt atts.length; i++) {
                    if (atts[i] &gt highestLikeli) {
                        highestLikeli = atts[i];
                        classIndex = i;
                    }
                }
                return classIndex;
            }

            public static void main(String[] args) {
                if (args.length == 3) {
                    double[] atts = new double[args.length];
                    for (int i = 0; i&ltargs.length; i++) {
                        atts[i] = Double.parseDouble(args[i]);
                    }
                    System.out.println(Predictor.predict(atts));
                }
            }
        }
    }

</code>```

Results

```

    0: 3.3, 4.4, 5.5 => 2
    1: 5.5, 3.3, 4.4 => 0
    2: 4.4, 5.5, 3.3 => 1

```

Body:
I have the following Predictor class, which implements a predict() method:

class Predictor {

    public static int predict(double[] atts) {
        if (atts.length != 3) {
            return -1;
        }
        int i, j;

        ;

        for (i = 0; i < 2; i++) {
            double sum = 0.;
            for (j = 0; j < 3; j++) {
                sum += Math.log(2. * Math.PI * sigmas[i][j]);
            }
            double nij = -0.5 * sum;
            sum = 0.;
            for (j = 0; j < 3; j++) {
                sum += Math.pow(atts[j] - thetas[i][j], 2.) / sigmas[i][j];
            }
            nij -= 0.5 * sum;
            likelihoods[i] = Math.log(priors[i]) + nij;
        }

        double highestLikeli = Double.NEGATIVE_INFINITY;
        int classIndex = -1;
        for (i = 0; i < 2; i++) {
            if (likelihoods[i] > highestLikeli) {
                highestLikeli = likelihoods[i];
                classIndex = i;
            }
        }
        return classIndex;
    }

    public static void main(String[] args) {
        if (args.length == 3) {
            double[] atts = new double[args.length];
            for (int i = 0, l = args.length; i < l; i++) {
                atts[i] = Double.parseDouble(args[i]);
            }
            System.out.println(Predictor.predict(atts));
        }
    }
}

The predict method predicts a number label (i.e. int number 0 or 1). Which I am using inside an android app in order to given an array of floats predict the number label of such array of floats. Visually, this looks as follows:

arrayOfFloats -> predict_method -> Label(0/1)

Note that, arrayOfFloats is a stream of data (consecutively I will have several of this arrays).

Here is the code:

public void run() { //stuff that updates ui
    finalValues = String.format("%s, %s, %s, %s, %s, %s\n", rollValue, pitchValue, yawValue, gxValue, gyValue, gzValue);
    //finalValues = String.format("%s, %s, %s\n",  rollValue, pitchValue, yawValue);

    Log.e("WalkingActivity", finalValues);

    WalkingLog.setText(finalValues);

    // Classifier
    values[0] = rollValue;
    values[1] = pitchValue;
    values[2] = yawValue;
    //values[3] = gxValue;
    //values[4] = gyValue;
    //values[5] = gzValue;

    int y_pred = Brain.predict(values);

    ClassifierLog.setText(Integer.toString(y_pred));

    System.out.println("pred: " + Integer.toString(y_pred));

    int counter = 0;

    //Simple threshold
    if (rollValue < -40 && rollValue > -80
      && pitchValue < 0 && yawValue > 0
      && gxValue < 1000 && gxValue > -2000
      && gyValue < 500 && gyValue > -1000
      && gzValue < 1000 && gzValue > -2000) {
        ClassifierLog.setText("N");
        System.out.println("COUNTER: " + counter);

    } else {
        counter++;
        ClassifierLog.setText("W");
        System.out.println("COUNTER: " + counter);
    }
}

The problem with the above code is that I am always getting the same number label 1 (I am predicting the same number) instead of getting a different output 0 or 1. As far I understand I need to append all the float values in a single array. Although I try to pass such array to the predict method it is not working. However it is not working, which is the correct way to use the predict method from the Predictor class?,

Body:
The best way to obtain a solution is to construct & present a very small java class that runs and only contains the bare essentials of the issue you wish to have solved (including the inputs). While it will take you a small amount of effort to do this, it will clearly convey what you are attempting to accomplish.  See my example below.

My best guess is that you are simply looking to pass in an array of three values and return a single result.  If that is the case, then your first code example shows that you are already doing that correctly.

Thus, your issue of always returning 1 is in the logic of the Predictor code itself; i.e. the sigma/theta logic (which you have not conveyed their values).  However, knowing you are passing the values in/out correctly, means you simply need to debug the sigma/theta logic.  For example, after the if statement in the highestLikeli loop, add a sysout:

    System.out.format("%d %f %f\n",classIndex,highestLikeli,likelihoods[i]);

For reference, here's a small java file showing the array values being passed in and the predictor value being passed out (which is what your question seems to be about).

    public class Test {

        public static void main(String[] args) {
            String params[][] = { { "3.3", "4.4", "5.5" }, { "5.5", "3.3", "4.4" }, { "4.4", "5.5", "3.3" } };
            for (int i = 0; i &lt params[0].length; i++) {
                System.out.format("%d: %s, %s, %s =&gt ", i, params[i][0], params[i][1], params[i][2]);
                Predictor.main(params[i]);
            }
        }

        static class Predictor {

            // Simplistic example taking 3 values and returning the index of the largest.
            public static int predict(double[] atts) {
                double highestLikeli = Double.NEGATIVE_INFINITY;
                int classIndex = -1;
                for (int i = 0; i &lt atts.length; i++) {
                    if (atts[i] &gt highestLikeli) {
                        highestLikeli = atts[i];
                        classIndex = i;
                    }
                }
                return classIndex;
            }

            public static void main(String[] args) {
                if (args.length == 3) {
                    double[] atts = new double[args.length];
                    for (int i = 0; i&ltargs.length; i++) {
                        atts[i] = Double.parseDouble(args[i]);
                    }
                    System.out.println(Predictor.predict(atts));
                }
            }
        }
    }

Results

    0: 3.3, 4.4, 5.5 => 2
    1: 5.5, 3.3, 4.4 => 0
    2: 4.4, 5.5, 3.3 => 1


问:
Displaying generic data into tab contents
I am sure this is very simple but i am not able to display data under every item tab. I am having problems with where to place the for loops to get the right structure of the tab contents. How can i do this please?

HTML

```<code>      <div class="row">
            <div class="col-md-7">
              <div class="nav-tabs-custom">
              <ul class="nav nav-tabs">
                   @foreach($items as $item)

              <li><a href="#tab_1" data-toggle="tab" >{!!$item->name!!}</a></li>

              </ul>
               //data for a item tab is displayed here -- content
              <div class="tab-content">
              <div class="tab-pane active" id="tab_1">

              @foreach($item->stuff as $data)

              <label class="mylabel" >  {{$data->name}} </label>
              @endforeach

              @endforeach

               </div>

               </div>

              </div>

            </div>
</code>```

答:
You would need to loop over your items twice, once to build the tabs ul list and then again to display the content for each tab.

Something like:

```<code><div class="row">
    <div class="col-md-7">
        <div class="nav-tabs-custom">
            // Links for the tabs
            <ul class="nav nav-tabs">
                @foreach($items as $key => $item)
                    <li><a href="#tab_{{ $key }}" data-toggle="tab" >{!! $item->name !!}</a></li>
                @endforeach
            </ul>

            // Data for the tabs
            <div class="tab-content">
                @foreach($items as $key => $item)
                    <div class="tab-pane{{ $key == 1 ? ' active' : '' }}" id="tab_{{ $key }}">
                        @foreach($item->stuff as $data)
                            <label class="mylabel">{{ $data->name }}</label>
                        @endforeach
                    </div>
                @endforeach
            </div>
        </div>
    </div>
</div>
</code>```

Body:
I am sure this is very simple but i am not able to display data under every item tab. I am having problems with where to place the for loops to get the right structure of the tab contents. How can i do this please?

HTML

                   @foreach($items as $item)

{!!$item->name!!}

               //data for a item tab is displayed here -- content

              @foreach($item->stuff as $data)

                {{$data->name}}
              @endforeach

              @endforeach

Body:
You would need to loop over your items twice, once to build the tabs ul list and then again to display the content for each tab.

Something like:

<div class="row">
    <div class="col-md-7">
        <div class="nav-tabs-custom">
            // Links for the tabs
            <ul class="nav nav-tabs">
                @foreach($items as $key => $item)
                    <li><a href="#tab_{{ $key }}" data-toggle="tab" >{!! $item->name !!}</a></li>
                @endforeach
            </ul>

            // Data for the tabs
            <div class="tab-content">
                @foreach($items as $key => $item)
                    <div class="tab-pane{{ $key == 1 ? ' active' : '' }}" id="tab_{{ $key }}">
                        @foreach($item->stuff as $data)
                            <label class="mylabel">{{ $data->name }}</label>
                        @endforeach
                    </div>
                @endforeach
            </div>
        </div>
    </div>
</div>


问:
multiple validation for single field
I have 3 fields 'account_name','billable_option' and 'billable_option_yes'
'billable_option' is required if 'billable_option_yes' is not filled and 'billable_option_yes' is required if 'billable_option' is not filled

and I want to check both field is not required if 'account_name' value is 0
I want to combine the validation required_unless:account_name,0

```<code>if($account!=0){ } not working

$account=$request->account_name;
     if($account!=0){ //not working
                $this->validate($request,[
                'billable_option' => 'required_without:billable_option_yes',
                'billable_option_yes' =>'required_without:billable_option',
                ],$messages);
    }
   $messages=[
            'billable_option.required_without'=>'The Billable is Required',
            'billable_option_yes.required_without'=>'The Billable optoion is Required',
       ];
      $this->validate($request,[
        ...
       'billable'=>'required_unless:account_name,0', //fourth field working fine
        ..
      ],$messages);
</code>```

答:
You might want to check the Require if validation rule from the docs.

required_if:anotherfield,value,...

  The field under validation must be present and not empty if the anotherfield field is equal to any value.

Title: multiple validation for single field

Body:
I have 3 fields 'account_name','billable_option' and 'billable_option_yes'
'billable_option' is required if 'billable_option_yes' is not filled and 'billable_option_yes' is required if 'billable_option' is not filled

and I want to check both field is not required if 'account_name' value is 0
I want to combine the validation required_unless:account_name,0

if($account!=0){ } not working

$account=$request->account_name;
     if($account!=0){ //not working
                $this->validate($request,[
                'billable_option' => 'required_without:billable_option_yes',
                'billable_option_yes' =>'required_without:billable_option',
                ],$messages);
    }
   $messages=[
            'billable_option.required_without'=>'The Billable is Required',
            'billable_option_yes.required_without'=>'The Billable optoion is Required',
       ];
      $this->validate($request,[
        ...
       'billable'=>'required_unless:account_name,0', //fourth field working fine
        ..
      ],$messages);


答:
You can integrate Application crash report for Android(ACRA) with your application. So many application on play store using this and very helpful. You can send data based on your requirement.

The main benefit is you can set up your own environment for server-side and no dependency on any others.

Check below link for more information.
https://github.com/ACRA/acra

Title: Sending log files to server after Android app crashed

Body: I have an Android app, and I'm able to log the crash details in a text file. I want to show a message after an app crash, and I need to send the log file to the server. Any suggestions will be helpful.


问:
Application running in websphere liberty 17.0.0.2 or latest 17.0.0.3 is not able to utilize proxy system properties
I created a sample web application for POC. This application running in Amazon EC2 liberty 17.0.0.2. When we send get request to servlet as below it has to send message to AWS SQS.

http://localhost:8080/TestSqsWeb/SqsServlet?message=Hello333

Our EC2 is coorporate EC2, it needs proxy to connect to internet. So I provided proxy configuration in jvm.options file in liberty.

```<code>-Dhttps.nonProxyHosts=169.254.169.254|localhost|127.0.0.1
-Dhttp.nonProxyHosts=169.254.169.254|localhost|127.0.0.1
-Dhttp.proxyHost=proxy.ebiz.abc.com
-Dhttp.proxyPort=80
-Dhttps.proxyHost=proxy.ebiz.abc.com
-Dhttps.proxyPort=80
</code>```

It is keep giving below exception.

```<code>org.apache.http.conn.ConnectTimeoutException: Connect to sqs.us-west-2.amazonaws.com:443 [sqs.us-west-2.amazonaws.com/52.119.168.22] failed: connect timed out
</code>```

After further analysis I found it is not taking proxy system properties while making connection. I did printing of all system property in code using System.getProperty. It prints my system properties, it means configuration is correct.

For further analysis I deployed same app in tomcat-8 in same EC2 with same proxy configuration , it is working. It is able to make connection and send my message to AWS SQS queue.

After this analysis I concluded that there is some issue in liberty.

[Libraries in my sample app][1]

```<code>  [1]: https://i.stack.imgur.com/K2gbj.png
</code>```

In one of post I found, it can happen due to old version of http-client but I am using latest httpclient-4.5.2.jar and httpcore-4.4.4.jar as you can see in above link.

Has any one encountered same issue with Liberty 17.0.0.2/17.0.0.3 ? I am using IBM JAVA SDK-8.

答:
As I understand it, those proxy system properties work for HTTP connection classes provided by the JDK - like HttpUrlConnection.  Depending on you use Apache HTTP Client, it may not use those APIs.

Instead of using the JDK-supplied system properties, you may want to modify your code like this:

```<code>    public static void main(String[] args)throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpHost target = new HttpHost("httpbin.org", 443, "https");
            HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");

            RequestConfig config = RequestConfig.custom()
                .setProxy(proxy)
                .build();
            HttpGet request = new HttpGet("/");
            request.setConfig(config);
            ...
</code>```

This code sample was taken from the Apache HTTP Client examples page.

There are other samples (including proxy authentication) here:
https://hc.apache.org/httpcomponents-client-ga/examples.html

Hope this helps,
Andy

Body:
I created a sample web application for POC. This application running in Amazon EC2 liberty 17.0.0.2. When we send get request to servlet as below it has to send message to AWS SQS.

http://localhost:8080/TestSqsWeb/SqsServlet?message=Hello333

Our EC2 is coorporate EC2, it needs proxy to connect to internet. So I provided proxy configuration in jvm.options file in liberty.

-Dhttps.nonProxyHosts=169.254.169.254|localhost|127.0.0.1
-Dhttp.nonProxyHosts=169.254.169.254|localhost|127.0.0.1
-Dhttp.proxyHost=proxy.ebiz.abc.com
-Dhttp.proxyPort=80
-Dhttps.proxyHost=proxy.ebiz.abc.com
-Dhttps.proxyPort=80

It is keep giving below exception.

org.apache.http.conn.ConnectTimeoutException: Connect to sqs.us-west-2.amazonaws.com:443 [sqs.us-west-2.amazonaws.com/52.119.168.22] failed: connect timed out

After further analysis I found it is not taking proxy system properties while making connection. I did printing of all system property in code using System.getProperty. It prints my system properties, it means configuration is correct.

For further analysis I deployed same app in tomcat-8 in same EC2 with same proxy configuration , it is working. It is able to make connection and send my message to AWS SQS queue.

After this analysis I concluded that there is some issue in liberty.

[Libraries in my sample app][1]

  [1]: https://i.stack.imgur.com/K2gbj.png

In one of post I found, it can happen due to old version of http-client but I am using latest httpclient-4.5.2.jar and httpcore-4.4.4.jar as you can see in above link.

Has any one encountered same issue with Liberty 17.0.0.2/17.0.0.3 ? I am using IBM JAVA SDK-8.

Body:
As I understand it, those proxy system properties work for HTTP connection classes provided by the JDK - like HttpUrlConnection.  Depending on you use Apache HTTP Client, it may not use those APIs.

Instead of using the JDK-supplied system properties, you may want to modify your code like this:

    public static void main(String[] args)throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpHost target = new HttpHost("httpbin.org", 443, "https");
            HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");

            RequestConfig config = RequestConfig.custom()
                .setProxy(proxy)
                .build();
            HttpGet request = new HttpGet("/");
            request.setConfig(config);
            ...

This code sample was taken from the Apache HTTP Client examples page.

There are other samples (including proxy authentication) here:
https://hc.apache.org/httpcomponents-client-ga/examples.html

Hope this helps,
Andy


问:
Date.prototype.getHours() not work
chrome v61.0.3163.100

```<code>var date = new Date("2017-11-15T04:00:00Z");
console.log(date) //Wed Nov 15 2017 04:00:00 GMT+0000 (UTC)
console.log(date.getHours() === date.getUTCHours()) //true
</code>```

safari v11.0 (12604.1.38.1.7)

```<code>var date = new Date("2017-11-15T04:00:00Z");
console.log(date) //Wed Nov 15 2017 12:00:00 GMT+0800 (CST)
console.log(date.getHours() === date.getUTCHours()) //false
</code>```

Why the same piece of code in different browsers operating results are different, sometimes in the same browser, there are differences

---------update-----------

When I reply to you, Chrome has output "Wed Nov 15 2017 12:00:00 GMT + 0800 (CST)", this is a sad question. In the meantime, I only had lunch and did not set the timeZone.

```<code>Intl.DateTimeFormat().resolvedOptions().timeZone

after => "America/Chicago"

befor => "China/Shanghai"(this is true)
</code>```

mdn document: An integer number, between 0 and 23, representing the hour for the given date according to local time.

答:
As you can see in the second example, the time is stored with an offset (+0800), while in the first, it is not (+0000). getHours() returns the local hour, while getUTCHours() is the UTC hour.

The difference appears to be in the browser storage of the timezone, which both have their advantages. Obviously which one you use depends on the circumstance, but the difference lies in the offset (shown in the string representation).

Title: Date.prototype.getHours() not work

Body:
chrome v61.0.3163.100

var date = new Date("2017-11-15T04:00:00Z");
console.log(date) //Wed Nov 15 2017 04:00:00 GMT+0000 (UTC)
console.log(date.getHours() === date.getUTCHours()) //true

safari v11.0 (12604.1.38.1.7)

var date = new Date("2017-11-15T04:00:00Z");
console.log(date) //Wed Nov 15 2017 12:00:00 GMT+0800 (CST)
console.log(date.getHours() === date.getUTCHours()) //false

Why the same piece of code in different browsers operating results are different, sometimes in the same browser, there are differences

---------update-----------

When I reply to you, Chrome has output "Wed Nov 15 2017 12:00:00 GMT + 0800 (CST)", this is a sad question. In the meantime, I only had lunch and did not set the timeZone.

Intl.DateTimeFormat().resolvedOptions().timeZone

after => "America/Chicago"

befor => "China/Shanghai"(this is true)

mdn document: An integer number, between 0 and 23, representing the hour for the given date according to local time.


问:
how to set httponly and session cookie for java web application
I am working on an XSS (cross site scripting) issue.  My application runs on an Oracle Weblogic portal.  We use Servlet version 2.5.

I have added the below 3 lines of code in the filter for setting httponly and secure cookies,
and it is working fine.

```<code>String sessionid = req.getSession().getId();
res.setHeader("Set-Cookie", "JSESSIONID=" +  sessionid + ";HttpOnly");
res.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid + "; secure");
</code>```

The issue is when I logout and login immediately in the same browser.  I am able to login, but after that, on the jsp pages I am getting a session timeout issue.  We use weblogic related apis.  The request.getuserprinical() api is returning null..  guess it is setting to null.

Please share any ideas.

If there are any other ways to set httponly or secure flag, please help.

答:
I have used  <http-only> and <secure> tags in web.xml to set the secure attributes and it worked.

```<code><session-config>
 <cookie-config>
  <http-only>true</http-only>
 </cookie-config>
<session-config>
</code>```

Body:
I am working on an XSS (cross site scripting) issue.  My application runs on an Oracle Weblogic portal.  We use Servlet version 2.5.

I have added the below 3 lines of code in the filter for setting httponly and secure cookies,
and it is working fine.

String sessionid = req.getSession().getId();
res.setHeader("Set-Cookie", "JSESSIONID=" +  sessionid + ";HttpOnly");
res.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid + "; secure");

The issue is when I logout and login immediately in the same browser.  I am able to login, but after that, on the jsp pages I am getting a session timeout issue.  We use weblogic related apis.  The request.getuserprinical() api is returning null..  guess it is setting to null.

Please share any ideas.

If there are any other ways to set httponly or secure flag, please help.

Body:
I have used  <http-only> and <secure> tags in web.xml to set the secure attributes and it worked.

<session-config>
 <cookie-config>
  <http-only>true</http-only>
 </cookie-config>
<session-config>


问:
GSON from JSON with numeric class names
I have a JSON string coming from a server, and I have no control over it.

I generated the Java classes through programmatic usage of the jsonschema2pojo library.

I am using GSON to deserialize the JSON into my Java objects.

Here is an example of the JSON.

```<code>"description_by_id": {
    "50": {
        "field1": "value1",
        "field2": "value2",
        "field3": "value3"
    }
}
</code>```

That "50" subclass is actually just 1 of 18 classes that are similarly named as a number.

When jsonschema2pojo generates the Java class, it understandably prepends an underscore to create the class name (so, _50).

jsonschema2pojo generates the DescriptionById class with this member:

@JsonProperty("50")
    private com.me.models._50 _50;

And the getter looks like this (setter is similar):

@JsonProperty("50")
    public com.me.models._50 get50() {
        return _50;
    }

I am using GSON like this:

Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();

But the _50 object and the other 17 like it are all null after GSON is done, and I have checked that the corresponding spots in the JSON are actually filled in with real values.

Is there anything along this chain that I can do to get it working properly without needing to manually hack around the issue?

答:
That "50" subclass is actually just 1 of 18 classes that are similarly named as a number

And what happens when you get one additional ID that you don't have a Java class for? Gson won't know what to do with it...

Don't make classes. Use a Map.

Make this "inner" POJO

```<code>public class Inner {

    private String field1;
    private String field2;
    private String field3;

}
</code>```

And the outer POJO

```<code>public class Outer {
    private TreeMap<String, Inner> description_by_id;
}
</code>```

And you would then have someOuter.getDescriptionById("50").getField1()

(Add back in the Gson attributes as necessary)

Title: GSON from JSON with numeric class names

Body:
I have a JSON string coming from a server, and I have no control over it.

I generated the Java classes through programmatic usage of the jsonschema2pojo library.

I am using GSON to deserialize the JSON into my Java objects.

Here is an example of the JSON.

"description_by_id": {
    "50": {
        "field1": "value1",
        "field2": "value2",
        "field3": "value3"
    }
}

That "50" subclass is actually just 1 of 18 classes that are similarly named as a number.

When jsonschema2pojo generates the Java class, it understandably prepends an underscore to create the class name (so, _50).

jsonschema2pojo generates the DescriptionById class with this member:

@JsonProperty("50")
    private com.me.models._50 _50;

And the getter looks like this (setter is similar):

@JsonProperty("50")
    public com.me.models._50 get50() {
        return _50;
    }

I am using GSON like this:

Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();

But the _50 object and the other 17 like it are all null after GSON is done, and I have checked that the corresponding spots in the JSON are actually filled in with real values.

Is there anything along this chain that I can do to get it working properly without needing to manually hack around the issue?

Body:
That "50" subclass is actually just 1 of 18 classes that are similarly named as a number

And what happens when you get one additional ID that you don't have a Java class for? Gson won't know what to do with it...

Don't make classes. Use a Map.

Make this "inner" POJO

public class Inner {

    private String field1;
    private String field2;
    private String field3;

}

And the outer POJO

public class Outer {
    private TreeMap<String, Inner> description_by_id;
}

And you would then have someOuter.getDescriptionById("50").getField1()

(Add back in the Gson attributes as necessary)


问:
Is there any way to get iOS crash report of its application programmatically?
After doing some research, I've tried these and here's what I've got:

I found out that crash logs are put in this folder:

/var/mobile/Library/Logs/CrashReporter/

With this information, I tried to:

Get files under this path by using

```<code>[[NSFileManager defaultManager]  contentsOfDirectoryAtPath:crashReportPath error:&error];
</code>```

But I always get NSCocoaErrorDomain 257, which means I don't have the permission.

Therefore, I tried to set permission to this folder by using

```<code>NSFileManager *manager = [NSFileManager defaultManager];
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:[manager attributesOfItemAtPath:crashReportPath error:nil]];
[attributes setValue:[NSNumber numberWithShort:0777] forKey:NSFilePosixPermissions];; // chmod permissions 777
[manager setAttributes:attributes ofItemAtPath:crashReportPath error:&error];
</code>```

But I always get NSCocoaErrorDomain 513 NSFileWriteNoPermissionError which means I don't have the permission to write.

Without luck, I've tried this post:
iPhone sdk read crash files programmatically?
to handle the unhandled exceptions by setting NSSetUncaughtExceptionHandler but this seemed to have some problems since sometimes the application might be left in an unstable or invalid state.

I know there are many third-party crash report plugins but most of them just generate its report of certain signals monitored, not the real crash reports.

Any suggestions on getting the real crash report?
Is there any other way around?

答:
I found the best way to implement crash reporting on our own server.

Implement this Crash Manager with your project it will give you maximum possible crashes and you can upload crash reports to your own server.

Or else you can also do without using of any library or third party code.
Refer this - How can we store crash logs in iOS application

Body:
After doing some research, I've tried these and here's what I've got:

I found out that crash logs are put in this folder:

/var/mobile/Library/Logs/CrashReporter/

With this information, I tried to:

Get files under this path by using

[[NSFileManager defaultManager]  contentsOfDirectoryAtPath:crashReportPath error:&error];

But I always get NSCocoaErrorDomain 257, which means I don't have the permission.

Therefore, I tried to set permission to this folder by using

NSFileManager *manager = [NSFileManager defaultManager];
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:[manager attributesOfItemAtPath:crashReportPath error:nil]];
[attributes setValue:[NSNumber numberWithShort:0777] forKey:NSFilePosixPermissions];; // chmod permissions 777
[manager setAttributes:attributes ofItemAtPath:crashReportPath error:&error];

But I always get NSCocoaErrorDomain 513 NSFileWriteNoPermissionError which means I don't have the permission to write.

Without luck, I've tried this post:
iPhone sdk read crash files programmatically?
to handle the unhandled exceptions by setting NSSetUncaughtExceptionHandler but this seemed to have some problems since sometimes the application might be left in an unstable or invalid state.

I know there are many third-party crash report plugins but most of them just generate its report of certain signals monitored, not the real crash reports.

Any suggestions on getting the real crash report?
Is there any other way around?


问:
Install and configure supervisord on centos 7 to run Laravel queues permanently
I want to use Laravel queue system in my project and I want to run php artisan queue:work permanently on server's background, I did some searches about this and I found a command line which can run it even after quit from ssh terminal but It can be down in some cases and can make terrible problems for me. So after a while I found out that there is a package named Supervisord which can restart command even after server is rebooted. So I want to ask someone to help from 0 to 100 step by step how to install Supervisord and configure it on centos 7 and after that set the queue command line. Thank you so much..

答:
here is how to install and config supervisord on centos 7 to run Laravel queues permanently:

easy_install supervisor

yum install supervisor

vim /etc/supervisord.conf edit section program as following:

```<code>[program:laravel-worker]
command=php /path/to/app.com/artisan queue:work
process_name=%(program_name)s_%(process_num)02d
numprocs=8
priority=999
autostart=true
autorestart=true
startsecs=1
startretries=3
user=apache
redirect_stderr=true
stdout_logfile=/path/to/log/worker.log
</code>```

systemctl enable supervisord to autorun at start

systemctl restart supervisord to restart the service

Body:
here is how to install and config supervisord on centos 7 to run Laravel queues permanently:

easy_install supervisor

yum install supervisor

vim /etc/supervisord.conf edit section program as following:

[program:laravel-worker]
command=php /path/to/app.com/artisan queue:work
process_name=%(program_name)s_%(process_num)02d
numprocs=8
priority=999
autostart=true
autorestart=true
startsecs=1
startretries=3
user=apache
redirect_stderr=true
stdout_logfile=/path/to/log/worker.log

systemctl enable supervisord to autorun at start

systemctl restart supervisord to restart the service


问:
What's wrong if compiler optimization is turned on in debug build?
Why is it necessary/recommended to turn off all compiler optimizations when debugging application?

Background

I'm working in an 8-bit micro controller (OKI 411) which has 15K usable code memory space for interrupt service routines + ROM region/window (const global variables) + code. We nearly eat up ~13K so it is very tempting to turn on maximum possible optimization during even debugging.

答:
When compiling a debug binary, the compiler tries to maintain a 1:1 correspondence between code statements (or pieces of code statements) to assembly language instructions.  This way, when you are debugging, you can step through, instruction by instruction, and it is easy for the debugger to correlate its current position in the binary with the correct source code.  Usually the compiler also ensures that all named variables actually exist somewhere in memory so that you can view their contents in the debugger.

Compiler optimizations may elide unused or unnecessary local variables and may restructure your code so that it is more efficient.  Functions may be inlined and expressions may be partially or wholly precomputed or rearranged.  Most of these and similar optimizations make it difficult to correlate the original source code with the generated assembly.


问:
How to authenticate in Remedy using Java
I need to authenticate myself in Remedy. I'm following the documentation, but I still getting some errors.
https://communities.bmc.com/docs/DOC-17514

This is my code:

```<code>import com.bmc.arsys.api.ARException;
import com.bmc.arsys.api.ARServerUser;

public class Tutorial {
    public static void main(String[] args) {
        ARServerUser ctx = new ARServerUser();
        ctx.setServer("127.0.0.1");
        ctx.setUser("myusername");
        ctx.setPassword("mypassword");
        ctx.setPort(8080);

        try {
            ctx.verifyUser();
        } catch (ARException e) {
            System.out.println(e.getMessage());
        }
    }
}
</code>```

I'm receiving this error:
ERROR (91): RPC call failed; 127.0.0.1:8080 can not receive ONC/RPC data

How can I fix that? I need to set the instance, like 127.0.0.1/arsys. My Remedy instance is arsys.

I can authenticate using the browser: http://127.0.0.1:8080/arsys

Thanks in advance.

答: Since you have mentioned that you are able to authenticate using http://127.0.0.1:8080/arsys via browser, it means that 8080 is being used by web server and AR Server can't use the same. Please provide your port number(where your AR Server is listening) in setPort(). Also try to make sure that your hostname/ip address is reachable from the machine where you are executing your program.</p>

Body:
I need to authenticate myself in Remedy. I'm following the documentation, but I still getting some errors.
https://communities.bmc.com/docs/DOC-17514

This is my code:

import com.bmc.arsys.api.ARException;
import com.bmc.arsys.api.ARServerUser;

public class Tutorial {
    public static void main(String[] args) {
        ARServerUser ctx = new ARServerUser();
        ctx.setServer("127.0.0.1");
        ctx.setUser("myusername");
        ctx.setPassword("mypassword");
        ctx.setPort(8080);

        try {
            ctx.verifyUser();
        } catch (ARException e) {
            System.out.println(e.getMessage());
        }
    }
}

I'm receiving this error:
ERROR (91): RPC call failed; 127.0.0.1:8080 can not receive ONC/RPC data

How can I fix that? I need to set the instance, like 127.0.0.1/arsys. My Remedy instance is arsys.

I can authenticate using the browser: http://127.0.0.1:8080/arsys

Thanks in advance.


问:
Dropdown field in a form to populate a few hidden fields in a form
I'm have an registration form for visitors to sign up for talks on my page.
The problem is that I have 4 different talks they can sign up for.
So I would like to have them select the talk they want to attend and store the talk details e.g. Date, Time and Session in separate fields.

The code below show me storing my talk sessions registered as:

 25th Nov 10:00am on EFFECTIVE LEARNING

I would like to have my confirmation email showing :

Date : 25th Nov

Time : 10:00am

Session : EFFECTIVE LEARNING

Would appreciate any help in this matter.

```<code>    <select class="validate-required" name="Session" placeholder="Your Session Choice" data-error-text="You need to select a Session to attend">
        <option selected="25th Nov  2:00pm on LEARNING MADE EASY" value="">Select</option>
        <option value="25th Nov 10:00am on EFFECTIVE LEARNING">EFFECTIVE LEARNING</option>
        <option value="25th Nov  2:00pm on LEARNING MADE EASY">LEARNING MADE EASY</option>
        <option value="26th Nov 10:00am on TURNING THE C's & B's into A's">TURNING THE C's & B's into A's</option>
        <option value="26th Nov  2:00pm on DRAWING OUT THE SPECIAL CHILD">DRAWING OUT THE SPECIAL CHILD</option>
    </select>
</code>```

答:
```<code><select class="validate-required" name="Session" id="sessions" placeholder="Your Session Choice" data-error-text="You need to select a Session to attend">
        <option value="0" selected>Select One</option>
        <option data-date="26th Nov" data-time="3:00pm" data-session="EFFECTIVE LEARNING" value="1">EFFECTIVE LEARNING</option>
        <option data-date="27th Nov" data-time="4:00pm" data-session="HTML Learning" value="2">LEARNING MADE EASY</option>
        <option data-date="28th Nov" data-time="5:00pm" data-session="JavaScript Learning" value="3">TURNING THE C's & B's into A's</option>
        <option data-date="29th Nov" data-time="6:00pm" data-session="PHP Learning" value="4">DRAWING OUT THE SPECIAL CHILD</option>
</select>

<script type="text/javascript">
    document.getElementById("sessions").addEventListener("change", function(el){
        var value = document.getElementById('sessions').options[this.selectedIndex].getAttribute('value');
        if (value != "0") {
            var session = document.getElementById('sessions').options[this.selectedIndex].getAttribute('data-session');
            var date = document.getElementById('sessions').options[this.selectedIndex].getAttribute('data-date');
            var time = document.getElementById('sessions').options[this.selectedIndex].getAttribute('data-time');
            alert('Session: '+session);
            alert('Date:'+date);
            alert('Time:'+time);
        } else {
            alert("You must select a valid option.");
        }
        });
</script>
</code>```

Body:
I'm have an registration form for visitors to sign up for talks on my page.
The problem is that I have 4 different talks they can sign up for.
So I would like to have them select the talk they want to attend and store the talk details e.g. Date, Time and Session in separate fields.

The code below show me storing my talk sessions registered as:

 25th Nov 10:00am on EFFECTIVE LEARNING

I would like to have my confirmation email showing :

Date : 25th Nov

Time : 10:00am

Session : EFFECTIVE LEARNING

Would appreciate any help in this matter.

    <select class="validate-required" name="Session" placeholder="Your Session Choice" data-error-text="You need to select a Session to attend">
        <option selected="25th Nov  2:00pm on LEARNING MADE EASY" value="">Select</option>
        <option value="25th Nov 10:00am on EFFECTIVE LEARNING">EFFECTIVE LEARNING</option>
        <option value="25th Nov  2:00pm on LEARNING MADE EASY">LEARNING MADE EASY</option>
        <option value="26th Nov 10:00am on TURNING THE C's & B's into A's">TURNING THE C's & B's into A's</option>
        <option value="26th Nov  2:00pm on DRAWING OUT THE SPECIAL CHILD">DRAWING OUT THE SPECIAL CHILD</option>
    </select>

Body:
<select class="validate-required" name="Session" id="sessions" placeholder="Your Session Choice" data-error-text="You need to select a Session to attend">
        <option value="0" selected>Select One</option>
        <option data-date="26th Nov" data-time="3:00pm" data-session="EFFECTIVE LEARNING" value="1">EFFECTIVE LEARNING</option>
        <option data-date="27th Nov" data-time="4:00pm" data-session="HTML Learning" value="2">LEARNING MADE EASY</option>
        <option data-date="28th Nov" data-time="5:00pm" data-session="JavaScript Learning" value="3">TURNING THE C's &amp; B's into A's</option>
        <option data-date="29th Nov" data-time="6:00pm" data-session="PHP Learning" value="4">DRAWING OUT THE SPECIAL CHILD</option>
</select>

<script type="text/javascript">
    document.getElementById("sessions").addEventListener("change", function(el){
        var value = document.getElementById('sessions').options[this.selectedIndex].getAttribute('value');
        if (value != "0") {
            var session = document.getElementById('sessions').options[this.selectedIndex].getAttribute('data-session');
            var date = document.getElementById('sessions').options[this.selectedIndex].getAttribute('data-date');
            var time = document.getElementById('sessions').options[this.selectedIndex].getAttribute('data-time');
            alert('Session: '+session);
            alert('Date:'+date);
            alert('Time:'+time);
        } else {
            alert("You must select a valid option.");
        }
        });
</script>