问:
How to automatically set the Signing Team on IOS cordova project?
I am trying to automate the build/deployment of my hybdrid mobile application in Jenkins using fastlane.
I use ionic (v3.3.0) and cordova (v7.0.1) for the source. I use fastlane v2.36.0 and Xcode is version 8.3.2.

The command I run in the jenkins job

```<code>yarn
ionic cordova prepare
fastlane ios build
</code>```

The fastlane/FastFile

```<code>platform :ios do
  before_all do
  end

  ios_project_path = "platforms/ios/awesomeproject.xcodeproj"

  desc "Build for IOS"
  lane :build do
    increment_build_number(
      xcodeproj: ios_project_path,
      build_number: ENV["BUILD_NUMBER"]
    )

    # Recreate schemes to ensure a smooth transition from cordova to gym
    recreate_schemes(project: ios_project_path)

    update_project_team(
      path: ios_project_path,
      teamid: "TEAMID"
    )

    #update_provisioning_profile_specifier(xcodeproj: ios_project_path)

      gym(scheme: "awesomeproject",
          configuration: "Debug",
          clean: true,
          project: ios_project_path,
          output_directory: "target")
  end
end
</code>```

The fastlane/Appfile

```<code>package_name "com.xxx.awesomeapp"

app_identifier "com.xxx.awesomeapp" # The bundle identifier of your app
apple_id "xxx.xxxx@xxx.com" # Your Apple email address

team_id "TEAMID" # Developer Portal Team ID
</code>```

The command fastlane ios build is failing on the gym instruction with the error

Code signing is required for product type 'Application' in SDK 'iOS
  10.3'

The detailed error in the fastlane log is

Check dependencies Signing for "awesomeproject" requires a development
  team. Select a development team in the project editor. Code signing is
  required for product type 'Application' in SDK 'iOS
  10.3'

The xcode project generated by Cordova has the Automatic signing activated but it is missing the Signing Team.
The workaround I used so far is to manually select the Team with Xcode the first time the platform/ios folder is generated. But if I remove the platform folder generated by cordova, I need to redo the selection of the team in XCode.

Is there a way to select with Cordova or any fastlane plugin the Signing team? I am open to use any solution, script.
So my build will be fully automated. The update_project_team instruction is not working.

答:
Create a file called build.json in the root directory of your project, with the Team ID and provisioning profile GUID you want to use to sign the app:

build.json:

```<code>{
  "ios": {
    "debug": {
      "codeSignIdentity": "iPhone Developer",
      "provisioningProfile": "{your development profile}",
      "developmentTeam": "{your Team ID}",
      "packageType": "development"
    },
    "release": {
      "codeSignIdentity": "iPhone Distribution",
      "provisioningProfile": "{your distribution profile}",
      "developmentTeam": "{your Team ID}",
      "packageType": "app-store"
    }
  }
}
</code>```

Then, when you build using the Cordova CLI, these signing credentials will be used.

Note: according to the Cordova documentation the above syntax is deprecated for Xcode 8 and iOS 10, and the provisioning profile GUID is no longer needed. However, I've been unable to get it working without specifying the provisioning profile using Cordova v7.0.1.

Body:
I am trying to automate the build/deployment of my hybdrid mobile application in Jenkins using fastlane.
I use ionic (v3.3.0) and cordova (v7.0.1) for the source. I use fastlane v2.36.0 and Xcode is version 8.3.2.

The command I run in the jenkins job

yarn
ionic cordova prepare
fastlane ios build

The fastlane/FastFile

platform :ios do
  before_all do
  end

  ios_project_path = "platforms/ios/awesomeproject.xcodeproj"

  desc "Build for IOS"
  lane :build do
    increment_build_number(
      xcodeproj: ios_project_path,
      build_number: ENV["BUILD_NUMBER"]
    )

    # Recreate schemes to ensure a smooth transition from cordova to gym
    recreate_schemes(project: ios_project_path)

    update_project_team(
      path: ios_project_path,
      teamid: "TEAMID"
    )

    #update_provisioning_profile_specifier(xcodeproj: ios_project_path)

      gym(scheme: "awesomeproject",
          configuration: "Debug",
          clean: true,
          project: ios_project_path,
          output_directory: "target")
  end
end

The fastlane/Appfile

package_name "com.xxx.awesomeapp"

app_identifier "com.xxx.awesomeapp" # The bundle identifier of your app
apple_id "xxx.xxxx@xxx.com" # Your Apple email address

team_id "TEAMID" # Developer Portal Team ID

The command fastlane ios build is failing on the gym instruction with the error

Code signing is required for product type 'Application' in SDK 'iOS
  10.3'

The detailed error in the fastlane log is

Check dependencies Signing for "awesomeproject" requires a development
  team. Select a development team in the project editor. Code signing is
  required for product type 'Application' in SDK 'iOS
  10.3'

The xcode project generated by Cordova has the Automatic signing activated but it is missing the Signing Team.
The workaround I used so far is to manually select the Team with Xcode the first time the platform/ios folder is generated. But if I remove the platform folder generated by cordova, I need to redo the selection of the team in XCode.

Is there a way to select with Cordova or any fastlane plugin the Signing team? I am open to use any solution, script.
So my build will be fully automated. The update_project_team instruction is not working.

Body:
Create a file called build.json in the root directory of your project, with the Team ID and provisioning profile GUID you want to use to sign the app:

build.json:

{
  "ios": {
    "debug": {
      "codeSignIdentity": "iPhone Developer",
      "provisioningProfile": "{your development profile}",
      "developmentTeam": "{your Team ID}",
      "packageType": "development"
    },
    "release": {
      "codeSignIdentity": "iPhone Distribution",
      "provisioningProfile": "{your distribution profile}",
      "developmentTeam": "{your Team ID}",
      "packageType": "app-store"
    }
  }
}

Then, when you build using the Cordova CLI, these signing credentials will be used.

Note: according to the Cordova documentation the above syntax is deprecated for Xcode 8 and iOS 10, and the provisioning profile GUID is no longer needed. However, I've been unable to get it working without specifying the provisioning profile using Cordova v7.0.1.


来源: stackexchange

问:
Compiler optimization: g++ slower than intel
I recently acquired a computer with dual-boot to code in C++. On windows I use intel C++ compiler and g++ on linux.
My programs consist mostly of computation (fixed point iteration algorithm with numerical integration, etc.).

I thought I could get performances close to windows on my linux, but so far I don't: for the exact same code, the program compiled with g++ is about 2 times slower than the one with intel compiler. From what I read, icc can be faster, maybe even up to 20-30% gains, but I did not read anything about it being twice as fast (and in general I actually read that both should be equivalent).

At first I was using flags which are approximately equivalent:

icl /openmp /I "C:\boost_1_61_0" /fast program.cpp

and

g++ -o program program.cpp -std=c++11 -fopenmp -O3 -ffast-math

Following advices from several other topics I tried adding/replacing several other flags like: -funsafe-math-optimizations, -march=native, -fwhole-program, -Ofast etc. with only slight (or no) performances gain.

Is icc really faster or am I missing something?
I'm fairly new to linux so I don't know, maybe I forgot to install something properly (like a driver), or to change some option in g++ ? I have no idea whether the situation is normal or not, that's why I prefer to ask. Especially since I prefer to use linux to code ideally, so I would rather have it be up to speed.

EDIT: I decided to install the last intel compiler (Intel Compiler C++ 17, update4) on linux to check. I end up with mitigated results: it does NOT do better than gcc (even worse in fact).
I ran cross comparison linux/windows - icc/gcc - parallelized or not, using the flags mentioned earlier in the post (to make direct comparisons), here are my results (time to run 1 iteration measured in ms):

Plain loop, no parallelization:

Windows:

gcc = 122074    ; icc = 68799

Linux:

gcc = _91042    ; icc = 92102

Parallelized version:

Windows:

gcc = 27457    ; icc = 19800

Linux:

gcc =  27000    ; icc = 30000

To sum up: it's a bit of a mess.
On linux, gcc seems to always be faster than icc, especially when parallelization is involved (I ran it for longer program, the difference is much higher than the one here).

On windows, it's the opposite and icc clearly dominates gcc, especially when there is no parallelization (in which case gcc takes a really long time to compile).

The fastest compilation is done with parallelization and icc on windows. I don't understand why I cannot replicate this on linux. Is there anything I need to do (ubuntu 16.04) to help fasten my processes?

The other difference is that on windows I use an older intel composer (Composer XE 2013) and call 'ia32' instead of intel64 (which is the one I should be using) while on linux I use the last version that I installed yesterday.  And on linux, the Intel Compiler 17 folder is on my second hdd (and not my ssd on which linux is install) I don't know if this might slow things down too.

Any idea where the problem may come from?

Edit: Exact hardware:
 Intel(R) Core(TM) i7-4710HQ CPU @ 2.50GHz, 8 CPU, 4 cores, 2 threads per core, architecture x86_64
- Linux Ubuntu 16.04 with gcc 5.4.1 and Intel Compiler 17 (update4)
- Windows 8.1, Intel Composer 2013

Edit: Code is very long, here is the form of the loop that I'm testing (i.e. just one iteration of my fixed point iteration). It's very classic I guess... not sure it can bring anything to the topic.

```<code>// initialization of all the objects...
// length_grid1 is about 2000
vector< double > V_NEXT(length_grid1), PRICE_NEXT(length_grid1);
double V_min, price_min;
#pragma omp parallel
{
#pragma omp for private(V_min, price_min, i, indexcurrent, alpha, beta)
    for (i = 0; i < length_grid1; i++) {
         indexcurrent = indexsum[i];
         V_min = V_compute(&price_min, indexcurrent, ...);
         V_NEXT[indexcurrent] = V_min; PRICE_NEXT[indexcurrent] = price_min;
     }
 }// end parallel
</code>```

where V_compute function is a classic and simple optimization algorithm (customized golden search) returning the optimal value and its argument:

```<code>double V_compute(double *xmin, int row_index, ... ) {
double x1, x2, f1, f2, fxmin;
// golden_ratio=0.61803399;
x1 = upper_bound - golden_ratio*(upper_bound - lower_bound);
x2 = lower_bound + golden_ratio*(upper_bound - lower_bound);

// Evaluate the function at the test points
f1 = intra_value(x1, row_index, ...);
f2 = intra_value(x2, row_index, ...);

while (fabs(upper_bound - lower_bound) > tolerance) {
    if (f2 > f1){
        upper_bound = x2; x2 = x1; f2 = f1;
        x1 = upper_bound - golden_ratio*(upper_bound - lower_bound);
        f1 = intra_value(x1, row_index, ...);
    } else {
        lower_bound = x1; x1 = x2; f1 = f2;
        x2 = lower_bound + golden_ratio*(upper_bound - lower_bound);
        f2 = intra_value(x2, row_index, ...);
    }
}
// Estimated minimizer = (lower bound + upper bound) / 2
*xmin = (lower_bound + upper_bound)/2;
fxmin = intra_value(*xmin, row_index, ...);
return - fxmin; }
</code>```

The function optimized (intra_value) is quite complicated in terms of computation (pick a grid point (row_index) from precompiled grid, then involve a lot of numerical integration, etc.).

答:
Note that "fast-math" breaks some language rules to get fast code and may produce incorrect results in some cases.

Also note that -O3 is not guaranteed to be faster than -O2 or any of the other optimization levels (it depends on your code) - you should test multiple versions.

You may also want to enable -Wl,-O1 - the linker also can do some optimizations.

You may also want to try building with LTO (link time optimization) - it can often yield significant improvements.

I realize this does not answer your question as such. But it should give you some things to play with :-)

Also, gcc is improving pretty fast. You may want to try a newer version if you are not already on 7.1.  Also; try Clang for a third datapoint. Additionally, you can use icc on Linux if you want to.

ContentLicense: CC BY-SA 3.0

Body:
I recently acquired a computer with dual-boot to code in C++. On windows I use intel C++ compiler and g++ on linux.
My programs consist mostly of computation (fixed point iteration algorithm with numerical integration, etc.).

I thought I could get performances close to windows on my linux, but so far I don't: for the exact same code, the program compiled with g++ is about 2 times slower than the one with intel compiler. From what I read, icc can be faster, maybe even up to 20-30% gains, but I did not read anything about it being twice as fast (and in general I actually read that both should be equivalent).

At first I was using flags which are approximately equivalent:

icl /openmp /I "C:\boost_1_61_0" /fast program.cpp

and

g++ -o program program.cpp -std=c++11 -fopenmp -O3 -ffast-math

Following advices from several other topics I tried adding/replacing several other flags like: -funsafe-math-optimizations, -march=native, -fwhole-program, -Ofast etc. with only slight (or no) performances gain.

Is icc really faster or am I missing something?
I'm fairly new to linux so I don't know, maybe I forgot to install something properly (like a driver), or to change some option in g++ ? I have no idea whether the situation is normal or not, that's why I prefer to ask. Especially since I prefer to use linux to code ideally, so I would rather have it be up to speed.

EDIT: I decided to install the last intel compiler (Intel Compiler C++ 17, update4) on linux to check. I end up with mitigated results: it does NOT do better than gcc (even worse in fact).
I ran cross comparison linux/windows - icc/gcc - parallelized or not, using the flags mentioned earlier in the post (to make direct comparisons), here are my results (time to run 1 iteration measured in ms):

Plain loop, no parallelization:

Windows:

gcc = 122074    ; icc = 68799

Linux:

gcc = _91042    ; icc = 92102

Parallelized version:

Windows:

gcc = 27457    ; icc = 19800

Linux:

gcc =  27000    ; icc = 30000

To sum up: it's a bit of a mess.
On linux, gcc seems to always be faster than icc, especially when parallelization is involved (I ran it for longer program, the difference is much higher than the one here).

On windows, it's the opposite and icc clearly dominates gcc, especially when there is no parallelization (in which case gcc takes a really long time to compile).

The fastest compilation is done with parallelization and icc on windows. I don't understand why I cannot replicate this on linux. Is there anything I need to do (ubuntu 16.04) to help fasten my processes?

The other difference is that on windows I use an older intel composer (Composer XE 2013) and call 'ia32' instead of intel64 (which is the one I should be using) while on linux I use the last version that I installed yesterday.  And on linux, the Intel Compiler 17 folder is on my second hdd (and not my ssd on which linux is install) I don't know if this might slow things down too.

Any idea where the problem may come from?

Edit: Exact hardware:
 Intel(R) Core(TM) i7-4710HQ CPU @ 2.50GHz, 8 CPU, 4 cores, 2 threads per core, architecture x86_64
- Linux Ubuntu 16.04 with gcc 5.4.1 and Intel Compiler 17 (update4)
- Windows 8.1, Intel Composer 2013

Edit: Code is very long, here is the form of the loop that I'm testing (i.e. just one iteration of my fixed point iteration). It's very classic I guess... not sure it can bring anything to the topic.

// initialization of all the objects...
// length_grid1 is about 2000
vector< double > V_NEXT(length_grid1), PRICE_NEXT(length_grid1);
double V_min, price_min;
#pragma omp parallel
{
#pragma omp for private(V_min, price_min, i, indexcurrent, alpha, beta)
    for (i = 0; i < length_grid1; i++) {
         indexcurrent = indexsum[i];
         V_min = V_compute(&price_min, indexcurrent, ...);
         V_NEXT[indexcurrent] = V_min; PRICE_NEXT[indexcurrent] = price_min;
     }
 }// end parallel

where V_compute function is a classic and simple optimization algorithm (customized golden search) returning the optimal value and its argument:

double V_compute(double *xmin, int row_index, ... ) {
double x1, x2, f1, f2, fxmin;
// golden_ratio=0.61803399;
x1 = upper_bound - golden_ratio*(upper_bound - lower_bound);
x2 = lower_bound + golden_ratio*(upper_bound - lower_bound);

// Evaluate the function at the test points
f1 = intra_value(x1, row_index, ...);
f2 = intra_value(x2, row_index, ...);

while (fabs(upper_bound - lower_bound) > tolerance) {
    if (f2 > f1){
        upper_bound = x2; x2 = x1; f2 = f1;
        x1 = upper_bound - golden_ratio*(upper_bound - lower_bound);
        f1 = intra_value(x1, row_index, ...);
    } else {
        lower_bound = x1; x1 = x2; f1 = f2;
        x2 = lower_bound + golden_ratio*(upper_bound - lower_bound);
        f2 = intra_value(x2, row_index, ...);
    }
}
// Estimated minimizer = (lower bound + upper bound) / 2
*xmin = (lower_bound + upper_bound)/2;
fxmin = intra_value(*xmin, row_index, ...);
return - fxmin; }

The function optimized (intra_value) is quite complicated in terms of computation (pick a grid point (row_index) from precompiled grid, then involve a lot of numerical integration, etc.).


问:
Get Location Permissions from User in Android Application
I´m trying to get the users actual location with the typicaly permissions box:
like this:

If anyone knows how to make it , pleas answer.

答:
First, you need to write a class where you will define a method for granting and checking user location permission.

```<code>public class CheckPermission {

    //  CHECK FOR LOCATION PERMISSION
    public static boolean checkPermission(Activity activity){
        int result = ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION);
        if (result == PackageManager.PERMISSION_GRANTED){

            return true;

        } else {

            return false;

        }
    }

    //REQUEST FOR PERMISSSION
    public static void requestPermission(Activity activity, final int code){

        if (ActivityCompat.shouldShowRequestPermissionRationale(activity,Manifest.permission.ACCESS_FINE_LOCATION)){

            Toast.makeText(activity,"GPS permission allows us to access location data. Please allow in App Settings for additional functionality.",Toast.LENGTH_LONG).show();

        } else {

            ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},code);
        }
    }

}
</code>```

Now you can call above two static methods to checking or granting permissions in your activity.

```<code>public class LocationActivity extends AppCompatActivity {

    private GPSTracker mytracker;
    private Location myLocation;
    private double latitude=0.0d,longitude=0.0d;
    public final static int TAG_PERMISSION_CODE=1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_screen);

        if(!CheckPermission.checkPermission(LocationActivity.this)) {
          CheckPermission.requestPermission(SplashScreenActivity.this,TAG_PERMISSION_CODE);

        }
    }
}
</code>```

Body:
First, you need to write a class where you will define a method for granting and checking user location permission.

public class CheckPermission {

    //  CHECK FOR LOCATION PERMISSION
    public static boolean checkPermission(Activity activity){
        int result = ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION);
        if (result == PackageManager.PERMISSION_GRANTED){

            return true;

        } else {

            return false;

        }
    }

    //REQUEST FOR PERMISSSION
    public static void requestPermission(Activity activity, final int code){

        if (ActivityCompat.shouldShowRequestPermissionRationale(activity,Manifest.permission.ACCESS_FINE_LOCATION)){

            Toast.makeText(activity,"GPS permission allows us to access location data. Please allow in App Settings for additional functionality.",Toast.LENGTH_LONG).show();

        } else {

            ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},code);
        }
    }

}

Now you can call above two static methods to checking or granting permissions in your activity.

public class LocationActivity extends AppCompatActivity {

    private GPSTracker mytracker;
    private Location myLocation;
    private double latitude=0.0d,longitude=0.0d;
    public final static int TAG_PERMISSION_CODE=1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_screen);

        if(!CheckPermission.checkPermission(LocationActivity.this)) {
          CheckPermission.requestPermission(SplashScreenActivity.this,TAG_PERMISSION_CODE);

        }
    }
}


问:
Model hook loading with refreshModel
My Route currently looks like:

```<code>export default Ember.Route.extend({
    queryParams: {
        dateFrom: { refreshModel: true },
        dateTo: { refreshModel: true }
    },

    model(params) {
        return this.store.findRecord('foo', params.id, {
            adapterOptions: {
                filter: {
                    dateFrom: params.dateFrom,
                    dateTo: params.dateTo,
                }
            }
        });
    },
});
</code>```

When the query param is changed on the route, the model hook is fired again. Is there a way I can tell if the model hook is in a loading state? I have tried model.isLoading in my template, but this doesn't seem to update when refreshModel is triggered.

I don't want to use loading substates, as I need a property I can pass into components.

答:
I am not sure about this approach, but still, you can try it inside the route,</p>

```<code>actions: {
        loading(transition, originRoute) {
            //if you want to set controller property, this.controller.set('isLoading',true); will do
            this.set('isLoading',true);
            transition.promise.finally(() => {
               this.set('isLoading',false);
            });
            return true;
        }
    }
</code>```

Title: Model hook loading with refreshModel

Body:
My Route currently looks like:

export default Ember.Route.extend({
    queryParams: {
        dateFrom: { refreshModel: true },
        dateTo: { refreshModel: true }
    },

    model(params) {
        return this.store.findRecord('foo', params.id, {
            adapterOptions: {
                filter: {
                    dateFrom: params.dateFrom,
                    dateTo: params.dateTo,
                }
            }
        });
    },
});

When the query param is changed on the route, the model hook is fired again. Is there a way I can tell if the model hook is in a loading state? I have tried model.isLoading in my template, but this doesn't seem to update when refreshModel is triggered.

I don't want to use loading substates, as I need a property I can pass into components.

Body:
I am not sure about this approach, but still, you can try it inside the route,

actions: {
        loading(transition, originRoute) {
            //if you want to set controller property, this.controller.set('isLoading',true); will do
            this.set('isLoading',true);
            transition.promise.finally(() => {
               this.set('isLoading',false);
            });
            return true;
        }
    }


问:
Android phone code
I am struggling to get the attached layout on the screen, especially the dashes where they will act like a single digit text field and since it is a code the next number have to jump to the next , textfield, if that is what I have to use.
This is when the user recieves a code (4 digits) he have to enter it, but one number per field.

I think the picture is self explanatory. Thankyou.

答: You can use this Library easy to implement & customize as per your need.</p>

Title: Android phone code


问:
C# KeyPressEventArgs Multiple Keypress
Using KeyPressEventArgs I want to be able to detect multiple keypresses. I have tried it like this without luck.

```<code>[GLib.ConnectBefore]
public override void OnKeyPress (object o, global::Gtk.KeyPressEventArgs args)
{
  if ((args.Event.Key == Gdk.Key.Up) && (args.Event.Key == Gdk.Key.Right))
  {
      playerPhysics.AddVector (_taxiGoUp);
      Player._state = Taxi.State.MoveUp;
      playerPhysics.AddVector (_taxiGoRight);
      Player._state = Taxi.State.MoveRight;
  }
}
</code>```

Can anyone help figuring this out?

答:
You should handle key down and up events in your case. Here is code for basic idea how you could do it:

```<code>bool keyRight = false;
bool keyUp = false;

[GLib.ConnectBefore]
public override void OnKeyDown (object o, global::Gtk.KeyDownEventArgs args)
{
    switch (args.Event.Key)
    {
       case Gdk.Key.Up:
         if(!keyUp)
         {
            keyUp = true;
            playerPhysics.AddVector (_taxiGoUp);
            Player._state = Taxi.State.MoveUp;
         }
         break;
       case Gdk.Key.Right:
         if(!keyRight)
         {
            keyRight = true;
            playerPhysics.AddVector (_taxiGoRight);
            Player._state = Taxi.State.MoveRight;
         }
         break;
    }
}

[GLib.ConnectBefore]
public override void OnKeyDown (object o, global::Gtk.KeyUpEventArgs args)
{
    switch (args.Event.Key)
    {
       case Gdk.Key.Up:
         keyUp = false;
         break;
       case Gdk.Key.Right:
         keyRight = false;
         break;
    }
}
</code>```

Title: C# KeyPressEventArgs Multiple Keypress

Body:
Using KeyPressEventArgs I want to be able to detect multiple keypresses. I have tried it like this without luck.

[GLib.ConnectBefore]
public override void OnKeyPress (object o, global::Gtk.KeyPressEventArgs args)
{
  if ((args.Event.Key == Gdk.Key.Up) && (args.Event.Key == Gdk.Key.Right))
  {
      playerPhysics.AddVector (_taxiGoUp);
      Player._state = Taxi.State.MoveUp;
      playerPhysics.AddVector (_taxiGoRight);
      Player._state = Taxi.State.MoveRight;
  }
}

Can anyone help figuring this out?

Body:
You should handle key down and up events in your case. Here is code for basic idea how you could do it:

bool keyRight = false;
bool keyUp = false;

[GLib.ConnectBefore]
public override void OnKeyDown (object o, global::Gtk.KeyDownEventArgs args)
{
    switch (args.Event.Key)
    {
       case Gdk.Key.Up:
         if(!keyUp)
         {
            keyUp = true;
            playerPhysics.AddVector (_taxiGoUp);
            Player._state = Taxi.State.MoveUp;
         }
         break;
       case Gdk.Key.Right:
         if(!keyRight)
         {
            keyRight = true;
            playerPhysics.AddVector (_taxiGoRight);
            Player._state = Taxi.State.MoveRight;
         }
         break;
    }
}

[GLib.ConnectBefore]
public override void OnKeyDown (object o, global::Gtk.KeyUpEventArgs args)
{
    switch (args.Event.Key)
    {
       case Gdk.Key.Up:
         keyUp = false;
         break;
       case Gdk.Key.Right:
         keyRight = false;
         break;
    }
}


问:
R - renaming multiple columns in multiple dataframes, using nested loop
I have 29 data frames, named Student1 to Student 29. Each of these 29 data frames contains variables Name, Nationality and Membership.number, each with the corresponding number at the end. e.g. Student1 contains Name.1, Nationality.1 and Membership.number.1, Student29 contains Name.29 etc.

I'm trying to standardise these by stripping out the numbers at the end of these variable names. I'm very new to R, but I've put together the following code to try and automate this.

```<code>for (j in 1:29) {
 for (i in 1:3) {
    oldnames = c(paste('Name', i, sep="."), paste('Nationality', i, sep="."), paste('Membership.number', i, sep="."))
    newnames = c("Name", "Nationality", "Membership.number")
    names(paste("Student",j,sep=""))[names(paste("Student",j,sep=""))==oldnames[i]]=newnames[i]
  }
}
</code>```

This appears to be close to achieving what I want, and works as it should for a single dataframe if I insert Student1 in place of paste("Student",j,sep=""), but the paste ("Student",j,sep="") code seems to be failing due to "target of assignment expands to non-language object". Is there something simple which I'm doing wrong here?

答:
The problem is that paste() returns a string, so your code is effectively doing things like:

```<code>names("Student1")[names("Student1")==oldnames[i]] = newnames[i]
</code>```

but, of course, the string "Student1" isn't the same as the variable Student1 that contains your data frame, so this doesn't get you very far.  The error message is a little confusing but ultimately means that you're trying to assign to something that can't be assigned to.

The simplest solution is to make use of the functions get() and assign() which take a string naming a variable (like the string "Student1") and allow you to retrieve and assign the variable.  For example, this will rename one of the columns of Student1:

```<code>dfname = "Student1"
df = get(dfname)
names(df)[names(df)=="Name.1"] = "Name"
assign(dfname, df)
</code>```

So, you can write:

```<code>for (j in 1:29) {
    oldnames = c(paste('Name', j, sep="."),
                 paste('Nationality', j, sep="."),
                 paste('Membership.number', j, sep="."))
    newnames = c("Name", "Nationality", "Membership.number")
    dfname = paste("Student", j, sep="")
    df = get(dfname)
    for (i in 1:3) {
        names(df)[names(df) == oldnames[i]] = newnames[i]
    }
    assign(dfname, df)
}
</code>```

Note that I fixed the oldnames definition to use j instead of i and moved the definitions that depended only on j out of the inner loop.  One caveat here is that this only works at "top level" (i.e., entered at the R prompt).  If you put it in a function, then assign() gets trickier because you need to specify where you want the variable assigned (at the top level with the rest of the global variables, within the function, etc.).

This code can still be improved.  It turns out that your definition of oldnames can be rewritten as:

```<code>oldnames = paste(c("Name","Nationality","Membership.number"), j, sep=".")
</code>```

which means that you can actually write:

```<code>newnames = c("Name","Nationality","Membership.number")
oldnames = paste(newnames, j, sep=".")
</code>```

You can go one step further and use the function match.  This function gets the index of each of the elements of its first argument within its second argument and can be used to retrieve the positions of all the oldnames in the names() vector simultaneously.  Then, you don't even need the inner loop:

```<code>for (j in 1:29) {
    newnames = c("Name","Nationality","Membership.number")
    oldnames = paste(newnames, j, sep=".")
    dfname = paste("Student", j, sep="")
    df = get(dfname)
    names(df)[match(oldnames, names(df))] = newnames
    assign(dfname, df)
}
</code>```

This sort of use of match to find and replace values in a vector is a very common R technique.

Finally, if there aren't any other columns in the data frames (so you really just want to remove all suffixes that consist of a period and some digits from the end of all names), then a common trick in R is to use sub() to modify the names using regular expressions:

```<code>for (j in 1:29) {
    newnames = c("Name","Nationality","Membership.number")
    oldnames = paste(newnames, j, sep=".")
    dfname = paste("Student", j, sep="")
    df = get(dfname)
    names(df) = sub("\\.[0-9]+$", "", names(df))
    assign(dfname, df)
}
</code>```

Note that, in R, backslashes in regular expressions need to be doubled up, so the above "\\." will match a period.  I use this sub-based technique all the time when cleaning up datasets that have unwanted prefixes and suffixes on a bunch of column names.

Happy R-ing!

Body:
I have 29 data frames, named Student1 to Student 29. Each of these 29 data frames contains variables Name, Nationality and Membership.number, each with the corresponding number at the end. e.g. Student1 contains Name.1, Nationality.1 and Membership.number.1, Student29 contains Name.29 etc.

I'm trying to standardise these by stripping out the numbers at the end of these variable names. I'm very new to R, but I've put together the following code to try and automate this.

for (j in 1:29) {
 for (i in 1:3) {
    oldnames = c(paste('Name', i, sep="."), paste('Nationality', i, sep="."), paste('Membership.number', i, sep="."))
    newnames = c("Name", "Nationality", "Membership.number")
    names(paste("Student",j,sep=""))[names(paste("Student",j,sep=""))==oldnames[i]]=newnames[i]
  }
}

This appears to be close to achieving what I want, and works as it should for a single dataframe if I insert Student1 in place of paste("Student",j,sep=""), but the paste ("Student",j,sep="") code seems to be failing due to "target of assignment expands to non-language object". Is there something simple which I'm doing wrong here?

Body:
The problem is that paste() returns a string, so your code is effectively doing things like:

names("Student1")[names("Student1")==oldnames[i]] = newnames[i]

but, of course, the string "Student1" isn't the same as the variable Student1 that contains your data frame, so this doesn't get you very far.  The error message is a little confusing but ultimately means that you're trying to assign to something that can't be assigned to.

The simplest solution is to make use of the functions get() and assign() which take a string naming a variable (like the string "Student1") and allow you to retrieve and assign the variable.  For example, this will rename one of the columns of Student1:

dfname = "Student1"
df = get(dfname)
names(df)[names(df)=="Name.1"] = "Name"
assign(dfname, df)

So, you can write:

for (j in 1:29) {
    oldnames = c(paste('Name', j, sep="."),
                 paste('Nationality', j, sep="."),
                 paste('Membership.number', j, sep="."))
    newnames = c("Name", "Nationality", "Membership.number")
    dfname = paste("Student", j, sep="")
    df = get(dfname)
    for (i in 1:3) {
        names(df)[names(df) == oldnames[i]] = newnames[i]
    }
    assign(dfname, df)
}

Note that I fixed the oldnames definition to use j instead of i and moved the definitions that depended only on j out of the inner loop.  One caveat here is that this only works at "top level" (i.e., entered at the R prompt).  If you put it in a function, then assign() gets trickier because you need to specify where you want the variable assigned (at the top level with the rest of the global variables, within the function, etc.).

This code can still be improved.  It turns out that your definition of oldnames can be rewritten as:

oldnames = paste(c("Name","Nationality","Membership.number"), j, sep=".")

which means that you can actually write:

newnames = c("Name","Nationality","Membership.number")
oldnames = paste(newnames, j, sep=".")

You can go one step further and use the function match.  This function gets the index of each of the elements of its first argument within its second argument and can be used to retrieve the positions of all the oldnames in the names() vector simultaneously.  Then, you don't even need the inner loop:

for (j in 1:29) {
    newnames = c("Name","Nationality","Membership.number")
    oldnames = paste(newnames, j, sep=".")
    dfname = paste("Student", j, sep="")
    df = get(dfname)
    names(df)[match(oldnames, names(df))] = newnames
    assign(dfname, df)
}

This sort of use of match to find and replace values in a vector is a very common R technique.

Finally, if there aren't any other columns in the data frames (so you really just want to remove all suffixes that consist of a period and some digits from the end of all names), then a common trick in R is to use sub() to modify the names using regular expressions:

for (j in 1:29) {
    newnames = c("Name","Nationality","Membership.number")
    oldnames = paste(newnames, j, sep=".")
    dfname = paste("Student", j, sep="")
    df = get(dfname)
    names(df) = sub("\\.[0-9]+$", "", names(df))
    assign(dfname, df)
}

Note that, in R, backslashes in regular expressions need to be doubled up, so the above "\\." will match a period.  I use this sub-based technique all the time when cleaning up datasets that have unwanted prefixes and suffixes on a bunch of column names.

Happy R-ing!


问:
Customise googlemap viewport in iphone
m stucked in figuring out how can i set the viewport for my google map markers.

is there any way to do it in objC??

or i have to do it in my map itself??? if yes, then how???

My code for google map just shows the maps along with the markers,but when i click it,it just shows the name of the place in a small box.. :(

how to make it a proper viewport???

here's the viewport image:

答:
1) You can subclass MKAnnotationView. I think it's the best way to solve your problem.

2) You can customize your annotation callout view, e.g:

```<code>- (MKAnnotationView *) mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation {
    static NSString* ItemAnnotationIdentifier = @"itemAnnotationIdentifier";
    MKPinAnnotationView* pinView = (MKPinAnnotationView *)
                                  [theMapView dequeueReusableAnnotationViewWithIdentifier:ItemAnnotationIdentifier];
    if (!pinView)
    {
      // if an existing pin view was not available, create one
      MKPinAnnotationView* customPinView = [[[MKPinAnnotationView alloc]
                                             initWithAnnotation:annotation
                                             reuseIdentifier:ItemAnnotationIdentifier]
                                            autorelease];
      customPinView.canShowCallout = YES;

      UIImage *logo = [ImageProcessor scaleImage:[UIImage imageNamed:@"logo.png"] toSize:CGSizeMake(30, 30)];
      customPinView.leftCalloutAccessoryView = [[[UIImageView alloc] initWithImage:logo] autorelease];

      UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
      rightButton.tag = [((ItemAnnotation *)annotation).itemId intValue];
      [rightButton addTarget:self
                      action:@selector(showDetails:)
            forControlEvents:UIControlEventTouchUpInside];
      customPinView.rightCalloutAccessoryView = rightButton;

      return customPinView;
    }
    else
    {
      pinView.annotation = annotation;
    }
    return pinView;
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Customise googlemap viewport in iphone

Body:
1) You can subclass MKAnnotationView. I think it's the best way to solve your problem.

2) You can customize your annotation callout view, e.g:

- (MKAnnotationView *) mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation {
    static NSString* ItemAnnotationIdentifier = @"itemAnnotationIdentifier";
    MKPinAnnotationView* pinView = (MKPinAnnotationView *)
                                  [theMapView dequeueReusableAnnotationViewWithIdentifier:ItemAnnotationIdentifier];
    if (!pinView)
    {
      // if an existing pin view was not available, create one
      MKPinAnnotationView* customPinView = [[[MKPinAnnotationView alloc]
                                             initWithAnnotation:annotation
                                             reuseIdentifier:ItemAnnotationIdentifier]
                                            autorelease];
      customPinView.canShowCallout = YES;

      UIImage *logo = [ImageProcessor scaleImage:[UIImage imageNamed:@"logo.png"] toSize:CGSizeMake(30, 30)];
      customPinView.leftCalloutAccessoryView = [[[UIImageView alloc] initWithImage:logo] autorelease];

      UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
      rightButton.tag = [((ItemAnnotation *)annotation).itemId intValue];
      [rightButton addTarget:self
                      action:@selector(showDetails:)
            forControlEvents:UIControlEventTouchUpInside];
      customPinView.rightCalloutAccessoryView = rightButton;

      return customPinView;
    }
    else
    {
      pinView.annotation = annotation;
    }
    return pinView;
}


问:
Would final users have to download android app again when app is moved from a Google play account to another?
Suppose you have an android application associated to some account in Google Play. Then, this account's onwer decide to disassociate such app from his/her account.
So, I would have to upload (don't know for sure) this app to Google Play again using a new account owner.

Would end users have to download app again (from this new account)? Or app updates would still work 'automatically'?

Regards,

答:
You can contact the support to move an app from one developer account to another. Like that, the users won't have to download the app again and you even keep all the statistics in the playstore.

https://support.google.com/googleplay/android-developer/answer/6230247


问:
Is it possible to cancel an event using Microsoft Graph?
I'm trying to write a simple api in C# that will be used to, among other things, delete events from a user's calendar using the Graph api.

The problem I've run into is that I can't delete events that need to be canceled, obviously because they need to be canceled. However, I can't figure out how to write a function to actually CANCEL these events. I'm currently using https://developer.microsoft.com/en-us/graph/docs/api-reference/beta/api/event_cancel to try and cancel an event, and I'm getting a success status code... but nothing happens. The event isn't canceled, and it isn't removed from my calendar.

Any suggestions or advice are greatly appreciated. My code for canceling an event is below.

```<code>   public async void CancelAppointment(string eventId)
    {
        try
        {
            var client = GetHttpClient();
            Uri targetEndpoint = new Uri("https://graph.microsoft.com/beta/me/events/" + eventId + "/cancel");
            string postBody = "{" +
                              "\"Comment\": \"Appointment canceled.\"" +
                              "}";
            var body = new StringContent(postBody, System.Text.Encoding.UTF8, "application/json");

            var response = await client.PostAsync(targetEndpoint, body);
            Console.WriteLine(response.StatusCode);

            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("Canceled appointment with Id: " + eventId);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Could not cancel appointment " + eventId + " " + e.Message);
        }
    }
</code>```

答: This appears to have been fixed. Events are now canceling properly with no changes made to my own code.</p>

Body:
I'm trying to write a simple api in C# that will be used to, among other things, delete events from a user's calendar using the Graph api.

The problem I've run into is that I can't delete events that need to be canceled, obviously because they need to be canceled. However, I can't figure out how to write a function to actually CANCEL these events. I'm currently using https://developer.microsoft.com/en-us/graph/docs/api-reference/beta/api/event_cancel to try and cancel an event, and I'm getting a success status code... but nothing happens. The event isn't canceled, and it isn't removed from my calendar.

Any suggestions or advice are greatly appreciated. My code for canceling an event is below.

   public async void CancelAppointment(string eventId)
    {
        try
        {
            var client = GetHttpClient();
            Uri targetEndpoint = new Uri("https://graph.microsoft.com/beta/me/events/" + eventId + "/cancel");
            string postBody = "{" +
                              "\"Comment\": \"Appointment canceled.\"" +
                              "}";
            var body = new StringContent(postBody, System.Text.Encoding.UTF8, "application/json");

            var response = await client.PostAsync(targetEndpoint, body);
            Console.WriteLine(response.StatusCode);

            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("Canceled appointment with Id: " + eventId);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Could not cancel appointment " + eventId + " " + e.Message);
        }
    }


问:
Does a higher variable value use more computing power?
I want to return a max value from a method and I have two ways of achieving this:

I could use a number that won't be reached ever by the calculation, like 10000

I could return Double.MAX_VALUE

My question now is: Is there a difference in terms of speed, RAM usage etc?

答:
No, there is no difference. A double will always use the same number of bits in its representation.

A Java double is an implementation of the IEEE-754 standard.

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.2.3

If you want to represent "no maximum," however, a better way might be to use an OptionalDouble.


问:
How can I define my javascript to display the images I found in my php script
first of all I am new in this and I thank all the people here I learned of.

My problem:
I created a setting where you can upload pictures in the folder "test"in two different ways.
I want to display the picutes in an automatic slideshow which takes the pictures out of the folder. (Imag 1.jpg, 2.jpg, 3.jpg are in the folder TEST.)

my PHP CODE:

```<code><?php
$dir_path = "test/";
$extensions_array = array('jpg','png','jpeg');
$phpArray = array();

$dateien=scandir($dir_path);
$anzahl=count($dateien);

    //echo "Anzahl $anzahl";

if(is_dir($dir_path))
{
$files = scandir($dir_path);

for($i = 0; $i < count($files); $i++)
{
if($files[$i] !='.' && $files[$i] !='..')
    {
        $file = pathinfo($files[$i]);
        $extension = $file['extension'];

        while(in_array($extension, $extensions_array))
        {
        // show image

        echo "<img src='$dir_path$files[$i]' style='width:500px;height:500px;'><br>";
           $phpArray []= array($dir_path, $files[$i]);
           $filename[]= array($files[$i]);
            //echo $i;
            $i++;
        //echo "Anzahl $anzahl";

                if ($i>$anzahl)
                    {break;}
            }
    }
}
}
$dir_path2 = "uplaods/";
$dateien2=scandir($dir_path);
$anzahl2=count($dateien2);

if ($anzahl2>$anzahl)

?>
</code>```

with the php code I get the folder path and the file name and I could display the pictures seperatly, but not in an slideshow:

MY HTML/JAVASCRIPT CODE

```<code><!DOCTYPE html>
<html>
<title>automatic slideshow</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<style>
.mySlides {display:none;}
</style>
<body>

<h2 class="w3-center">Automatic Slideshow</h2>

<div class="w3-content w3-section" style="max-width:500px">
<img class="mySlides" src="1.jpg" style="width:100%" >
<img class="mySlides" src="2.jpg" style="width:100%">
<img class="mySlides" src="3.jpg"style="width:100%">
</div>

<script>

var myIndex = 0;
carousel();

function carousel() {
var i;
 var x = document.getElementsByClassName("mySlides");  / HERE I NEED HELP
for (i = 0; i < x.length; i++) {
   x[i].style.display = "none";
}
myIndex++;
if (myIndex > x.length) {myIndex = 1}
x[myIndex-1].style.display = "block";
setTimeout(carousel, 2000); // Change image every 2 seconds
}

</script>

</body>
</html>
</code>```

the slideshow code works for the images I defined in the div, but I want to have it out of the folder. I was able to get the filename and the folder path from php to javascript but I was not able to tell javascript to display the picutes out of the folder.

is it even possible?

答:
PHP:

```<code><?php
$dir_path = "test/";
//$dir_path2 = "uplaods/";
$extensions_array = array('jpg','png','jpeg');

if(is_dir($dir_path))
{
    $files = array_slice(scandir($dir_path), 2);
    foreach ($files as $file)
    {
        $ext = pathinfo($file);
        $ext = $ext['extension'];

        if(in_array($ext, $extensions_array))
            $images[] = '<img class="mySlides" src="'. $dir_path . $file .'" style="width:500px;height:500px;">';
    }
}
?>
</code>```

HTML (within PHP file):

<!DOCTYPE html>

 <title>automatic slideshow</title>
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

Automatic Slideshow

 <?php echo implode ("
", $images); ?>

```

Body:
first of all I am new in this and I thank all the people here I learned of.

My problem:
I created a setting where you can upload pictures in the folder "test"in two different ways.
I want to display the picutes in an automatic slideshow which takes the pictures out of the folder. (Imag 1.jpg, 2.jpg, 3.jpg are in the folder TEST.)

my PHP CODE:

<?php
$dir_path = "test/";
$extensions_array = array('jpg','png','jpeg');
$phpArray = array();

$dateien=scandir($dir_path);
$anzahl=count($dateien);

    //echo "Anzahl $anzahl";

if(is_dir($dir_path))
{
$files = scandir($dir_path);

for($i = 0; $i < count($files); $i++)
{
if($files[$i] !='.' && $files[$i] !='..')
    {
        $file = pathinfo($files[$i]);
        $extension = $file['extension'];

        while(in_array($extension, $extensions_array))
        {
        // show image

        echo "
";
           $phpArray []= array($dir_path, $files[$i]);
           $filename[]= array($files[$i]);
            //echo $i;
            $i++;
        //echo "Anzahl $anzahl";

                if ($i>$anzahl)
                    {break;}
            }
    }
}
}
$dir_path2 = "uplaods/";
$dateien2=scandir($dir_path);
$anzahl2=count($dateien2);

if ($anzahl2>$anzahl)

?>

with the php code I get the folder path and the file name and I could display the pictures seperatly, but not in an slideshow:

MY HTML/JAVASCRIPT CODE

<!DOCTYPE html>

<title>automatic slideshow</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

Automatic Slideshow

the slideshow code works for the images I defined in the div, but I want to have it out of the folder. I was able to get the filename and the folder path from php to javascript but I was not able to tell javascript to display the picutes out of the folder.

is it even possible?

Body:
PHP:

<?php
$dir_path = "test/";
//$dir_path2 = "uplaods/";
$extensions_array = array('jpg','png','jpeg');

if(is_dir($dir_path))
{
    $files = array_slice(scandir($dir_path), 2);
    foreach ($files as $file)
    {
        $ext = pathinfo($file);
        $ext = $ext['extension'];

        if(in_array($ext, $extensions_array))
            $images[] = '<img class="mySlides" src="'. $dir_path . $file .'" style="width:500px;height:500px;">';
    }
}
?>

HTML (within PHP file):

<!DOCTYPE html>
<html>
<head>
 <title>automatic slideshow</title>
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
 <style>
 .mySlides {display:none;}
 </style>
</head>
<body>

 <h2 class="w3-center">Automatic Slideshow</h2>
 <div class="w3-content w3-section" style="max-width:500px">
 <?php echo implode ("<br />", $images); ?>
 </div>

 <script>
  var myIndex = 0;
  carousel();

  function carousel() {
   var i;
   var x = document.getElementsByClassName("mySlides");  //HERE I NEED HELP
   for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
   }
   myIndex++;
   if (myIndex > x.length) {myIndex = 1}
   x[myIndex-1].style.display = "block";
   setTimeout(carousel, 2000); // Change image every 2 seconds
  }
 </script>
</body>
</html>


问:
Adding values of strings containing a specific string in Javascript
I have an object called guild, that has the following array:

```<code>members: [
{
uuid: "6afc724d566746c796d13b233c9960ea",
rank: "MEMBER",
joined: 1492733608170,
dailyCoins-1-5-2017: 920,
dailyCoins-2-5-2017: 790,
dailyCoins-3-5-2017: 260,
dailyCoins-4-5-2017: 790
},
{
uuid: "fa014557f1ac4325b23940fb872031a4",
rank: "MEMBER",
joined: 1493332956351
},
etc.
</code>```

How can I add together the value of each string that contains the string "dailyCoins" ?

Here is my current attempt:

```<code> var guildMembers = [];
 var memberCoins = 0;
    for (i = 0; i < guild.members.length; i++) {
        for (j = 0; j < Object.keys(guild.members[i]).length; j++)
            console.log(Object.keys(guild.members[i]));
            if (Object.keys(guild.members[i])[j].includes("dailyCoins")) {
                var memberCoins = memberCoins + Object.values(guild.members[i])[j];
            }
        var member = {
            uuid: guild.members[i].uuid,
            rank: guild.members[i].rank,
            joined: guild.members[i].joined,
            coins: memberCoins
        };
        guildMembers.push(member);
    }
</code>```

答:
You could use map to iterate over your collection, Object.keys(obj) to fetch object properties, then filter to filter required object properties and reduce to accumulate result:

var members  = [
  {
    'uuid': "6afc724d566746c796d13b233c9960ea",
    'rank': "MEMBER",
    'joined': 1492733608170,
    'dailyCoins-1-5-2017': 920,
    'dailyCoins-2-5-2017': 790,
    'dailyCoins-3-5-2017': 260,
    'dailyCoins-4-5-2017': 790
  },
  {
    'uuid': "fa014557f1ac4325b23940fb872031a4",
    'rank': "MEMBER",
    'joined': 1493332956351
  }
];

var guildMembers = members.map(function(row) {
    var filter = function(key) { return key.indexOf('dailyCoins') >= 0; };
    var reduce = function(sum, current) { return sum + row[current]; };

    return {
     uuid: row.uuid,
     rank: row.rank,
     joined: row.joined,
     coins: Object.keys(row).filter(filter).reduce(reduce, 0)
    };
});

console.log(guildMembers);```

Body:
I have an object called guild, that has the following array:

members: [
{
uuid: "6afc724d566746c796d13b233c9960ea",
rank: "MEMBER",
joined: 1492733608170,
dailyCoins-1-5-2017: 920,
dailyCoins-2-5-2017: 790,
dailyCoins-3-5-2017: 260,
dailyCoins-4-5-2017: 790
},
{
uuid: "fa014557f1ac4325b23940fb872031a4",
rank: "MEMBER",
joined: 1493332956351
},
etc.

How can I add together the value of each string that contains the string "dailyCoins" ?

Here is my current attempt:

 var guildMembers = [];
 var memberCoins = 0;
    for (i = 0; i < guild.members.length; i++) {
        for (j = 0; j < Object.keys(guild.members[i]).length; j++)
            console.log(Object.keys(guild.members[i]));
            if (Object.keys(guild.members[i])[j].includes("dailyCoins")) {
                var memberCoins = memberCoins + Object.values(guild.members[i])[j];
            }
        var member = {
            uuid: guild.members[i].uuid,
            rank: guild.members[i].rank,
            joined: guild.members[i].joined,
            coins: memberCoins
        };
        guildMembers.push(member);
    }


答:
It looks like you're using OpenMP, and so I suspect the difference is in the OpenMP implementation, not just the quality of the optimized code.

Intel's OpenMP runtime is known to be quite high performance, and GCC's is good but not great.

OpenMP programs have very different performance characteristics, they don't just depend on how well the compiler can optimize loops or inline function calls. The implementation of the OpenMP runtime matters a lot, as well as the OS implementation of threads and synchronization primitives, which are quite different between Windows and GNU/Linux.

Title: Compiler optimization: g++ slower than intel


答:
Ask for permission at runtime to use device current location as below :</p>

```<code>if (ActivityCompat.checkSelfPermission(YourActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(YourActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
      ActivityCompat.requestPermissions(YourActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
      return;
}else{
  // Write you code here if permission already given.
}
</code>```

Title: Get Location Permissions from User in Android Application

Body:
I´m trying to get the users actual location with the typicaly permissions box:
like this:

If anyone knows how to make it , pleas answer.

Body:
Ask for permission at runtime to use device current location as below :

if (ActivityCompat.checkSelfPermission(YourActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(YourActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
      ActivityCompat.requestPermissions(YourActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
      return;
}else{
  // Write you code here if permission already given.
}


问:
What is the most suitable control to use for 3D rendering and animation programming in Windows Forms?
I am researching 3D and 2D rendering animation. I found the PictureBox control
is pretty okay for this purpose, but I feel I have only very beginner level knowledge. I am curious to know if it is possible to make a moderately complex level of rendering applications with the PictureBox control. In short, which is the best control in the Windows application tool box to be selected for my intended purpose?

I am making a Windows Forms application with C#.

答:
I'm not sure what exactly you are doing with the PictureBox control for this purpose. But if you're using Windows Forms, then you may want to consider making your own Control subclass with all of your drawing operations handled using GDI+ calls in the OnPaint method. You could pair this with a Timer object called every so often to determine when to refresh.

This is an approach I have personally used for drawing previews of simulated mechanical objects in 2D, so this might work for your purposes as well.

Unless you can tell us what exactly you are trying to draw or provide some existing code for us to look at, it will be hard to give you a precise answer. But MSDN has some pages covering this topic, which you can take a look at to get started and for further reading:

Custom Control Painting and Rendering

Rendering a Windows Forms Control

User-Drawn Controls

Control.OnPaint Method (PaintEventArgs)

Graphics Class


问:
webpack is not recognized as a internal or external command,operable program or batch file
I am Learning React.js and i am using windows 8 OS.i have navigate to my root folder

```<code>1.Created the package.json file by npm init
2. install webpack by npm install -S webpack.now webpack has been downloaded to my modules folder
3. install webpack globally by typing npm install webpack -g
4. i am also having a webpack.config.js in my root folder which contains the source and ouput directory
5. when i type the webpack command i am getting the below error.
</code>```

webpack is not recognized as a internal or external command,operable program or batch file

答:
I've had same issue and just added the code block into my package.json file;

```<code> "scripts": {
   "build": "webpack -d --progress --colors"
 }
</code>```

and then run command on terminal;

```<code>npm run build
</code>```

Body:
I am Learning React.js and i am using windows 8 OS.i have navigate to my root folder

1.Created the package.json file by npm init
2. install webpack by npm install -S webpack.now webpack has been downloaded to my modules folder
3. install webpack globally by typing npm install webpack -g
4. i am also having a webpack.config.js in my root folder which contains the source and ouput directory
5. when i type the webpack command i am getting the below error.

webpack is not recognized as a internal or external command,operable program or batch file

Body:
I've had same issue and just added the code block into my package.json file;

 "scripts": {
   "build": "webpack -d --progress --colors"
 }

and then run command on terminal;

npm run build


问:
confused with mobile friendly websites or related
I read somewhere that once you log in here (http://skweezer.com/) and put the website url, we can get the way the site will appear on mobile browsers. I tried getting this url (http://sachindra149.wordpress.com/) and was baffled to see he way it looked.

1) Can anyone please let me know why is that so ??

2) Why such a major difference???

3) And also what needs to be done ...

keeping one thing in mind that I dont have the control over the web codes for the page as it is a blog....
Hope I am clear enough !!!!!!!!

答:
It looks like it just dumps pages to text. That isn't a realistic view of what mobile browsers do these days. Unless you are explicitly developing websites for low end and old mobile devices, don't worry about it.

If you are developing websites for such devices, then:

Don't use generic blog hosting which doesn't give you lots of control

Avoid tabular data

Avoid chrome (large navigation, anything that isn't the primary content)

Keep content short and to the point

Test of real mobile devices instead of third party emulators


问:
How can I color text in
 that it contains in a

How to color a text in a
 that it contains in a
 when the user hovers with the mouse.

Suppose  I have this html code:

```<code><div id="riga_ristorante_1" >
<div>
  <p>HI</p>
</div>
<div><p>HOME</p></div>
<div><p>DOG</p></div>
</div>
</code>```

I want color the "hi","HOME","DOG" in black when the user go on the
 element, so I use CSS:

```<code>#riga_ristorante_1:hover > p {
     text-align: center;
     color: black;

}
</code>```

But it doesn't work. Anyone can help me?

答:
You are targeting the paragraph directly after your ID div which in your html you don't have a paragraph tag that is a immediate child of your riga_ristorante_1

for more info on > selector

https://developer.mozilla.org/en/docs/Web/CSS/Child_selectors

With your given html you can do

```<code>#riga_ristorante_1:hover p { ... }
</code>```

or

```<code>#riga_ristorante_1:hover div > p { ... }
</code>```

or

```<code>#riga_ristorante_1 div:hover > p { ... }
</code>```

or even

```<code>#riga_ristorante_1 p:hover { ... }
</code>```

Title: How can I color text in <p> that it contains in a <div>

Body:
How to color a text in a
 that it contains in a
 when the user hovers with the mouse.

Suppose  I have this html code:

HI

HOME

DOG

I want color the "hi","HOME","DOG" in black when the user go on the
 element, so I use CSS:

#riga_ristorante_1:hover > p {
     text-align: center;
     color: black;

}

But it doesn't work. Anyone can help me?

Body:
You are targeting the paragraph directly after your ID div which in your html you don't have a paragraph tag that is a immediate child of your riga_ristorante_1

for more info on > selector

https://developer.mozilla.org/en/docs/Web/CSS/Child_selectors

With your given html you can do

#riga_ristorante_1:hover p { ... }

or

#riga_ristorante_1:hover div > p { ... }

or

#riga_ristorante_1 div:hover > p { ... }

or even

#riga_ristorante_1 p:hover { ... }


问:
Redelivery of JMS message in microserices
I want to know the redelivery of JMS in a microservices.

For example, if I have a microservices system. And I have 2 instances of User service. And have a listener on a destination in user service. It means I have 2 listeners. The listener is like this:

```<code>@JmsListener(destination = "order:new", containerFactory = "orderFactory")
@Transactional
public void create(OrderDTO orderDTO) {
    Order order = new Order(orderDTO);
    orderRepository.save(order);
    jmsTemplate.convertAndSend("order:need_to_pay", order);
}
</code>```

So my question is, how many times a message will be delivered. And if there is some error in this function, and the message will be re-delivered. But I have 2 instances of the service. And on which this message will be delivered?

答:
It's not part of the spec; it depends on the broker configuration how many times it will be delivered; many brokers can be configured to send the message to a dead-letter queue after some number of attempts.

There is no guarantee the redelivery will go to the same instance.

Body:
I want to know the redelivery of JMS in a microservices.

For example, if I have a microservices system. And I have 2 instances of User service. And have a listener on a destination in user service. It means I have 2 listeners. The listener is like this:

@JmsListener(destination = "order:new", containerFactory = "orderFactory")
@Transactional
public void create(OrderDTO orderDTO) {
    Order order = new Order(orderDTO);
    orderRepository.save(order);
    jmsTemplate.convertAndSend("order:need_to_pay", order);
}

So my question is, how many times a message will be delivered. And if there is some error in this function, and the message will be re-delivered. But I have 2 instances of the service. And on which this message will be delivered?


问:
Replicate Nginx proxy_pass on NodeJs + Express
If you do this in Nginx:

```<code>location /apiproxy/ {
    proxy_pass                      https://apidev.site.com/;
}
</code>```

All request to domain.com/apiproxy/* will be passed to apidev.site.com/*, so domain.com/apiproxy/foo/bar/ will be passed to apidev.site.com/foo/bar.

Im trying to replicate the same behavior in NodeJS with express and proxy, according to documentation:

```<code>app.use('/apiproxy/*', proxy('https://apidev.site.com/v1', {
    proxyReqPathResolver: function(req) {
        console.log(require('url').parse(req.url).path);
        return require('url').parse(req.url).path;
    }}));
</code>```

But that loose everithing after /apriproxy/. Any idea?

答:
Dont know if you have tried this, but if you do not add *. then it passes the url.

Example

```<code>app.use('/proxy', proxy('http://google.com', {
  proxyReqPathResolver: function (req) {
    console.log(require('url').parse(req.url).path);
    return require('url').parse(req.url).path;
  }
}));
</code>```

If we call /proxy/abc, then it calls http://google.com/abc

Body:
If you do this in Nginx:

location /apiproxy/ {
    proxy_pass                      https://apidev.site.com/;
}

All request to domain.com/apiproxy/* will be passed to apidev.site.com/*, so domain.com/apiproxy/foo/bar/ will be passed to apidev.site.com/foo/bar.

Im trying to replicate the same behavior in NodeJS with express and proxy, according to documentation:

app.use('/apiproxy/*', proxy('https://apidev.site.com/v1', {
    proxyReqPathResolver: function(req) {
        console.log(require('url').parse(req.url).path);
        return require('url').parse(req.url).path;
    }}));

But that loose everithing after /apriproxy/. Any idea?

Body:
Dont know if you have tried this, but if you do not add *. then it passes the url.

Example

app.use('/proxy', proxy('http://google.com', {
  proxyReqPathResolver: function (req) {
    console.log(require('url').parse(req.url).path);
    return require('url').parse(req.url).path;
  }
}));

If we call /proxy/abc, then it calls http://google.com/abc


问:
multidimensional array initialized with array returned by function
I have a problem with the following example:

```<code>public static void main(String[] args) {

    // this works
    int[] test1DArray = returnArray();

    int[][] test2DArray = new int[][] {

        // this does not work
        new int[]= returnArray(),

        // yet this does
        new int[] {1, 2 ,3}
}

private static int[] returnArray() {

    int[] a = {1, 2, 3};
    return a;
}
</code>```

I am looking for a way to create a two-dimensional array, and have the second dimension be the array that is returned from a method. I do not understand why it does not work, as the error I am getting in Eclipse is

The left-hand side of an assignment must be a variable

From my understanding, I am creating a new int array and assigning the returned value to it. Populating the second dimension array immediately like this

```<code>new int[] {1, 2 ,3}
</code>```

works like a charm, and I am looking to do something similar with the array that's returned to me from returnArray()

Any help is greatly appreciated.

p/

答:
Although @Eran has solved the problem, I feel you should understand why this went wrong.

When you initialize the contents of an array, you are basically returning values to it.

E.g.: new int[]{1, 2, 3} returns 1, 2, and 3 inside test2Darray, whereas int[] n = new int[]{1, 2, 3} is initializing and declaring an array inside test2Darray. The latter is not returning any primitive value inside the array, so it gives an error.

returnValue() is a method which does return a value (an integer array). So the control considers it equivalent to typing new int[]{1, 2, 3}.

Hence new int[]{1, 2, 3} and returnValue() work.

Body:
I have a problem with the following example:

public static void main(String[] args) {

    // this works
    int[] test1DArray = returnArray();

    int[][] test2DArray = new int[][] {

        // this does not work
        new int[]= returnArray(),

        // yet this does
        new int[] {1, 2 ,3}
}

private static int[] returnArray() {

    int[] a = {1, 2, 3};
    return a;
}

I am looking for a way to create a two-dimensional array, and have the second dimension be the array that is returned from a method. I do not understand why it does not work, as the error I am getting in Eclipse is

The left-hand side of an assignment must be a variable

From my understanding, I am creating a new int array and assigning the returned value to it. Populating the second dimension array immediately like this

new int[] {1, 2 ,3}

works like a charm, and I am looking to do something similar with the array that's returned to me from returnArray()

Any help is greatly appreciated.

p/


问:
When i run the monkey runner, i am getting swt error
I have created the below script and saved it as (test.mr) in the lib folder and running from the command prompt C:\Android_Stuff\android-sdk-windows\tools\lib\monkeyrunner test.mr

```<code>@Importing monkeyrunner
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice

@waiting for the device connection
device = MonkeyRunner.waitForConnection()

@Installing my app.
device.installPackage('C:/Android_Stuff/android-sdk-windows/tools/lib/purchase.apk')

@starting my demo page
device.startActivity(component='com.mobilemoneynetwork.purchase/.demo')

@selecting the Menu Button.
device.press('KEYCODE_MENU','DOWN_AND_UP')
</code>```

I am getting

```<code>Unable to access jarfile ..\framework\archquery.jar
SWT folder '' does not exist.
Please set ANDROID_SWT to point to the folder containing swt.jar for your platform.
</code>```

答: Set ANDROID_SWT path in environment variable it should be "your path"\Android\Sdk\tools\lib\x86_64</p>

Body:
I have created the below script and saved it as (test.mr) in the lib folder and running from the command prompt C:\Android_Stuff\android-sdk-windows\tools\lib\monkeyrunner test.mr

@Importing monkeyrunner
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice

@waiting for the device connection
device = MonkeyRunner.waitForConnection()

@Installing my app.
device.installPackage('C:/Android_Stuff/android-sdk-windows/tools/lib/purchase.apk')

@starting my demo page
device.startActivity(component='com.mobilemoneynetwork.purchase/.demo')

@selecting the Menu Button.
device.press('KEYCODE_MENU','DOWN_AND_UP')

I am getting

Unable to access jarfile ..\framework\archquery.jar
SWT folder '' does not exist.
Please set ANDROID_SWT to point to the folder containing swt.jar for your platform.


答:
You are using a child combinator (a greater than sign: >), but the div with the id your selector matches is the grandparent of the paragraphs, not the parent.

Use a descendant combinator (a space: ) instead.


问:
Numpy 2d histogram not summing to 1
I think I'm misunderstanding Numpy's histogram2d range and bin arguments.

Here's a example of it working how I'd expect:

```<code>d, x_r, y_r = np.histogram2d(
    [0, 1, 3],
    [0, 1, 3],
    bins=[3, 3],
    range=[[0, 3], [0, 3]],
    normed=True)

d
array([[ 0.33333333,  0.        ,  0.        ],
       [ 0.        ,  0.33333333,  0.        ],
       [ 0.        ,  0.        ,  0.33333333]])
np.sum(d)
1.0
</code>```

And here's where things start to fall apart for me (increasing bin count):

```<code>d, x_r, y_r = np.histogram2d(
    [0, 1, 3],
    [0, 1, 3],
    bins=[3, 6],
    range=[[0, 3], [0, 3]],
    normed=True)
d
array([[ 0.66666667,  0.,  0.        ,  0.,  0., 0.        ],
       [ 0.        ,  0.,  0.66666667,  0.,  0., 0.        ],
       [ 0.        ,  0.,  0.        ,  0.,  0., 0.66666667]])
np.sum(d)
2.0
</code>```

I would have expected:

```<code>d
array([[ 0.33333333,  0.,  0.        ,  0.,  0., 0.        ],
       [ 0.        ,  0.,  0.33333333,  0.,  0., 0.        ],
       [ 0.        ,  0.,  0.        ,  0.,  0., 0.33333333]])
</code>```

Would appreciate any help on understanding this and getting the result I'm looking for. Thanks.

答:
The normed arg in np.histogram2d normalizes as follows

```<code>bin_count / sample_count / bin_area
</code>```

These take a while to understand, and the source code is not written very well in my opinion (poorly chosen variable names)

bin_count is is the value in the histogram bin

sample_count is the total sum of all bin_counts

bin_area is the area of the particular bin

We can define the above 3 variables in both cases without using the normed arg, and see whats going on:

Case 1

```<code>bin_count, binsx, binsy = np.histogram2d( [0,1,3], [0,1,3],
    bins=[3,3], range=[[0,3],[0,3]], normed=False)
</code>```

If you look at binsx and binsy you will see the area of each bin is 1

```<code>print(binsx, binsy)
#In [54]: print (binsx, binsy)
#(array([ 0.,  1.,  2.,  3.]), array([ 0.,  1.,  2.,  3.]))
</code>```

Therefore we let bin_area=1 and the 2D histogram normalized looks like

```<code>bin_count / bin_count.sum() / bin_area

#array([[ 0.33333333,  0.        ,  0.        ],
       #[ 0.        ,  0.33333333,  0.        ],
       #[ 0.        ,  0.        ,  0.33333333]])
</code>```

Case 2

```<code>bin_count, binsx, binsy = np.histogram2d( [0,1,3], [0,1,3],
    bins=[3,6], range=[[0,3],[0,3]], normed=False)
print(binsx, binsy)
#(array([ 0.,  1.,  2.,  3.]), array([ 0. ,  0.5,  1. ,  1.5,  2. ,  2.5,  3. ]))
</code>```

Now you can see your bin_area has decreased by a factor of 2 (because you increased the number of y-bins by a factor of 2)

Hence , we let bin_area=.5, and the normalized hist looks like

```<code>bin_count / bin_count.sum() / bin_area

#array([[ 0.66666667,  0.        ,  0.        ,  0.        ,  0.        ,
#         0.        ],
#       [ 0.        ,  0.        ,  0.66666667,  0.        ,  0.        ,
#         0.        ],
#       [ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ,
#         0.66666667]])
</code>```

General Case

In general you can have bins of variable sizes, hence bin_area might be a variable. Consider some non-even bins:

```<code>bin_count, binsx, binsy = np.histogram2d( [0,1,3], [0,1,3],
    bins=([0.,1.5,3.],[0, .6, 1.7,3.]),
    range=[[0,3],[0,3]], normed=False)
</code>```

In this case, calculate the area of each bin explicitly:

```<code>bin_area = np.array( [ [(x1 -x0)* (y1-y0)
    for y1,y0 in zip(binsy[1:], binsy[:-1])]
        for x1,x0 in zip(binsx[1:], binsx[:-1]) ] )

print(bin_area)
#array([[ 0.9 ,  1.65,  1.95],
#       [ 0.9 ,  1.65,  1.95]])

bin_count / bin_count.sum() / bin_area
#array([[ 0.37037037,  0.2020202 ,  0.        ],
#       [ 0.        ,  0.        ,  0.17094017]])
</code>```

Indeed, if we set the normed arg to True

```<code>normed_bin_count, binsx, binsy = np.histogram2d( [0,1,3], [0,1,3],
    bins=([0.,1.5,3.],[0, .6, 1.7,3.]),
    range=[[0,3],[0,3]], normed=True)
print(normed_bin_count)
#array([[ 0.37037037,  0.2020202 ,  0.        ],
#       [ 0.        ,  0.        ,  0.17094017]])
</code>```

Title: Numpy 2d histogram not summing to 1

Body:
I think I'm misunderstanding Numpy's histogram2d range and bin arguments.

Here's a example of it working how I'd expect:

d, x_r, y_r = np.histogram2d(
    [0, 1, 3],
    [0, 1, 3],
    bins=[3, 3],
    range=[[0, 3], [0, 3]],
    normed=True)

d
array([[ 0.33333333,  0.        ,  0.        ],
       [ 0.        ,  0.33333333,  0.        ],
       [ 0.        ,  0.        ,  0.33333333]])
np.sum(d)
1.0

And here's where things start to fall apart for me (increasing bin count):

d, x_r, y_r = np.histogram2d(
    [0, 1, 3],
    [0, 1, 3],
    bins=[3, 6],
    range=[[0, 3], [0, 3]],
    normed=True)
d
array([[ 0.66666667,  0.,  0.        ,  0.,  0., 0.        ],
       [ 0.        ,  0.,  0.66666667,  0.,  0., 0.        ],
       [ 0.        ,  0.,  0.        ,  0.,  0., 0.66666667]])
np.sum(d)
2.0

I would have expected:

d
array([[ 0.33333333,  0.,  0.        ,  0.,  0., 0.        ],
       [ 0.        ,  0.,  0.33333333,  0.,  0., 0.        ],
       [ 0.        ,  0.,  0.        ,  0.,  0., 0.33333333]])

Would appreciate any help on understanding this and getting the result I'm looking for. Thanks.

Body:
The normed arg in np.histogram2d normalizes as follows

bin_count / sample_count / bin_area

These take a while to understand, and the source code is not written very well in my opinion (poorly chosen variable names)

bin_count is is the value in the histogram bin

sample_count is the total sum of all bin_counts

bin_area is the area of the particular bin

We can define the above 3 variables in both cases without using the normed arg, and see whats going on:

Case 1

bin_count, binsx, binsy = np.histogram2d( [0,1,3], [0,1,3],
    bins=[3,3], range=[[0,3],[0,3]], normed=False)

If you look at binsx and binsy you will see the area of each bin is 1

print(binsx, binsy)
#In [54]: print (binsx, binsy)
#(array([ 0.,  1.,  2.,  3.]), array([ 0.,  1.,  2.,  3.]))

Therefore we let bin_area=1 and the 2D histogram normalized looks like

bin_count / bin_count.sum() / bin_area

#array([[ 0.33333333,  0.        ,  0.        ],
       #[ 0.        ,  0.33333333,  0.        ],
       #[ 0.        ,  0.        ,  0.33333333]])

Case 2

bin_count, binsx, binsy = np.histogram2d( [0,1,3], [0,1,3],
    bins=[3,6], range=[[0,3],[0,3]], normed=False)
print(binsx, binsy)
#(array([ 0.,  1.,  2.,  3.]), array([ 0. ,  0.5,  1. ,  1.5,  2. ,  2.5,  3. ]))

Now you can see your bin_area has decreased by a factor of 2 (because you increased the number of y-bins by a factor of 2)

Hence , we let bin_area=.5, and the normalized hist looks like

bin_count / bin_count.sum() / bin_area

#array([[ 0.66666667,  0.        ,  0.        ,  0.        ,  0.        ,
#         0.        ],
#       [ 0.        ,  0.        ,  0.66666667,  0.        ,  0.        ,
#         0.        ],
#       [ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ,
#         0.66666667]])

General Case

In general you can have bins of variable sizes, hence bin_area might be a variable. Consider some non-even bins:

bin_count, binsx, binsy = np.histogram2d( [0,1,3], [0,1,3],
    bins=([0.,1.5,3.],[0, .6, 1.7,3.]),
    range=[[0,3],[0,3]], normed=False)

In this case, calculate the area of each bin explicitly:

bin_area = np.array( [ [(x1 -x0)* (y1-y0)
    for y1,y0 in zip(binsy[1:], binsy[:-1])]
        for x1,x0 in zip(binsx[1:], binsx[:-1]) ] )

print(bin_area)
#array([[ 0.9 ,  1.65,  1.95],
#       [ 0.9 ,  1.65,  1.95]])

bin_count / bin_count.sum() / bin_area
#array([[ 0.37037037,  0.2020202 ,  0.        ],
#       [ 0.        ,  0.        ,  0.17094017]])

Indeed, if we set the normed arg to True

normed_bin_count, binsx, binsy = np.histogram2d( [0,1,3], [0,1,3],
    bins=([0.,1.5,3.],[0, .6, 1.7,3.]),
    range=[[0,3],[0,3]], normed=True)
print(normed_bin_count)
#array([[ 0.37037037,  0.2020202 ,  0.        ],
#       [ 0.        ,  0.        ,  0.17094017]])


问:
to Create a bat file to run a query
I need to create a bat file which include a query to run a package.
I use plsql developer to develop the package. its username,password and database is user,pswd,db1 respectively.
The query to run the package is:

```<code>SELECT
   COLUMN1 AS "LAST NAME",
   COLUMN2 AS "FIRST NAME",
   COLUMN3 AS "LOCATION"
FROM TABLE(PKG.GET_SUM('09-NOV-2010','12-NOV-2010'))
</code>```

can anyone help me what code shud I write to create a bat file

Thanks in advance

This is my code

```<code>connect usr/pswd@db1
SET NEWPAGE 0
SET SPACE 0
SET LINESIZE 80
SET PAGESIZE 100
COLUMN COLUMN1 HEADING 'LAST NAME'
COLUMN COLUMN2 HEADING 'FIRST NAME'
COLUMN COLUMN3 HEADING 'LOCATION'
spool c:\temp\get_sums.csv
SELECT COLUMN1
    ,COLUMN2
    ,COLUMN3
    ,COLUMN4
    ,COLUMN5
    , COLUMN6
    ,COLUMN7,
    COLUMN8
    ,COLUMN9
FROM TABLE(ACTY_SUMM('09-NOV-2010','12-NOV-2010'))
/
spool off
exit;
</code>```

I changed the line size and pagesize. But not able to get the desirable format. I have 12 columns.  I need it in a report format.

Hi I tried to change the Linesize,but still I am not getting the desired format. I want the report in the following format

```<code>FirstNAME LASTNAME LOCATION  A  B  C  D  E  F  G  H  I
NAME1     LNAME1    LOC1     A1 B1 C1 D1 E1 F1 G1 H1 I1
NAME2     LNAME2    LOC1     A2 B2 C2 D2 E2 F2 G2 H2 I2
                    LOCTOT
NAME3     LNAME3    LOC2     A3 B3 C3 D3 E3 F3 G3 H3 I3
                    LOCTOT
</code>```

I need all the column in one row and their corresponding values of each person under each column and after each location there will be location total and at the end there will be grant total. I tried with the linesize,page size and all. still no result. Can anyone help me to get the report in this format

Hi

As of now client is ok with the csv format. But the challenge is I am not getting the heading. This is my code in sql script.

```<code>connect usr/pwd@db1
SET NEWPAGE 0
SET LINESIZE 100
SET PAGESIZE 0
spool c:\temp\q1.csv

COLUMN COLUMN1 HEADING 'LAST NAME'
COLUMN COLUMN2 HEADING 'FIRST NAME'
COLUMN COLUMN3 HEADING 'LOCATION'
COLUMN COLUMN4 HEADING 'A'
COLUMN COLUMN5 HEADING 'B'
COLUMN COLUMN6 HEADING 'C'
COLUMN COLUMN7 HEADING 'D'
COLUMN COLUMN8 HEADING 'E'
COLUMN COLUMN9 HEADING 'F'
COLUMN COLUMN10 HEADING 'G'
COLUMN COLUMN11 HEADING 'H'
COLUMN COLUMN12 HEADING 'I'
SELECT
    '"'||COLUMN1
    ||'","'|| COLUMN2
    ||'","'|| COLUMN3
    ||'","'|| COLUMN4
    ||'","'|| COLUMN5
    ||'","'|| COLUMN6
    ||'","'|| COLUMN7
    ||'","'|| COLUMN8
    ||'","'|| COLUMN9
    ||'","'|| COLUMN10
    ||'","'|| COLUMN11
   ||'","'|| COLUMN12||'"'
FROM
TABLE(ACTY_SUM('09-NOV-2010','12-NOV-2010'))
/

spool off
exit;
</code>```

Can you please suggest on this issue

答:
First create a script to run the query.  You'll want to capture the output to a file, hence the SPOOL command.

```<code>connect usr/pswd@db1
spool c:\temp`get_sums.lst

SELECT

   COLUMN1 AS "LAST NAME",
   COLUMN2 AS "FIRST NAME",
   COLUMN3 AS "LOCATION"

FROM TABLE(PKG.GET_SUM('09-NOV-2010','12-NOV-2010'))
/

spool off
exit;
</code>```

save that to a file called get_sums.sql .  Then you need a batch file get_sums.bat like this:

```<code>sqlplus /nolog @C:\get_sums.sql
</code>```

There are various SQL*Plus commands you can include in the .sql file t format the output.  Find out more.

Apparently a link to the formatting documentation is not sufficient.

There is no point in setting LINESiZE to 80, that is the default.  If you are selecting nine columns and you want all nine values to appear on one line you need to set the LINESIZE so that it is long enough to accomodate all the columns.  This means you need to set LINESIZE to the sum of all the columns' widths plus eight (the number of interstitial spaces between ninbe columns).

Although I see you have tried

```<code>SET SPACE 0
</code>```

This causes all the selected columns to run together in one long line, which is a highly unusual way of laying out a report.  But if that's really what you want then ignore the interstitial spaces when calculating the correct value for LINESIZE.

Having formatted you posted code I see you are outputting to .csv.  Why didn't you say you wanted to export comma separated values in the first place?

There are several ways of doing this.  The most straightforward is to concatenate your query's projection with commas:

```<code>SELECT
    '"'||COLUMN1
    ||'","'|| COLUMN2
    ||'","'|| COLUMN3
    ||'","'|| COLUMN4
    ||'","'|| COLUMN5
    ||'","'|| COLUMN6
    ||'","'|| COLUMN7
    ||'","'|| COLUMN8
    ||'","'|| COLUMN9 ||'"'
FROM TABLE(ACTY_SUMM('09-NOV-2010','12-NOV-2010'))
/
</code>```

The double-quotes are the optional field terminators, which will handle any string columns which contain commas.

"I dont want coma seperated values. I
  edited my post. Please suggest "

Here is some test data:

```<code>SQL> select * from t23
  2  /

♀FIRSTNAME            LASTNAME              LOCATION    A   B   C   D   E   F
--------------------  --------------------  ----------  --  --  --  --  --  --
G   H   I
--  --  --
NAME1                 LNAME1                LOC1        A1  B1  C1  D1  E1  F1
G1  H1  I1

NAME2                 LNAME2                LOC1        A2  B2  C2  D2  E2  F2
G2  H2  I2

NAME3                 LNAME3                LOC2        A3  B3  C3  D3  E3  F3
G3  H3  I3

SQL>
</code>```

I can produce the basic layout you want using SQL*Plus formatting commands

```<code>SQL> set linesize 100
SQL> break on location
SQL> compute count of location on location
SQL> compute count of location on report
SQL> r
  1* select * from t23
♀FIRSTNAME            LASTNAME              LOCATION    A   B   C   D   E   F   G   H   I
--------------------  --------------------  ----------  --  --  --  --  --  --  --  --  --
NAME1                 LNAME1                LOC1        A1  B1  C1  D1  E1  F1  G1  H1  I1
NAME2                 LNAME2                            A2  B2  C2  D2  E2  F2  G2  H2  I2
                                            ----------
                                                     2
NAME3                 LNAME3                LOC2        A3  B3  C3  D3  E3  F3  G3  H3  I3
                                            ----------
                                                     1

SQL>
</code>```

Title: to Create a bat file to run a query

Body:
I need to create a bat file which include a query to run a package.
I use plsql developer to develop the package. its username,password and database is user,pswd,db1 respectively.
The query to run the package is:

SELECT
   COLUMN1 AS "LAST NAME",
   COLUMN2 AS "FIRST NAME",
   COLUMN3 AS "LOCATION"
FROM TABLE(PKG.GET_SUM('09-NOV-2010','12-NOV-2010'))

can anyone help me what code shud I write to create a bat file

Thanks in advance

This is my code

connect usr/pswd@db1
SET NEWPAGE 0
SET SPACE 0
SET LINESIZE 80
SET PAGESIZE 100
COLUMN COLUMN1 HEADING 'LAST NAME'
COLUMN COLUMN2 HEADING 'FIRST NAME'
COLUMN COLUMN3 HEADING 'LOCATION'
spool c:\temp\get_sums.csv
SELECT COLUMN1
    ,COLUMN2
    ,COLUMN3
    ,COLUMN4
    ,COLUMN5
    , COLUMN6
    ,COLUMN7,
    COLUMN8
    ,COLUMN9
FROM TABLE(ACTY_SUMM('09-NOV-2010','12-NOV-2010'))
/
spool off
exit;

I changed the line size and pagesize. But not able to get the desirable format. I have 12 columns.  I need it in a report format.

Hi I tried to change the Linesize,but still I am not getting the desired format. I want the report in the following format

FirstNAME LASTNAME LOCATION  A  B  C  D  E  F  G  H  I
NAME1     LNAME1    LOC1     A1 B1 C1 D1 E1 F1 G1 H1 I1
NAME2     LNAME2    LOC1     A2 B2 C2 D2 E2 F2 G2 H2 I2
                    LOCTOT
NAME3     LNAME3    LOC2     A3 B3 C3 D3 E3 F3 G3 H3 I3
                    LOCTOT

I need all the column in one row and their corresponding values of each person under each column and after each location there will be location total and at the end there will be grant total. I tried with the linesize,page size and all. still no result. Can anyone help me to get the report in this format

Hi

As of now client is ok with the csv format. But the challenge is I am not getting the heading. This is my code in sql script.

connect usr/pwd@db1
SET NEWPAGE 0
SET LINESIZE 100
SET PAGESIZE 0
spool c:\temp\q1.csv

COLUMN COLUMN1 HEADING 'LAST NAME'
COLUMN COLUMN2 HEADING 'FIRST NAME'
COLUMN COLUMN3 HEADING 'LOCATION'
COLUMN COLUMN4 HEADING 'A'
COLUMN COLUMN5 HEADING 'B'
COLUMN COLUMN6 HEADING 'C'
COLUMN COLUMN7 HEADING 'D'
COLUMN COLUMN8 HEADING 'E'
COLUMN COLUMN9 HEADING 'F'
COLUMN COLUMN10 HEADING 'G'
COLUMN COLUMN11 HEADING 'H'
COLUMN COLUMN12 HEADING 'I'
SELECT
    '"'||COLUMN1
    ||'","'|| COLUMN2
    ||'","'|| COLUMN3
    ||'","'|| COLUMN4
    ||'","'|| COLUMN5
    ||'","'|| COLUMN6
    ||'","'|| COLUMN7
    ||'","'|| COLUMN8
    ||'","'|| COLUMN9
    ||'","'|| COLUMN10
    ||'","'|| COLUMN11
   ||'","'|| COLUMN12||'"'
FROM
TABLE(ACTY_SUM('09-NOV-2010','12-NOV-2010'))
/

spool off
exit;

Can you please suggest on this issue

Body:
First create a script to run the query.  You'll want to capture the output to a file, hence the SPOOL command.

connect usr/pswd@db1
spool c:\temp`get_sums.lst

SELECT

   COLUMN1 AS "LAST NAME",
   COLUMN2 AS "FIRST NAME",
   COLUMN3 AS "LOCATION"

FROM TABLE(PKG.GET_SUM('09-NOV-2010','12-NOV-2010'))
/

spool off
exit;

save that to a file called get_sums.sql .  Then you need a batch file get_sums.bat like this:

sqlplus /nolog @C:\get_sums.sql

There are various SQL*Plus commands you can include in the .sql file t format the output.  Find out more.

Apparently a link to the formatting documentation is not sufficient.

There is no point in setting LINESiZE to 80, that is the default.  If you are selecting nine columns and you want all nine values to appear on one line you need to set the LINESIZE so that it is long enough to accomodate all the columns.  This means you need to set LINESIZE to the sum of all the columns' widths plus eight (the number of interstitial spaces between ninbe columns).

Although I see you have tried

SET SPACE 0

This causes all the selected columns to run together in one long line, which is a highly unusual way of laying out a report.  But if that's really what you want then ignore the interstitial spaces when calculating the correct value for LINESIZE.

Having formatted you posted code I see you are outputting to .csv.  Why didn't you say you wanted to export comma separated values in the first place?

There are several ways of doing this.  The most straightforward is to concatenate your query's projection with commas:

SELECT
    '"'||COLUMN1
    ||'","'|| COLUMN2
    ||'","'|| COLUMN3
    ||'","'|| COLUMN4
    ||'","'|| COLUMN5
    ||'","'|| COLUMN6
    ||'","'|| COLUMN7
    ||'","'|| COLUMN8
    ||'","'|| COLUMN9 ||'"'
FROM TABLE(ACTY_SUMM('09-NOV-2010','12-NOV-2010'))
/

The double-quotes are the optional field terminators, which will handle any string columns which contain commas.

"I dont want coma seperated values. I
  edited my post. Please suggest "

Here is some test data:

SQL> select * from t23
  2  /

♀FIRSTNAME            LASTNAME              LOCATION    A   B   C   D   E   F
--------------------  --------------------  ----------  --  --  --  --  --  --
G   H   I
--  --  --
NAME1                 LNAME1                LOC1        A1  B1  C1  D1  E1  F1
G1  H1  I1

NAME2                 LNAME2                LOC1        A2  B2  C2  D2  E2  F2
G2  H2  I2

NAME3                 LNAME3                LOC2        A3  B3  C3  D3  E3  F3
G3  H3  I3

SQL>

I can produce the basic layout you want using SQL*Plus formatting commands

SQL> set linesize 100
SQL> break on location
SQL> compute count of location on location
SQL> compute count of location on report
SQL> r
  1* select * from t23
♀FIRSTNAME            LASTNAME              LOCATION    A   B   C   D   E   F   G   H   I
--------------------  --------------------  ----------  --  --  --  --  --  --  --  --  --
NAME1                 LNAME1                LOC1        A1  B1  C1  D1  E1  F1  G1  H1  I1
NAME2                 LNAME2                            A2  B2  C2  D2  E2  F2  G2  H2  I2
                                            ----------
                                                     2
NAME3                 LNAME3                LOC2        A3  B3  C3  D3  E3  F3  G3  H3  I3
                                            ----------
                                                     1

SQL>


答:
css selector will be riga_ristorante_1:hover > div > p {}

#riga_ristorante_1:hover > div > p {
     text-align: center;
     color: blue;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="riga_ristorante_1" >
<div>
  <p>HI</p>
</div>
<div><p>HOME</p></div>
<div><p>DOG</p></div>
</div></code>```

Body:
css selector will be riga_ristorante_1:hover > div > p {}

#riga_ristorante_1:hover > div > p {
     text-align: center;
     color: blue;

}

<div id="riga_ristorante_1" >
<div>
  <p>HI</p>
</div>
<div><p>HOME</p></div>
<div><p>DOG</p></div>
</div>


问:
Laravel Envoy Permissions?
Ok, so I am trying to call Envoy from a controller function but running into permissions problems that nobody else seems to be getting?

I have installed envoy globally and done a symlink to /usr/local/bin so that my site can see it. But I cannot figure out why it doesn't have permission.

I am running from Ubuntu 16.04, Nginx, PHP 7.0

Any help is appreciated:

```<code>$result = [];
         $live = false;

         $process = new \Symfony\Component\Process\Process('envoy run deploy --domain="test"');
         $process->setTimeout(3600);
         $process->setIdleTimeout(300);
         $process->setWorkingDirectory(base_path());
         $process->run(
             function ($type, $buffer) use ($live, &$result) {
                 $buffer = str_replace('[127.0.0.1]: ', '', $buffer);

                 if ($live) {
                     echo $buffer . '</br />';
                 }

                 $result[] = $buffer;
             }
         );

         dd($result);
</code>```

But getting:

```<code>0 => "sh: 1: "
  1 => "envoy: Permission denied"
  2 => "\n"
</code>```

答: I have found a solution by using: laravelcollective.com/docs/5.0/ssh</p>

Title: Laravel Envoy Permissions?

Body:
Ok, so I am trying to call Envoy from a controller function but running into permissions problems that nobody else seems to be getting?

I have installed envoy globally and done a symlink to /usr/local/bin so that my site can see it. But I cannot figure out why it doesn't have permission.

I am running from Ubuntu 16.04, Nginx, PHP 7.0

Any help is appreciated:

$result = [];
         $live = false;

         $process = new \Symfony\Component\Process\Process('envoy run deploy --domain="test"');
         $process->setTimeout(3600);
         $process->setIdleTimeout(300);
         $process->setWorkingDirectory(base_path());
         $process->run(
             function ($type, $buffer) use ($live, &$result) {
                 $buffer = str_replace('[127.0.0.1]: ', '', $buffer);

                 if ($live) {
                     echo $buffer . '
';
                 }

                 $result[] = $buffer;
             }
         );

         dd($result);

But getting:

0 => "sh: 1: "
  1 => "envoy: Permission denied"
  2 => "\n"


问:
What will be the output if the argument's date type is different?
What happens  if the actual parameter and formal parameter's data types are different in overloading   ?  </p>

```<code>Class A
{
   public void m1(int i)
    {
    System.out.println("int");
     }
     public void m1(float f)
     {
     System.out.println("float");
     }
 Public static void main(String[] args)
 {
  A a=new A();
  a.m1('a');
  a.m1(10l);
  }
  }
</code>```

答: The method with the closest matching valid signature gets called.  This could well be a direct match (e.g. exactly the same function argument types), or (as in your code) the runtime knows how to automatically convert the char a to an int, so the method with the int param is called.

Body:
What happens  if the actual parameter and formal parameter's data types are different in overloading   ?

Class A
{
   public void m1(int i)
    {
    System.out.println("int");
     }
     public void m1(float f)
     {
     System.out.println("float");
     }
 Public static void main(String[] args)
 {
  A a=new A();
  a.m1('a');
  a.m1(10l);
  }
  }


答:
This code should solve it in your way.</p>

```<code>var guildMembers = [];
for (i = 0; i < members.length; i++) {
  let memberCoins = 0;
    for (j = 0; j < Object.keys(members[i]).length; j++)
        if (Object.keys(members[i])[j].includes("dailyCoins")) {
             memberCoins = memberCoins + members[i][Object.keys(members[i])[j]];
        }
    var member = {
        uuid: members[i].uuid,
        rank: members[i].rank,
        joined: members[i].joined,
        coins: memberCoins
    };
    guildMembers.push(member);
}
</code>```

Title: Adding values of strings containing a specific string in Javascript

Body:
I have an object called guild, that has the following array:

members: [
{
uuid: "6afc724d566746c796d13b233c9960ea",
rank: "MEMBER",
joined: 1492733608170,
dailyCoins-1-5-2017: 920,
dailyCoins-2-5-2017: 790,
dailyCoins-3-5-2017: 260,
dailyCoins-4-5-2017: 790
},
{
uuid: "fa014557f1ac4325b23940fb872031a4",
rank: "MEMBER",
joined: 1493332956351
},
etc.

How can I add together the value of each string that contains the string "dailyCoins" ?

Here is my current attempt:

 var guildMembers = [];
 var memberCoins = 0;
    for (i = 0; i < guild.members.length; i++) {
        for (j = 0; j < Object.keys(guild.members[i]).length; j++)
            console.log(Object.keys(guild.members[i]));
            if (Object.keys(guild.members[i])[j].includes("dailyCoins")) {
                var memberCoins = memberCoins + Object.values(guild.members[i])[j];
            }
        var member = {
            uuid: guild.members[i].uuid,
            rank: guild.members[i].rank,
            joined: guild.members[i].joined,
            coins: memberCoins
        };
        guildMembers.push(member);
    }

Body:
This code should solve it in your way.

var guildMembers = [];
for (i = 0; i < members.length; i++) {
  let memberCoins = 0;
    for (j = 0; j < Object.keys(members[i]).length; j++)
        if (Object.keys(members[i])[j].includes("dailyCoins")) {
             memberCoins = memberCoins + members[i][Object.keys(members[i])[j]];
        }
    var member = {
        uuid: members[i].uuid,
        rank: members[i].rank,
        joined: members[i].joined,
        coins: memberCoins
    };
    guildMembers.push(member);
}