问:
MeshLabServer - Simplification : Quadric Edge Collapse Decimation (WITH TEXTURE) Failure
I test some decimation / simplification tools to reduce triangles number of many OBJ files who represent a 3D model programmatically.

I have a problem with the function "Simplification: Quadric Edge Collapse Decimation (with texture) in MeshLab.

When I run the function I get the message :
Filter failure message

I found a workaround with the IDE, I apply the function Filters / Texture / Converts PerVertex UV into PerWedge UV and then apply the simplification filter...
But in the MeshLabXML api i can't find the filter to convert UV texture coordinates...

Anyone have had the problem? And resolved it?

答:
You have two alternatives to do that:

First takes two steps:

Convert your mesh to per-wedge-textured using the command meshlabserver -i inputMesh.obj -o tmpMesh.obj -m wt

Apply your other filters using meshlabserver -i tmpMesh.obj -o outputMesh.obj -m wt -s myScript.mlx

The second alternative is do everything in just a step, by calling the filter Convert PerVertex UV into PerWedge UV in your mlx script before of calling Simplification: Quadric Edge .... Also, I suggest to call Remove Unreferenced Verticesjust by sanity.

Try saving this script to a file named textureSimplify.mlx

```<code><!DOCTYPE FilterScript>
<FilterScript>
 <filter name="Remove Unreferenced Vertices"/>
 <filter name="Convert PerVertex UV into PerWedge UV"/>
 <filter name="Simplification: Quadric Edge Collapse Decimation (with texture)">
  <Param value="3000" name="TargetFaceNum" description="Target number of faces" isxmlparam="0" tooltip="" type="RichInt"/>
  <Param value="0" name="TargetPerc" description="Percentage reduction (0..1)" isxmlparam="0" tooltip="" type="RichFloat"/>
  <Param value="0.3" name="QualityThr" description="Quality threshold" isxmlparam="0" tooltip="" type="RichFloat"/>
  <Param value="1" name="Extratcoordw" description="Texture Weight" isxmlparam="0" tooltip="" type="RichFloat"/>
  <Param value="false" name="PreserveBoundary" description="Preserve Boundary of the mesh" isxmlparam="0" tooltip="" type="RichBool"/>
  <Param value="1" name="BoundaryWeight" description="Boundary Preserving Weight" isxmlparam="0" tooltip="" type="RichFloat"/>
  <Param value="true" name="OptimalPlacement" description="Optimal position of simplified vertices" isxmlparam="0" tooltip="" type="RichBool"/>
  <Param value="true" name="PreserveNormal" description="Preserve Normal" isxmlparam="0" tooltip="" type="RichBool"/>
  <Param value="true" name="PlanarQuadric" description="Planar Simplification" isxmlparam="0" tooltip="" type="RichBool"/>
  <Param value="false" name="Selected" description="Simplify only selected faces" isxmlparam="0" tooltip="" type="RichBool"/>
 </filter>

</FilterScript>

</code>```

Edit the line <Param value="3000" name="TargetFaceNum" to change the value 3000 to your desired number of faces, and then execute the script using the command:

```<code>> meshlabserver -i inputMesh.obj -o outputMesh.obj -m wt -s textureSimplify.mlx
</code>```

Body:
You have two alternatives to do that:

First takes two steps:

Convert your mesh to per-wedge-textured using the command meshlabserver -i inputMesh.obj -o tmpMesh.obj -m wt

Apply your other filters using meshlabserver -i tmpMesh.obj -o outputMesh.obj -m wt -s myScript.mlx

The second alternative is do everything in just a step, by calling the filter Convert PerVertex UV into PerWedge UV in your mlx script before of calling Simplification: Quadric Edge .... Also, I suggest to call Remove Unreferenced Verticesjust by sanity.

Try saving this script to a file named textureSimplify.mlx

<!DOCTYPE FilterScript>
<FilterScript>
 <filter name="Remove Unreferenced Vertices"/>
 <filter name="Convert PerVertex UV into PerWedge UV"/>
 <filter name="Simplification: Quadric Edge Collapse Decimation (with texture)">
  <Param value="3000" name="TargetFaceNum" description="Target number of faces" isxmlparam="0" tooltip="" type="RichInt"/>
  <Param value="0" name="TargetPerc" description="Percentage reduction (0..1)" isxmlparam="0" tooltip="" type="RichFloat"/>
  <Param value="0.3" name="QualityThr" description="Quality threshold" isxmlparam="0" tooltip="" type="RichFloat"/>
  <Param value="1" name="Extratcoordw" description="Texture Weight" isxmlparam="0" tooltip="" type="RichFloat"/>
  <Param value="false" name="PreserveBoundary" description="Preserve Boundary of the mesh" isxmlparam="0" tooltip="" type="RichBool"/>
  <Param value="1" name="BoundaryWeight" description="Boundary Preserving Weight" isxmlparam="0" tooltip="" type="RichFloat"/>
  <Param value="true" name="OptimalPlacement" description="Optimal position of simplified vertices" isxmlparam="0" tooltip="" type="RichBool"/>
  <Param value="true" name="PreserveNormal" description="Preserve Normal" isxmlparam="0" tooltip="" type="RichBool"/>
  <Param value="true" name="PlanarQuadric" description="Planar Simplification" isxmlparam="0" tooltip="" type="RichBool"/>
  <Param value="false" name="Selected" description="Simplify only selected faces" isxmlparam="0" tooltip="" type="RichBool"/>
 </filter>

</FilterScript>

Edit the line <Param value="3000" name="TargetFaceNum" to change the value 3000 to your desired number of faces, and then execute the script using the command:

> meshlabserver -i inputMesh.obj -o outputMesh.obj -m wt -s textureSimplify.mlx


来源: stackexchange

问:
Add escape character in front of specific characters [oracle sql]
What I am looking for is some regexp that will add \\ character in varchar column in front of certain characters (e.g ", \ ... N chars).

example: James"Bond\007 -> James\"Bond\\\007

I can do this with N replace but I am looking for more elegant solution if oracle provides it.

```<code>REPLACE(REPLACE(ColumnX, '\', '\\'), '"', '\"')
</code>```

P.S need for oracle 12.1 & oracle 12.2

答:
You can use back-references:

```<code>select regexp_replace (
         'James"Bond\007',
         '("|\\)', -- add all the characters you want to replace
         '\\\1'
       )
from   dual;

REGEXP_REPLACE('JAMES"BOND\007','("|\\)','\\\1')
James\"Bond\\007
</code>```

Note you need to escape the back-slashes in your regex with an extra backslash!

ContentLicense: CC BY-SA 4.0

Body:
What I am looking for is some regexp that will add \\ character in varchar column in front of certain characters (e.g ", \ ... N chars).

example: James"Bond\007 -> James\"Bond\\\007

I can do this with N replace but I am looking for more elegant solution if oracle provides it.

REPLACE(REPLACE(ColumnX, '\', '\\'), '"', '\"')

P.S need for oracle 12.1 & oracle 12.2

Body:
You can use back-references:

select regexp_replace (
         'James"Bond\007',
         '("|\\)', -- add all the characters you want to replace
         '\\\1'
       )
from   dual;

REGEXP_REPLACE('JAMES"BOND\007','("|\\)','\\\1')
James\"Bond\\007

Note you need to escape the back-slashes in your regex with an extra backslash!


问:
Why implicit property declaration in PHP?
I'm wondering why the PHP language allows implicit property declaration when most languages need to define properties within the class declaration itself (see code below). Is there a practical use for this type of coding style?</p>

```<code>$user1 = new User();
$user1->name = "Kylie";
echo $user1->name;

class User{}
</code>```

答: try to disable warnings suppression and such declaration will not seem so implicit anymore))</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm wondering why the PHP language allows implicit property declaration when most languages need to define properties within the class declaration itself (see code below). Is there a practical use for this type of coding style?

$user1 = new User();
$user1->name = "Kylie";
echo $user1->name;

class User{}


问:
React Native Custome Sign Up
I have been trying to edit the theme of the default UI for amplify's withAuthenticator and got the theme working no problem but now it seems that it has reset my sign up page back to the default one?

for example, see my code here:

```<code>const signUpConfig = {
  header: 'Sign up to our App',
  hideAllDefaults: true,
  signUpFields: [
    {
      label: 'Username',
      key: 'username',
      required: true,
      displayOrder: 1,
      type: 'string'
    },
    {
      label: 'Password',
      key: 'password',
      required: true,
      displayOrder: 2,
      type: 'password'
    },
    {
      label: 'Email',
      key: 'email',
      required: true,
      displayOrder: 4,
      type: 'string'
    }
  ]
};
const usernameAttributes = 'Username';

const MyButton = Object.assign({}, AmplifyTheme.button, { backgroundColor: 'yellow' });
const sectionLink = Object.assign({}, AmplifyTheme.sectionFooterLink, { color: 'black' });
const buttondisable = Object.assign({}, AmplifyTheme.buttonDisabled, { backgroundColor: '#cccccc' });
const MyTheme = Object.assign({}, AmplifyTheme, { button: MyButton }, {sectionFooterLink:sectionLink},{buttonDisabled:buttondisable});

export default withAuthenticator(RealApp,false, [], null, MyTheme, {signUpConfig}
);
</code>```

Any ideas? I have read the documentation and even formatted the export default different ways but either the sign up page gets overwritten or the theme isn't applied etc.

答:
Got it working.

Turns out you have to actually add in the whole config into the export e.g

```<code>export default withAuthenticator(RealApp,false, [], null, MyTheme, {header: 'Sign up to our App',
hideAllDefaults: true,
signUpFields: [
  {
    label: 'Username',
    key: 'username',
    required: true,
    displayOrder: 1,
    type: 'string'
  },
  {
    label: 'Password',
    key: 'password',
    required: true,
    displayOrder: 2,
    type: 'password'
  },
  {
    label: 'Email',
    key: 'email',
    required: true,
    displayOrder: 4,
    type: 'string'
  }
]
}
);
</code>```

Title: React Native Custome Sign Up

Body:
I have been trying to edit the theme of the default UI for amplify's withAuthenticator and got the theme working no problem but now it seems that it has reset my sign up page back to the default one?

for example, see my code here:

const signUpConfig = {
  header: 'Sign up to our App',
  hideAllDefaults: true,
  signUpFields: [
    {
      label: 'Username',
      key: 'username',
      required: true,
      displayOrder: 1,
      type: 'string'
    },
    {
      label: 'Password',
      key: 'password',
      required: true,
      displayOrder: 2,
      type: 'password'
    },
    {
      label: 'Email',
      key: 'email',
      required: true,
      displayOrder: 4,
      type: 'string'
    }
  ]
};
const usernameAttributes = 'Username';

const MyButton = Object.assign({}, AmplifyTheme.button, { backgroundColor: 'yellow' });
const sectionLink = Object.assign({}, AmplifyTheme.sectionFooterLink, { color: 'black' });
const buttondisable = Object.assign({}, AmplifyTheme.buttonDisabled, { backgroundColor: '#cccccc' });
const MyTheme = Object.assign({}, AmplifyTheme, { button: MyButton }, {sectionFooterLink:sectionLink},{buttonDisabled:buttondisable});

export default withAuthenticator(RealApp,false, [], null, MyTheme, {signUpConfig}
);

Any ideas? I have read the documentation and even formatted the export default different ways but either the sign up page gets overwritten or the theme isn't applied etc.

Body:
Got it working.

Turns out you have to actually add in the whole config into the export e.g

export default withAuthenticator(RealApp,false, [], null, MyTheme, {header: 'Sign up to our App',
hideAllDefaults: true,
signUpFields: [
  {
    label: 'Username',
    key: 'username',
    required: true,
    displayOrder: 1,
    type: 'string'
  },
  {
    label: 'Password',
    key: 'password',
    required: true,
    displayOrder: 2,
    type: 'password'
  },
  {
    label: 'Email',
    key: 'email',
    required: true,
    displayOrder: 4,
    type: 'string'
  }
]
}
);


问:
inserting data into database using ajax from a table
I am trying to enter data into database from table columns earned_leave,casual_leave and sick_leave but when I enter value 1,2,3 only 3 gets inserted in all columns of database. How to solve this issue?

controller

```<code>  public function AdminStore(Request $request){

      $admin= new Admin();
      $admin->employee_name=$request->get('name') ;
      $admin->month=$request->get('month');
      $admin->earned_leave=$request->get('earned');
      $admin->casual_leave=$request->get('casual');
      $admin->sick_leave=$request->get('sick');
      $admin->save();
      return response()->json(['status'=>true,'message'=>"successful."]);

  }
</code>```

js file

```<code>$(document).on("keypress",".keypressbutton",function(event) {

    var ids = localStorage.getItem("key");
    console.log("DATA==> ", ids);
    var currentEle = $(this).attr('id');
    var month = currentEle.split("_");
    console.log(month[1]);
    console.log("currentEle :: ", currentEle);
    var value = $(this).html();
    console.log("value==> ", value);

    var keyCode = event.which || event.keyCode;
    if (keyCode == 13) {
        event.preventDefault();
        var name=$('.name').val();
        var earned=$(this).val();
        var casual=$(this).val();
        var sick=$(this).val();
        $.ajax({
            url:"leaveSaved",
            type:'POST',
            dataType:'json',
            data:{name:name,month:month[1],earned:earned,casual:casual,sick:sick},
            success:function(data){
                console.log(data);
                alert('LEAVE ADDED');
                JSON.parse(data);
                if(data['status']==true){

                }
                else if(data['status']==false){
                    alert("Error occured !");
                }
            }
        });
        return false;
    }
});
</code>```

html

```<code>@foreach($month as $months)
  <tr>
     <td class="inner" id="month_{{$months}}"><input type="text" name="month" id="month_{{$months}}" value="{{$months}}-<?php echo date("Y"); ?>" class="form-control form-control-sm keypressbutton month" style="border: none;text-align: center;background-color: transparent;"></td>
     <td class="inner" id="earnedLeave_{{$months}}"><input type="text" class="form-control form-control-sm keypressbutton earned " style="border: none;text-align: center;background-color: transparent" name="earned_leave" id="earnedLeave_{{$months}}" readonly ondblclick="this.readOnly='';" onblur="this.readOnly='true';"></td>
     <td class="inner" id="casualLeave_{{$months}}"><input type="text" class="form-control form-control-sm keypressbutton casual " style="border: none;text-align: center;background-color: transparent" name="casual_leave" id="casualLeave_{{$months}}" readonly ondblclick="this.readOnly='';" onblur="this.readOnly='true';"></td>
     <td class="inner" id="sickLeave_{{$months}}"><input type="text" class="form-control form-control-sm keypressbutton sick"  style="border: none;text-align: center;background-color: transparent" name="sick_leave" id="sickLeave_{{$months}}" readonly ondblclick="this.readOnly='';" onblur="this.readOnly='true';"></td>
  </tr>
@endforeach
</code>```

答:
You're using the same input field to get the value of earned, casual, and sick:

```<code>var earned=$(this).val();
var casual=$(this).val();
var sick=$(this).val();
</code>```

You'll need to change this to use the appropriate selectors, e.g.:

```<code>var earned=$('#earned').val();
var casual=$('#casual').val();
var sick=$('#sick').val();
</code>```

Body:
I am trying to enter data into database from table columns earned_leave,casual_leave and sick_leave but when I enter value 1,2,3 only 3 gets inserted in all columns of database. How to solve this issue?

controller

  public function AdminStore(Request $request){

      $admin= new Admin();
      $admin->employee_name=$request->get('name') ;
      $admin->month=$request->get('month');
      $admin->earned_leave=$request->get('earned');
      $admin->casual_leave=$request->get('casual');
      $admin->sick_leave=$request->get('sick');
      $admin->save();
      return response()->json(['status'=>true,'message'=>"successful."]);

  }

js file

$(document).on("keypress",".keypressbutton",function(event) {

    var ids = localStorage.getItem("key");
    console.log("DATA==> ", ids);
    var currentEle = $(this).attr('id');
    var month = currentEle.split("_");
    console.log(month[1]);
    console.log("currentEle :: ", currentEle);
    var value = $(this).html();
    console.log("value==> ", value);

    var keyCode = event.which || event.keyCode;
    if (keyCode == 13) {
        event.preventDefault();
        var name=$('.name').val();
        var earned=$(this).val();
        var casual=$(this).val();
        var sick=$(this).val();
        $.ajax({
            url:"leaveSaved",
            type:'POST',
            dataType:'json',
            data:{name:name,month:month[1],earned:earned,casual:casual,sick:sick},
            success:function(data){
                console.log(data);
                alert('LEAVE ADDED');
                JSON.parse(data);
                if(data['status']==true){

                }
                else if(data['status']==false){
                    alert("Error occured !");
                }
            }
        });
        return false;
    }
});

html

@foreach($month as $months)

     <input type="text" name="month" id="month_{{$months}}" value="{{$months}}-<?php echo date("Y"); ?>" class="form-control form-control-sm keypressbutton month" style="border: none;text-align: center;background-color: transparent;">
     <input type="text" class="form-control form-control-sm keypressbutton earned " style="border: none;text-align: center;background-color: transparent" name="earned_leave" id="earnedLeave_{{$months}}" readonly ondblclick="this.readOnly='';" onblur="this.readOnly='true';">
     <input type="text" class="form-control form-control-sm keypressbutton casual " style="border: none;text-align: center;background-color: transparent" name="casual_leave" id="casualLeave_{{$months}}" readonly ondblclick="this.readOnly='';" onblur="this.readOnly='true';">
     <input type="text" class="form-control form-control-sm keypressbutton sick"  style="border: none;text-align: center;background-color: transparent" name="sick_leave" id="sickLeave_{{$months}}" readonly ondblclick="this.readOnly='';" onblur="this.readOnly='true';">

@endforeach

Body:
You're using the same input field to get the value of earned, casual, and sick:

var earned=$(this).val();
var casual=$(this).val();
var sick=$(this).val();

You'll need to change this to use the appropriate selectors, e.g.:

var earned=$('#earned').val();
var casual=$('#casual').val();
var sick=$('#sick').val();


问:
Docker image fail running docker-entrypoint.sh, but only when running from Docker Hub?
So here is my Dockerfile, simplified. The original file is https://github.com/gremo/docker-folder-mirror/blob/master/Dockerfile:

```<code>FROM alpine:latest

COPY ./docker-entrypoint.sh /usr/local/bin/

ENTRYPOINT ["docker-entrypoint.sh"]
</code>```

When I run my image locally (assuming the tag is folder-mirror:latest) everything works fine:

```<code>docker run --rm --env-file ./.env -v "${PWD}/data:/data" -v "${PWD}/logs:/var/log" folder-mirror:latest
</code>```

However, if I try to run the image directory (from Docker Hub):

```<code>docker run --rm --env-file ./.env -v "${PWD}/data:/data" -v "${PWD}/logs:/var/log" gremo1982/folder-mirror
</code>```

... it gives me the following error:

C:\Program Files\Docker\Docker\resources\bin\docker.exe: Error
  response from daemon: OCI runtime create failed:
  container_linux.go:346: starting container process caused "exec:
  \"docker-entrypoint.sh\": executable file not found in $PATH":
  unknown.

This is my first Docker image, so I'm pretty sure... I'm missing something. In fact, if I check the remote image i get:

```<code>/ # ls -la /usr/local/bin/
total 12
drwxr-xr-x    1 root     root          4096 Feb 18  2020 .
drwxr-xr-x    1 root     root          4096 Jan 16 22:52 ..
-rw-r--r--    1 root     root           890 Feb 18  2020 docker-entrypoint.sh
</code>```

That is my entrypoint is not executable. Why? Why it's working locally then?

答:
Why it is working locally, I cannot answer that. Two things you should try. One as the other commenters have suggested, do a chmod on the script to make it executable.

The other change, according to the Docker reference, the ENTRYPOINT command takes two forms. The exec form and the shell form. You are using the exec. It is possible that your environment variables are not being loaded correctly.

Try change to shell form.

Body:
So here is my Dockerfile, simplified. The original file is https://github.com/gremo/docker-folder-mirror/blob/master/Dockerfile:

FROM alpine:latest

COPY ./docker-entrypoint.sh /usr/local/bin/

ENTRYPOINT ["docker-entrypoint.sh"]

When I run my image locally (assuming the tag is folder-mirror:latest) everything works fine:

docker run --rm --env-file ./.env -v "${PWD}/data:/data" -v "${PWD}/logs:/var/log" folder-mirror:latest

However, if I try to run the image directory (from Docker Hub):

docker run --rm --env-file ./.env -v "${PWD}/data:/data" -v "${PWD}/logs:/var/log" gremo1982/folder-mirror

... it gives me the following error:

C:\Program Files\Docker\Docker\resources\bin\docker.exe: Error
  response from daemon: OCI runtime create failed:
  container_linux.go:346: starting container process caused "exec:
  \"docker-entrypoint.sh\": executable file not found in $PATH":
  unknown.

This is my first Docker image, so I'm pretty sure... I'm missing something. In fact, if I check the remote image i get:

/ # ls -la /usr/local/bin/
total 12
drwxr-xr-x    1 root     root          4096 Feb 18  2020 .
drwxr-xr-x    1 root     root          4096 Jan 16 22:52 ..
-rw-r--r--    1 root     root           890 Feb 18  2020 docker-entrypoint.sh

That is my entrypoint is not executable. Why? Why it's working locally then?


问:
windows 10 php 7.2 memcached
When I am transferring project to Windows (framework symfony), issue appears when running the command Composer update. I realized that on the server module is missing php mencached version php 7.2. I cannot find anywhere the module, could any one suggest me where can I find it or how can I compile, and where can I get the sours code& how to compile it.
Many thanks</p>

答:
check phpinfo() for found this information:

Compiler: MSVC14

Architecture: x64

PHP Extension Build: API20160303,NTS,VC14

Based on information in phpinfo(); choose right dll:

Source: https://github.com/nono303/PHP7-memcache-dll
Folder (based on example): vc14 / x64 / nts

Copy to php_memcache.dll to \PHP\v7.1\ext

Enable php_memcache in php.ini, add line:

extension=php_memcache.dll

Check if you see 'memcache' section in phpinfo();

Title: windows 10 php 7.2 memcached


问:
Drag and drop in WP7 for silverlight
I would like to have a way to drag some images that are displayed on my silvelight phone page to a specific location (for example a rectangle) on the same page.

How can I do this ?

Thanks in advance for any help

答: You can have a look at Laurent Bugnon WP7 Multitouch Behavior. It's an easy to use Behavior and it manages Drag and Drop.

Title: Drag and drop in WP7 for silverlight


问:
LoginActivity has leaked window DecorView@bb62df1[LoginActivity] that was originally added here
I keep getting the error that my Login Activity has a leaked window of some sort,
This is my block of code where the error occurs. I have tried to dismiss both the dialog and the Alert Box respectively, but still, keep getting this error.

```<code>    try
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
        builder.setTitle(R.string.login_ok_title);
        builder.setMessage(R.string.login_ok_text).setCancelable(false).setPositiveButton(R.string.ok, (dialog, id) ->
        {
            Intent intent =new Intent(LoginActivity.this, TrackActivity.class);
            startActivity(intent);
            TrackManagerService trackManager =TrackManagerService.getInstance();
            if (trackManager != null) {
                trackManager.setLoginListener(null);
            }

            LoginActivity.this.finish();
            dialog.dismiss();
        });
        alert = builder.create();
        alert.show();

    }
    catch (Exception ex)
    {
        ex.printStackTrace();
        Intent intent = new Intent(LoginActivity.this, TrackActivity.class);
        alert.dismiss();
        startActivity(intent);
        TrackManagerService trackManager = TrackManagerService.getInstance();
        if (trackManager != null)
        {
            trackManager.setLoginListener(null);
        }
        finish();
    }
</code>```

This is the Error Log

```<code>E/WindowManager: android.view.WindowLeaked: Activity com.example.tornado_app.LoginActivity has leaked window DecorView@59e20b9[LoginActivity] that was originally added here
    at android.view.ViewRootImpl.<init>(ViewRootImpl.java:627)
    at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:389)
    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:131)
    at android.app.Dialog.show(Dialog.java:531)
    at com.example.tornado_app.LoginActivity$2.lambda$onLoginResult$4$LoginActivity$2(LoginActivity.java:160)
    at com.example.tornado_app.-$$Lambda$LoginActivity$2$YvCiBtxWavxZ1iGtdLspSkuZOdU.run(Unknown Source:6)
    at android.os.Handler.handleCallback(Handler.java:907)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:216)
    at android.app.ActivityThread.main(ActivityThread.java:7625)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
</code>```

答:
Why are you use 2 time dialog.dismiss(); and after activity finish how you can dismiss dialog?Try to add below code

```<code>try {
    AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
    builder.setTitle(R.string.login_ok_title);
    builder.setMessage(R.string.login_ok_text).setCancelable(false).setPositiveButton(R.string.ok, (dialog, id) ->
    {
        //dialog.dismiss(); //Remove this
        Intent intent = new Intent(LoginActivity.this, TrackActivity.class);
        startActivity(intent);

        TrackManagerService trackManager = TrackManagerService.getInstance();
        if (trackManager != null) {
            trackManager.setLoginListener(null);
        }

        LoginActivity.this.finish();
        //dialog.dismiss(); //Remove this
    });
    alert = builder.create();
    alert.show();

} catch (Exception ex) {
    ex.printStackTrace();
    Intent intent = new Intent(LoginActivity.this, TrackActivity.class);
    startActivity(intent);
    TrackManagerService trackManager = TrackManagerService.getInstance();
    if (trackManager != null) {
        trackManager.setLoginListener(null);
    }
    finish();
}
</code>```

I hope this can help you!

Body:
I keep getting the error that my Login Activity has a leaked window of some sort,
This is my block of code where the error occurs. I have tried to dismiss both the dialog and the Alert Box respectively, but still, keep getting this error.

    try
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
        builder.setTitle(R.string.login_ok_title);
        builder.setMessage(R.string.login_ok_text).setCancelable(false).setPositiveButton(R.string.ok, (dialog, id) ->
        {
            Intent intent =new Intent(LoginActivity.this, TrackActivity.class);
            startActivity(intent);
            TrackManagerService trackManager =TrackManagerService.getInstance();
            if (trackManager != null) {
                trackManager.setLoginListener(null);
            }

            LoginActivity.this.finish();
            dialog.dismiss();
        });
        alert = builder.create();
        alert.show();

    }
    catch (Exception ex)
    {
        ex.printStackTrace();
        Intent intent = new Intent(LoginActivity.this, TrackActivity.class);
        alert.dismiss();
        startActivity(intent);
        TrackManagerService trackManager = TrackManagerService.getInstance();
        if (trackManager != null)
        {
            trackManager.setLoginListener(null);
        }
        finish();
    }

This is the Error Log

E/WindowManager: android.view.WindowLeaked: Activity com.example.tornado_app.LoginActivity has leaked window DecorView@59e20b9[LoginActivity] that was originally added here
    at android.view.ViewRootImpl.<init>(ViewRootImpl.java:627)
    at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:389)
    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:131)
    at android.app.Dialog.show(Dialog.java:531)
    at com.example.tornado_app.LoginActivity$2.lambda$onLoginResult$4$LoginActivity$2(LoginActivity.java:160)
    at com.example.tornado_app.-$$Lambda$LoginActivity$2$YvCiBtxWavxZ1iGtdLspSkuZOdU.run(Unknown Source:6)
    at android.os.Handler.handleCallback(Handler.java:907)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:216)
    at android.app.ActivityThread.main(ActivityThread.java:7625)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)

Body:
Why are you use 2 time dialog.dismiss(); and after activity finish how you can dismiss dialog?Try to add below code

try {
    AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
    builder.setTitle(R.string.login_ok_title);
    builder.setMessage(R.string.login_ok_text).setCancelable(false).setPositiveButton(R.string.ok, (dialog, id) ->
    {
        //dialog.dismiss(); //Remove this
        Intent intent = new Intent(LoginActivity.this, TrackActivity.class);
        startActivity(intent);

        TrackManagerService trackManager = TrackManagerService.getInstance();
        if (trackManager != null) {
            trackManager.setLoginListener(null);
        }

        LoginActivity.this.finish();
        //dialog.dismiss(); //Remove this
    });
    alert = builder.create();
    alert.show();

} catch (Exception ex) {
    ex.printStackTrace();
    Intent intent = new Intent(LoginActivity.this, TrackActivity.class);
    startActivity(intent);
    TrackManagerService trackManager = TrackManagerService.getInstance();
    if (trackManager != null) {
        trackManager.setLoginListener(null);
    }
    finish();
}

I hope this can help you!


问:
How replace specific strings on conditions in R?
I have data where I have compressed duplicate gene results to each be in 1 row. This has made some rows filled with commas, I am trying to replace rows which only contain commas with NA. However, I also have rows with commas and qualitative data I am trying to keep. For example:

```<code>Gene     Condition
Gene1    Name=Asymmetrical dimethylarginine level, Name=Bipolar disorder and schizophrenia, Name=3-hydroxypropylmercapturic acid levels in smoker
Gene2    Name=blood pressure, Name=diabetes
Gene3    Name=heart disease, , , , ,
Gene4    , , , , , , , , ,
Gene5    NA
Gene6    , , ,
</code>```

Expected output:

```<code>Gene     Condition
Gene1    Name=Asymmetrical dimethylarginine level, Name=Bipolar disorder and schizophrenia, Name=3-hydroxypropylmercapturic acid levels in smoker
Gene2    Name=blood pressure, Name=diabetes
Gene3    Name=heart disease, , , , ,
Gene4    NA
Gene5    NA
Gene6    NA
#ideally I would get rid of Gene3's extra commas but this is not necessary
</code>```

I am trying to code for a statement like "if the row has only commas in the condition column replace to NA", and trying to do it with a statement like data$Condition[ if("," & ![A-Z]|[a-z]|[=]) ] <- "NA" but I'm not sure how to get the syntax right or if this will work for all rows with only commas but the number of commas varies - I am new to R so any guidance would be appreciated.

Example data:

```<code>DF <-
structure(list(Gene = c("Gene1", "Gene2", "Gene3", "Gene4", "Gene5",
"Gene6"), Condition = c("Name=Asymmetrical dimethylarginine leve,l Name=Bipolar disorder and schizophrenia, Name=3-hydroxypropylmercapturic acid levels in smoker",
"Name=blood pressure, Name=diabetes", "Name=heart disease, , , , ,",
", , , , , , , , ,", NA, "Name=kidney disease, , ,")),
row.names = c(NA, -6L), class = "data.frame")
</code>```

答:
An option

grepl(pattern= "^[ ,]+$")

When the row which only contains blanck space and comma , this function will return TRUE.

```<code>DF <-
structure(list(Gene = c("Gene1", "Gene2", "Gene3", "Gene4", "Gene5",
"Gene6"), Condition= c("Name=Asymmetrical dimethylarginine leve,l Name=Bipolar disorder and schizophrenia, Name=3-hydroxypropylmercapturic acid levels in smoker",
"Name=blood pressure, Name=diabetes", "Name=heart disease, , , , ,",
", , , , , , , , ,", NA, "Name=kidney disease, , ,")),
row.names = c(NA, -6L), class = "data.frame")

DF[which(grepl("^[ ,]+$",DF$Condition)==T),2]<-NA

</code>```

Body:
I have data where I have compressed duplicate gene results to each be in 1 row. This has made some rows filled with commas, I am trying to replace rows which only contain commas with NA. However, I also have rows with commas and qualitative data I am trying to keep. For example:

Gene     Condition
Gene1    Name=Asymmetrical dimethylarginine level, Name=Bipolar disorder and schizophrenia, Name=3-hydroxypropylmercapturic acid levels in smoker
Gene2    Name=blood pressure, Name=diabetes
Gene3    Name=heart disease, , , , ,
Gene4    , , , , , , , , ,
Gene5    NA
Gene6    , , ,

Expected output:

Gene     Condition
Gene1    Name=Asymmetrical dimethylarginine level, Name=Bipolar disorder and schizophrenia, Name=3-hydroxypropylmercapturic acid levels in smoker
Gene2    Name=blood pressure, Name=diabetes
Gene3    Name=heart disease, , , , ,
Gene4    NA
Gene5    NA
Gene6    NA
#ideally I would get rid of Gene3's extra commas but this is not necessary

I am trying to code for a statement like "if the row has only commas in the condition column replace to NA", and trying to do it with a statement like data$Condition[ if("," & ![A-Z]|[a-z]|[=]) ] <- "NA" but I'm not sure how to get the syntax right or if this will work for all rows with only commas but the number of commas varies - I am new to R so any guidance would be appreciated.

Example data:

DF <-
structure(list(Gene = c("Gene1", "Gene2", "Gene3", "Gene4", "Gene5",
"Gene6"), Condition = c("Name=Asymmetrical dimethylarginine leve,l Name=Bipolar disorder and schizophrenia, Name=3-hydroxypropylmercapturic acid levels in smoker",
"Name=blood pressure, Name=diabetes", "Name=heart disease, , , , ,",
", , , , , , , , ,", NA, "Name=kidney disease, , ,")),
row.names = c(NA, -6L), class = "data.frame")

Body:
An option

grepl(pattern= "^[ ,]+$")

When the row which only contains blanck space and comma , this function will return TRUE.

DF <-
structure(list(Gene = c("Gene1", "Gene2", "Gene3", "Gene4", "Gene5",
"Gene6"), Condition= c("Name=Asymmetrical dimethylarginine leve,l Name=Bipolar disorder and schizophrenia, Name=3-hydroxypropylmercapturic acid levels in smoker",
"Name=blood pressure, Name=diabetes", "Name=heart disease, , , , ,",
", , , , , , , , ,", NA, "Name=kidney disease, , ,")),
row.names = c(NA, -6L), class = "data.frame")

DF[which(grepl("^[ ,]+$",DF$Condition)==T),2]<-NA


问:
Kotlin parcelable class throwing ClassNotFoundException
I have a class that I use as my data model for a RecyclerViewin order to pass object of this class from one activity to another via Intent I had to make it Parcelable

The problem is now that I am being able to send the object from one activity to another and retrieve it, so that the app does not crash, but keeps throwing ClassNotFoundException in the logcat screen.

What am I doing wrong?

----> Person.kt

```<code>@Parcelize
class Person(var name: String, var username: String, var address: String, val avatar: Int) : Parcelable
</code>```

----> in MainActivity.kt

```<code>val intent = Intent(this, ProfilePage::class.java)
        intent.putExtra("clicked_person",person)
        startActivity(intent)
</code>```

---->. onCreate() in ProfilePAge.kt

```<code>var person  = intent.getParcelableExtra<Person>("clicked_person") as Person
</code>```

And the Exception

```<code>E/Parcel: Class not found when unmarshalling: com.example.testkot.kotlinapp.Person
                                         java.lang.ClassNotFoundException: com.example.testkot.kotlinapp.Person
</code>```

Please remember that the app does not crash, it keeps working but shows the exception in logcat

答:
In the first Activity:

```<code> val intent = Intent(this@MainActivity, DetailsActivity::class.java)
        intent.putExtra(Const.SELECTED_NOTE, noteList[position])
        startActivity(intent)
</code>```

In the Second Activity:

```<code>val note = intent.getParcelableExtra<Note>(Const.SELECTED_NOTE)
</code>```

EXPLAIN: First you should Put Parcelable Data and call getParcelableExtra in next activity!
in getParcelableExtra you should call Data class (here is Note ) and Key Of Bundle (here is Const.SELECTED_NOTE)!

Body:
I have a class that I use as my data model for a RecyclerViewin order to pass object of this class from one activity to another via Intent I had to make it Parcelable

The problem is now that I am being able to send the object from one activity to another and retrieve it, so that the app does not crash, but keeps throwing ClassNotFoundException in the logcat screen.

What am I doing wrong?

----> Person.kt

@Parcelize
class Person(var name: String, var username: String, var address: String, val avatar: Int) : Parcelable

----> in MainActivity.kt

val intent = Intent(this, ProfilePage::class.java)
        intent.putExtra("clicked_person",person)
        startActivity(intent)

---->. onCreate() in ProfilePAge.kt

var person  = intent.getParcelableExtra<Person>("clicked_person") as Person

And the Exception

E/Parcel: Class not found when unmarshalling: com.example.testkot.kotlinapp.Person
                                         java.lang.ClassNotFoundException: com.example.testkot.kotlinapp.Person

Please remember that the app does not crash, it keeps working but shows the exception in logcat

Body:
In the first Activity:

 val intent = Intent(this@MainActivity, DetailsActivity::class.java)
        intent.putExtra(Const.SELECTED_NOTE, noteList[position])
        startActivity(intent)

In the Second Activity:

val note = intent.getParcelableExtra<Note>(Const.SELECTED_NOTE)

EXPLAIN: First you should Put Parcelable Data and call getParcelableExtra in next activity!
in getParcelableExtra you should call Data class (here is Note ) and Key Of Bundle (here is Const.SELECTED_NOTE)!


问:
Open whatsapp chat for a number ionic 3/4
I have developed an app that should open a whatsapp chat using this plugin.

I installed it using ionic CLI ionic cordova plugin add https://github.com/ranjitpandit/whatsapp-phonegap-plugin.git and the used it as below:

home.page.ts

```<code>...

declare var cordova;

...
constructor(public platform: Platform) {}

chat() {

    this.platform.ready().then(() => {

      cordova.plugins.Whatsapp.send('+263783187321');

    });

}
</code>```

Then in home.page.html I then did this:

```<code><ion-row>
    <ion-col size="12" no-padding>
      <img src="assets/imgs/chat.jpg" (click)="chat()" class="chat" />
    </ion-col>
</ion-row>
</code>```

The problem is that it's not opening a Whatsapp chat window when I click the image. Nothing happens. Please help. Thank you

答:
This simple method works for me in my PWA both in web and mobile(android) versions without having to add access into the config file:

JS:

```<code>window.open(`https://api.whatsapp.com/send?phone=${phoneNumber}`
</code>```

or

HTML:

```<code><a href=`https://api.whatsapp.com/send?phone=${phoneNumber}`>Link</a>
</code>```

Body:
I have developed an app that should open a whatsapp chat using this plugin.

I installed it using ionic CLI ionic cordova plugin add https://github.com/ranjitpandit/whatsapp-phonegap-plugin.git and the used it as below:

home.page.ts

...

declare var cordova;

...
constructor(public platform: Platform) {}

chat() {

    this.platform.ready().then(() => {

      cordova.plugins.Whatsapp.send('+263783187321');

    });

}

Then in home.page.html I then did this:

<ion-row>
    <ion-col size="12" no-padding>

    </ion-col>
</ion-row>

The problem is that it's not opening a Whatsapp chat window when I click the image. Nothing happens. Please help. Thank you

Body:
This simple method works for me in my PWA both in web and mobile(android) versions without having to add access into the config file:

JS:

window.open(`https://api.whatsapp.com/send?phone=${phoneNumber}`

or

HTML:

<a href=`https://api.whatsapp.com/send?phone=${phoneNumber}`>Link</a>


问:
Angular: how to submit form group on enter key pressed
I have a form which submits a request to the database to filter some data in a grid. The form is submitted when submit button is pressed but I need it to submit the form when enter key is pressed also.

HTML

```<code><form [formGroup]="bmForm"
    (keyup.enter)="onSearchClicked()"
    (ngSubmit)="onSearchClicked()">
    <div class="form-group">
        <div>
           <label>Full Text Search</label>
           <input type="name" class="form-control" id="search"
                formControlName="ftSearch"
                placeholder="Full Text Search">
        </div>
        <div>
            <label>Identifier</label>
            <input type="name" class="form-control" id="search"
                formControlName="id"
                placeholder="Identifier">
        </div>
    </div>
    <button
        type="submit"
        class="btn btn-primary mr-2"
        (keyup.enter)="onSearchClicked()"
        (keydown.enter)="onSearchClicked()">
        Search
    </button>
</form>
</code>```

I have tried using (keyup.enter)="onSearchClicked()" in the <form> &  <button> tag without making changes to the Typescript but have had no success. Currently the Enter tab refreshes the page when clicked.

答:
The keyup event is sent to an element when the user releases a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus.

Your submit button probably doesn't have focus when the page loads. The function never gets called.

You could force focus to the button by adding the autofocus attribute, however this is probably not what you want from a usability perspective (you'd probably want the first text input to have focus).

Try moving keyup.enter to the <form> element.

```<code><form (keyup.enter)="onSearchClicked()">
  // your form
</form>
</code>```

Body:
I have a form which submits a request to the database to filter some data in a grid. The form is submitted when submit button is pressed but I need it to submit the form when enter key is pressed also.

HTML

<form [formGroup]="bmForm"
    (keyup.enter)="onSearchClicked()"
    (ngSubmit)="onSearchClicked()">

           Full Text Search
           <input type="name" class="form-control" id="search"
                formControlName="ftSearch"
                placeholder="Full Text Search">

            Identifier
            <input type="name" class="form-control" id="search"
                formControlName="id"
                placeholder="Identifier">

    <button
        type="submit"
        class="btn btn-primary mr-2"
        (keyup.enter)="onSearchClicked()"
        (keydown.enter)="onSearchClicked()">
        Search
    </button>
</form>

I have tried using (keyup.enter)="onSearchClicked()" in the <form> &  <button> tag without making changes to the Typescript but have had no success. Currently the Enter tab refreshes the page when clicked.

Body:
The keyup event is sent to an element when the user releases a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus.

Your submit button probably doesn't have focus when the page loads. The function never gets called.

You could force focus to the button by adding the autofocus attribute, however this is probably not what you want from a usability perspective (you'd probably want the first text input to have focus).

Try moving keyup.enter to the <form> element.

<form (keyup.enter)="onSearchClicked()">
  // your form
</form>


问:
How to send the "chosen drop down option" to reciepnt and not the respective email id assiciated with it in contactform7?
I am creating a form using contactform7. I have to dynamically change the recipient depending on the "country" selected from the drop-down list. I have successfully done that by:

[select* Recipient placeholder "Country" "China|sidraaleem1234@gmail.com" "Belgium|sidraaleem@alumni.sjtu.edu.cn" "Canada|sidra.aleem@emcc-China.com"]```

Now, I want to send the country selected from the drop-down list to the email recipient. I have added [recipient] field in the message body under the mail tab of contactform7.

However, in the email, I get the respective email id of the chosen country from the drop-down as visible in the attached image. Though in drop-down I only added country names, not the email ids.
screenshot

Can someone help me to send the only country names to the receiver and not the email id?

答:
To get the value after pipe character, put the usual mail tag corresponding to the form tag ([your-recipient] in the case of the above example) in the Mail templates. To get value before pipe, you can use [raw{field name}] ([_raw_your-recipient]

This is completely explained in the Contact Form 7 Documentation

In your case, it's [_raw_Recipient]

Body:
I am creating a form using contactform7. I have to dynamically change the recipient depending on the "country" selected from the drop-down list. I have successfully done that by:

[select* Recipient placeholder "Country" "China|sidraaleem1234@gmail.com" "Belgium|sidraaleem@alumni.sjtu.edu.cn" "Canada|sidra.aleem@emcc-China.com"]

Now, I want to send the country selected from the drop-down list to the email recipient. I have added [recipient] field in the message body under the mail tab of contactform7.

However, in the email, I get the respective email id of the chosen country from the drop-down as visible in the attached image. Though in drop-down I only added country names, not the email ids.
screenshot

Can someone help me to send the only country names to the receiver and not the email id?


问:
Defining a new variable from division of another two variables with bash script
I have 2 variables which are up_votes and down_votes from a csv dataset. I am trying to create a new variable as percentage of up_votes / total_votes. For example, up_votes=296 down_votes=255, my output should be 53.7 but I get 25600.
Here is my equations.</p>

```<code>    x=$col3
    y=$col3+$col4
    z=($x/$y)*100
    ans=$z
</code>```

答:
You need to use external programs to do calculations because bash does not support float point arithmetic

#!/bin/bash

votes="topic1,0,0 topic2,296,255 topic3,3,4"

for vote_data in $votes ; do
    topic=`echo $vote_data|sed -r 's/([^,]*),([^,]*),(.*)/\1/'`
    up_votes=`echo $vote_data|sed -r 's/([^,]*),([^,]*),(.*)/\2/'`
    down_votes=`echo $vote_data|sed -r 's/([^,]*),([^,]*),(.*)/\3/'`

#    echo "$topic , up: $up_votes, down: $down_votes"

    total=`awk "BEGIN {print ($up_votes+$down_votes)}"`
    if [ $total -eq 0 ];then
    ans=divbyzero
    else
    ans=`awk "BEGIN {print 100.0*$up_votes/( $up_votes+$down_votes)}"`
    fi
    echo "$topic $ans [ $up_votes / $down_votes ]"

done
```

<p><strong>output:</strong></p>

```topic1 divbyzero [ 0 / 0 ]
topic2 53.7205 [ 296 / 255 ]
topic3 42.8571 [ 3 / 4 ]
```

Body:
I have 2 variables which are up_votes and down_votes from a csv dataset. I am trying to create a new variable as percentage of up_votes / total_votes. For example, up_votes=296 down_votes=255, my output should be 53.7 but I get 25600.
Here is my equations.

    x=$col3
    y=$col3+$col4
    z=($x/$y)*100
    ans=$z

Body:
You need to use external programs to do calculations because bash does not support float point arithmetic

#!/bin/bash

votes="topic1,0,0 topic2,296,255 topic3,3,4"

for vote_data in $votes ; do
    topic=`echo $vote_data|sed -r 's/([^,]*),([^,]*),(.*)/\1/'`
    up_votes=`echo $vote_data|sed -r 's/([^,]*),([^,]*),(.*)/\2/'`
    down_votes=`echo $vote_data|sed -r 's/([^,]*),([^,]*),(.*)/\3/'`

#    echo "$topic , up: $up_votes, down: $down_votes"

    total=`awk "BEGIN {print ($up_votes+$down_votes)}"`
    if [ $total -eq 0 ];then
    ans=divbyzero
    else
    ans=`awk "BEGIN {print 100.0*$up_votes/( $up_votes+$down_votes)}"`
    fi
    echo "$topic $ans [ $up_votes / $down_votes ]"

done

output:

topic1 divbyzero [ 0 / 0 ]
topic2 53.7205 [ 296 / 255 ]
topic3 42.8571 [ 3 / 4 ]


问:
What project would you recommend me to get up to speed with C++
I know that C++ is a very complex language that takes many years of practice to master.

Taking that into account do you know of a small project (around a 1k of loc) that tests all of C++ major features (inheritance, pointers, memory management, etc).

The thing is I'm a Java/Python programmer and I really want to learn C++ so I've been studying C++ for a while but haven't tested anything of what I've learned beyond small exercises.

I want to take all of that knowledge and put into practice.

答:
When I was learning C++, I used it to write my own language for writing Colossal Cave style adventures. Like most computer languages it never saw the light of day, but it did teach me a lot about C++.

Whatever you choose the thing to avoid when learning C++ is GUI programming, which is a trap which will drain all your gumption and probably teach you bad C++ habits in the process.

OwnerDisplayName: climatewarrior

OwnerDisplayName: anon

ContentLicense: CC BY-SA 2.5


问:
Java program skips asking for user input
I am trying to ask the user for a date and a time. In my program I have methods to ask the user for these values and methods to validate the inputs. However in my program, the user is never able to input the date value, as the program continues past that point and takes a null value for the date. Why is this? As a result the validation methods cause an error:

```<code>java.lang.NullPointerException
</code>```

"Main"

```<code>    public void bookAppointment(BankClient bc) {
    String date = askForDate();
    String time = askForTime();
    sendAppointmentNotification(createAppointmentNotification(date,time));
}
</code>```

Ask For Date Method

```<code>    private String askForDate() {
    GetInputFromUserInter input = new GetInputFromUser();
    while(true) {
        String date = input.getUserInput("Date For Appointment in the form of DD/MM/YYYY");
        date.trim();
        if (validateDate(date)) {
            return date;
        }
        else {
            System.out.println(date+" is Invalid Date format");
        }
    }
}
</code>```

Validate Date method

```<code>    private static boolean validateDate(String date) {
    System.out.println("here");
    SimpleDateFormat sdfrmt = new SimpleDateFormat("DD/MM/YYYY");
    sdfrmt.setLenient(false);
    try{
            Date javaDate = sdfrmt.parse(date);
    }
        /* Date format is invalid */
    catch (ParseException e){
        return false;
    }
    /* Return true if date format is valid */
        return true;
}
</code>```

Get Input Method

```<code>    static BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
public String getUserInput(String label) {
    String value = null;
    System.out.println( "\nProvide " + label + ":" );
    System.out.println( ">" );

    while(value !=null) {

        try {
            value = input.readLine();
        }

        catch (IOException ex) { ex.printStackTrace(); }
    }
    return value;
};
</code>```

答:
The reason your program skips the user input is because you are initializing String value = null in your getUserInput()method and then effectively saying while null != null which is false and thus your while loop never executes. I would modify the code like this:

```<code>String value = "";
System.out.println( "\nProvide " + label + ":" );
System.out.println( ">" );

while(value.equals("")) {

    try {
        value = input.readLine();
    }

    catch (IOException ex) { ex.printStackTrace(); }
}
return value;
</code>```

Then if the user just spams enter without typing anything it will continuously promt him to enter something.

Body:
I am trying to ask the user for a date and a time. In my program I have methods to ask the user for these values and methods to validate the inputs. However in my program, the user is never able to input the date value, as the program continues past that point and takes a null value for the date. Why is this? As a result the validation methods cause an error:

java.lang.NullPointerException

"Main"

    public void bookAppointment(BankClient bc) {
    String date = askForDate();
    String time = askForTime();
    sendAppointmentNotification(createAppointmentNotification(date,time));
}

Ask For Date Method

    private String askForDate() {
    GetInputFromUserInter input = new GetInputFromUser();
    while(true) {
        String date = input.getUserInput("Date For Appointment in the form of DD/MM/YYYY");
        date.trim();
        if (validateDate(date)) {
            return date;
        }
        else {
            System.out.println(date+" is Invalid Date format");
        }
    }
}

Validate Date method

    private static boolean validateDate(String date) {
    System.out.println("here");
    SimpleDateFormat sdfrmt = new SimpleDateFormat("DD/MM/YYYY");
    sdfrmt.setLenient(false);
    try{
            Date javaDate = sdfrmt.parse(date);
    }
        /* Date format is invalid */
    catch (ParseException e){
        return false;
    }
    /* Return true if date format is valid */
        return true;
}

Get Input Method

    static BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
public String getUserInput(String label) {
    String value = null;
    System.out.println( "\nProvide " + label + ":" );
    System.out.println( ">" );

    while(value !=null) {

        try {
            value = input.readLine();
        }

        catch (IOException ex) { ex.printStackTrace(); }
    }
    return value;
};

Body:
The reason your program skips the user input is because you are initializing String value = null in your getUserInput()method and then effectively saying while null != null which is false and thus your while loop never executes. I would modify the code like this:

String value = "";
System.out.println( "\nProvide " + label + ":" );
System.out.println( ">" );

while(value.equals("")) {

    try {
        value = input.readLine();
    }

    catch (IOException ex) { ex.printStackTrace(); }
}
return value;

Then if the user just spams enter without typing anything it will continuously promt him to enter something.


问:
"Unable to access jarfile jenkins.war" getting this error while run the cmd "java -jar jenkins.war" in OS- windows 7
"Unable to access jarfile jenkins.war" getting this error while run the cmd "java -jar jenkins.war" in OS- windows 7

How can I solve?
i did installation as per what showed in youtube

答:
Open Command Prompt as Administrator in Windows . Go to the directory where Jenkins is installed. and stop the Jenkins service first, using jenkins.exe stop

type the command to change the port using, java -jar jenkins.war

You will be able to access the .war file of Jenkins.


问:
Where is placed createSwitchNavigator in react-navigation 5.x for migrating from react-navigation 4 to 5.x
I'm migrating a React Native application from react-navigation 4 to 5.x and i can't find which package contains createSwitchNavigation. Specifically i have doubts with the auth token check part.

With react-navigation 4 i had:

const switchNavigator = createSwitchNavigator({
  ResolveAuth: ResolveAuthScreen,
  signinFlow: createStackNavigator({
    Signup: SignupScreen,
    Signin: SigninScreen,
  }),
  appFlow: createBottomTabNavigator({
    TrackCreate: TrackCreateScreen,
    trackListFlow: createStackNavigator({
      TrackList: TrackListScreen,
      TrackDetail: TrackDetailScreen
    }),
    Account: AccountScreen,
  })
}, {
  initialRouteName: 'ResolveAuth'
});
```

<p>Then i have a file containing ResolveAuthScreen component.</p>

<pre class="lang-js prettyprint-override"><code>import React, { useEffect } from 'react';
import { connect } from 'react-redux';

const ResolveAuthScreen = (props) => {
  useEffect(() => {
    if (!props.token) {
      props.navigation.navigate('loginFlow');
    } else {
      props.navigation.navigate('TrackList');
    }
  }, []);

  return null;
};

const mapStateToProps = (state) => {
  return {
    token: state.auth.token,
  };
};

export default connect(mapStateToProps, null)(ResolveAuthScreen);
</code>```

The rest of components are not important for this doubt. I want to know how to replicate the same Switch navigation flow.
I would like to know how can i create something like this:

const Switch = createSwitchNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Switch.Navigator>
        <Switch.Screen name="ResolveAuth" component={ResolveAuthScreen} />
        <Switch.Screen name="signinFlow" component={SignInFlowScreens} />
        <Switch.Screen name="appFlow" component={AppFlowScreens} />
      </Switch.Navigator>
    </NavigationContainer>
  );
}
```

答:
In earlier versions of React Navigation, there were 2 ways to handle this:

Keep multiple navigators and use switch navigator to switch the active navigator to a different one upon login (recommended)

Reset the state of the navigator to the desired screens upon login

But for v5, you need to use context. Take a look at here to see a detailed example!

Body:
I'm migrating a React Native application from react-navigation 4 to 5.x and i can't find which package contains createSwitchNavigation. Specifically i have doubts with the auth token check part.

With react-navigation 4 i had:

const switchNavigator = createSwitchNavigator({
  ResolveAuth: ResolveAuthScreen,
  signinFlow: createStackNavigator({
    Signup: SignupScreen,
    Signin: SigninScreen,
  }),
  appFlow: createBottomTabNavigator({
    TrackCreate: TrackCreateScreen,
    trackListFlow: createStackNavigator({
      TrackList: TrackListScreen,
      TrackDetail: TrackDetailScreen
    }),
    Account: AccountScreen,
  })
}, {
  initialRouteName: 'ResolveAuth'
});

Then i have a file containing ResolveAuthScreen component.

import React, { useEffect } from 'react';
import { connect } from 'react-redux';

const ResolveAuthScreen = (props) => {
  useEffect(() => {
    if (!props.token) {
      props.navigation.navigate('loginFlow');
    } else {
      props.navigation.navigate('TrackList');
    }
  }, []);

  return null;
};

const mapStateToProps = (state) => {
  return {
    token: state.auth.token,
  };
};

export default connect(mapStateToProps, null)(ResolveAuthScreen);

The rest of components are not important for this doubt. I want to know how to replicate the same Switch navigation flow.
I would like to know how can i create something like this:

const Switch = createSwitchNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Switch.Navigator>
        <Switch.Screen name="ResolveAuth" component={ResolveAuthScreen} />
        <Switch.Screen name="signinFlow" component={SignInFlowScreens} />
        <Switch.Screen name="appFlow" component={AppFlowScreens} />
      </Switch.Navigator>
    </NavigationContainer>
  );
}


问:
a connection attempt failed because the connected party did not properly respond python
I am trying to connect to LDAP.
server = Server('LDAP://url', get_info=ALL)
conn = Connection(server, auto_bind= True)

when I run this i get an error:
"a connection attempt failed because the connected party did not properly respond...."
[WinError 10060]

Kindly help.
Thanks in advance

答:
The error indicates that the client cannot reach the server.

Is 'LDAP://url' the real address of the server you are trying to connect to?


问:
How do I distinguish iPad 1 from iPad 2 in Cocoa?
My app needs to know where iPad's mic is, and the only way I know is to see if it's running on iPad, or on iPad 2, and act accordingly.

So - how do I check the device model?

答:
This SO answer provides a detailed method for using the sysctlbyname("hw.machine"... system.

Determine device (iPhone, iPod Touch) with iPhone SDK


问:
How to handle "invalid use of non-static data member" in class Implementation in c++?
I've been trying to solve a question Word Search II on LeetCode that requires use of Trie to help make the backtracking calls more efficient and basically tries are to be used, I've been trying to implement my own trie class but I'm running into a road block in my remove function, it requires a copy of root, but I'm not sure how to give it one. Here is the part I'm having trouble with:

TrieNode* crawl = root in the function remove(string word, TrieNode* crawl = root, int depth = 0)

The error: invalid use of non-static data member 'Trie::root'

I don't know the correct way to do it.

```<code>TrieNode* remove(string word, TrieNode* crawl = root, int depth = 0) {
    if(!crawl) return nullptr;

    if(depth == word.size()) {
        if(crawl->isLeaf) crawl->isLeaf = false;
        if(isEmpty(crawl)) {
            delete crawl;
            crawl = nullptr;
        }
        return crawl;
    }

    int index = word[depth] - 'a';
    crawl->arr[index] = remove(word, crawl->arr[index], depth + 1);

    if(isEmpty(crawl) && crawl->isLeaf == false) {
        delete crawl;
        crawl = nullptr;
    }

    return crawl;
}
</code>```

This is what my Trie class looks like:

```<code>class Trie {
    private:
        TrieNode* root;

    public:
        Trie() : root(new TrieNode()) {};

        void insert(const string &word) {
            auto crawl = root;
            // does it's thing
        }

        bool search(const string &word) {
            auto crawl = root;
            // does it's thing
        }

        bool isPrefix(const string &word) {
            auto crawl = root;
            // does it's thing
        }

        bool isEmpty(TrieNode* root) {
            for(int i = 0; i < 26; i++) if(root->arr[i]) return false;
            return true;
        }

        TrieNode* remove(string word, TrieNode* crawl = root, int depth = 0) {
</code>```

With this as the TrieNode:

```<code>struct TrieNode {
    bool isLeaf;
    vector<TrieNode*> arr;
    TrieNode() : isLeaf(false), arr(26, nullptr) {};
};
</code>```

Edit: Special thanks to @SPD for suggesting an improvement on the remove function

答:
A few suggestions:

you don't really need a Trie class, TrieNode is sufficient. All operations insert/remove can be moved to TrieNode, you'll probably find it more 'natural' to write member functions of TrieNode

If you stick to you existing design and delete crawl itself followed by crawl = nullptr, I think you need to pass crawl by pointer reference rather than just pointer.

An alternative to #2 is to delete crawl in the calling stack. remove() now returns a boolean indicating if the caller can safely delete this node. Sample code below.

Lastly, please consider using managed ptrs rather than raw ptrs. (It probably doesn't matter for a leetcode exercise)

```<code>bool remove(string word, TrieNode* crawl, int depth = 0) {
    if(!crawl) return true;

    if(depth == word.size()) {
        if(crawl->isLeaf) crawl->isLeaf = false;
        return isEmpty(crawl);
    }

    int index = word[depth] - 'a';
    if (remove(word, crawl->arr[index], depth + 1)) {
        // it's empty or nullptr, safe to remove
        delete crawl->arr[index];
        crawl->arr[index] = nullptr;
    }
    return !crawl->isLeaf && isEmpty(crawl);
}
</code>```

Body:
I've been trying to solve a question Word Search II on LeetCode that requires use of Trie to help make the backtracking calls more efficient and basically tries are to be used, I've been trying to implement my own trie class but I'm running into a road block in my remove function, it requires a copy of root, but I'm not sure how to give it one. Here is the part I'm having trouble with:

TrieNode* crawl = root in the function remove(string word, TrieNode* crawl = root, int depth = 0)

The error: invalid use of non-static data member 'Trie::root'

I don't know the correct way to do it.

TrieNode* remove(string word, TrieNode* crawl = root, int depth = 0) {
    if(!crawl) return nullptr;

    if(depth == word.size()) {
        if(crawl->isLeaf) crawl->isLeaf = false;
        if(isEmpty(crawl)) {
            delete crawl;
            crawl = nullptr;
        }
        return crawl;
    }

    int index = word[depth] - 'a';
    crawl->arr[index] = remove(word, crawl->arr[index], depth + 1);

    if(isEmpty(crawl) && crawl->isLeaf == false) {
        delete crawl;
        crawl = nullptr;
    }

    return crawl;
}

This is what my Trie class looks like:

class Trie {
    private:
        TrieNode* root;

    public:
        Trie() : root(new TrieNode()) {};

        void insert(const string &word) {
            auto crawl = root;
            // does it's thing
        }

        bool search(const string &word) {
            auto crawl = root;
            // does it's thing
        }

        bool isPrefix(const string &word) {
            auto crawl = root;
            // does it's thing
        }

        bool isEmpty(TrieNode* root) {
            for(int i = 0; i < 26; i++) if(root->arr[i]) return false;
            return true;
        }

        TrieNode* remove(string word, TrieNode* crawl = root, int depth = 0) {

With this as the TrieNode:

struct TrieNode {
    bool isLeaf;
    vector<TrieNode*> arr;
    TrieNode() : isLeaf(false), arr(26, nullptr) {};
};

Edit: Special thanks to @SPD for suggesting an improvement on the remove function

Body:
A few suggestions:

you don't really need a Trie class, TrieNode is sufficient. All operations insert/remove can be moved to TrieNode, you'll probably find it more 'natural' to write member functions of TrieNode

If you stick to you existing design and delete crawl itself followed by crawl = nullptr, I think you need to pass crawl by pointer reference rather than just pointer.

An alternative to #2 is to delete crawl in the calling stack. remove() now returns a boolean indicating if the caller can safely delete this node. Sample code below.

Lastly, please consider using managed ptrs rather than raw ptrs. (It probably doesn't matter for a leetcode exercise)

bool remove(string word, TrieNode* crawl, int depth = 0) {
    if(!crawl) return true;

    if(depth == word.size()) {
        if(crawl->isLeaf) crawl->isLeaf = false;
        return isEmpty(crawl);
    }

    int index = word[depth] - 'a';
    if (remove(word, crawl->arr[index], depth + 1)) {
        // it's empty or nullptr, safe to remove
        delete crawl->arr[index];
        crawl->arr[index] = nullptr;
    }
    return !crawl->isLeaf && isEmpty(crawl);
}


问:
How can I find my php.ini on wordpress?
I want to increase max execution time on my wordpress site. I know I should edit php.ini, but can't seem to find it!

any tips?

答:
Okay. Answer for self hosted wordpress installations - you'll have to find the file yourself. For my WordPres site I use nginx with php7.3-fpm.

Running php -i | grep ini from console gives me several lines including:
Loaded Configuration File => /etc/php/7.3/cli/php.ini. This is ini configuration when running php command from command line, a.k.a. cli.

Then looking around I see there is also a file: /etc/php/7.3/fpm/php.ini I use FPM service so that is it! I edit it and THEN reload the service to apply my changes using: service php7.3-fpm reload.

That was it. Now I can upload bigger files to my WordPress. Good luck

Title: How can I find my php.ini on wordpress?


问:
Immer data not updating in Vue
I'm trying to use Immer with Vue.  It appears that the state is updating, but Vue isn't updating the UI

// immutable.js
import produce, { applyPatches } from "immer"

let undo_buffer = []
export var state = { items: [] }
const handle_add_patch = (patch, inverse_patches) => {
  console.log("Inverse Patches: ", inverse_patches)
  undo_buffer.push(inverse_patches)
}
export const add_item = (item_name) => {
  console.log("Starting add_item call")
  const next_state = produce(
    state,
    draft => {
      draft.items.push({ name: item_name })
    },
    handle_add_patch
  )
  console.log("next state: ", next_state)
  state = next_state
}
export const undo = () => {
  const undo_patch = undo_buffer.pop()
  if (!undo_patch) return
  let new_state = applyPatches(state, undo_patch)
  console.log("New State: ", new_state)
  state = new_state
}
```

<pre class="lang-html prettyprint-override"><code><!-- item_list.Vue -->
<template>
  <div>
    <button @click.prevent="add_item()">Add Item</button>
      {{ items }}
    <button @click.prevent="undo()">Undo</button>
  </div>
</template>
<script>
import * as immutable from './immutable.js'
export default {
  computed: {
    items: function(){ return immutable.state.items }
  },
  methods: {
    add_item(){
      console.log("State Before: ", immutable.state)
      immutable.add_item("Hello")
      console.log("State After: ", immutable.state)
    },
    undo(){
      console.log("State Before: ", immutable.state)
      immutable.undo()
      console.log("State After: ", immutable.state)
    }
  }
}
</script>
</code>```

The console.log shows that the items array is changing, but the items in the Vue template just shows an empty array.  How can I make this visible within Vue?

答:
Computed properties are cached and they aren't recomputed until associated component data is changed. Since Immer object isn't a part of the component, recomputation never occurs.

Caching can be prevented by using getter method instead of computed property:

```<code>{{ getItems() }}

...

methods: {
  getItems: () => immutable.state.items
  addItem() {
    immutable.add_item("Hello");
    this.$forceUpdate();
  }
}
</code>```

A more direct approach is to force a property to be recomputed:

```<code>data() {
  return { _itemsDirtyFlag: 0 }
},
computed: {
  items: {
    get() {
      this._itemsDirtyFlag; // associate it with this computed property
      return immutable.state.items;
    }
},
methods: {
  updateItems() {
    this._itemsDirtyFlag++;
  },
  addItem() {
    immutable.add_item("Hello");
    this.updateItems();
  }
}
</code>```

A similar approach that uses Vue.util.defineReactive internal is used by vue-recomputed.

Title: Immer data not updating in Vue

Body:
I'm trying to use Immer with Vue.  It appears that the state is updating, but Vue isn't updating the UI

// immutable.js
import produce, { applyPatches } from "immer"

let undo_buffer = []
export var state = { items: [] }
const handle_add_patch = (patch, inverse_patches) => {
  console.log("Inverse Patches: ", inverse_patches)
  undo_buffer.push(inverse_patches)
}
export const add_item = (item_name) => {
  console.log("Starting add_item call")
  const next_state = produce(
    state,
    draft => {
      draft.items.push({ name: item_name })
    },
    handle_add_patch
  )
  console.log("next state: ", next_state)
  state = next_state
}
export const undo = () => {
  const undo_patch = undo_buffer.pop()
  if (!undo_patch) return
  let new_state = applyPatches(state, undo_patch)
  console.log("New State: ", new_state)
  state = new_state
}

<template>

    <button @click.prevent="add_item()">Add Item</button>
      {{ items }}
    <button @click.prevent="undo()">Undo</button>

</template>

The console.log shows that the items array is changing, but the items in the Vue template just shows an empty array.  How can I make this visible within Vue?

Body:
Computed properties are cached and they aren't recomputed until associated component data is changed. Since Immer object isn't a part of the component, recomputation never occurs.

Caching can be prevented by using getter method instead of computed property:

{{ getItems() }}

...

methods: {
  getItems: () => immutable.state.items
  addItem() {
    immutable.add_item("Hello");
    this.$forceUpdate();
  }
}

A more direct approach is to force a property to be recomputed:

data() {
  return { _itemsDirtyFlag: 0 }
},
computed: {
  items: {
    get() {
      this._itemsDirtyFlag; // associate it with this computed property
      return immutable.state.items;
    }
},
methods: {
  updateItems() {
    this._itemsDirtyFlag++;
  },
  addItem() {
    immutable.add_item("Hello");
    this.updateItems();
  }
}

A similar approach that uses Vue.util.defineReactive internal is used by vue-recomputed.


问:
Manipulating array of objects into new array
I have the following array:

var my_json = [{
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "845",
}, {
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD2",
  PRODUCT_QUANTITY_MT: "1002",
}, {
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD3",
  PRODUCT_QUANTITY_MT: "45",
}, {
  DATE: "2020-02-02",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "20",
}, {
  DATE: "2020-02-03",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "10",
}, {
  DATE: "2020-02-03",
  PRODUCT_NAME: "PROD2",
  PRODUCT_QUANTITY_MT: "230",
}]
```

<p>From the above array I want to create two new arrays, for each day for each product how much was sold. The final array should look like this.</p>

<p>The first value would be a default value call <code>DATE</code> followed by each product name.</p>

```var final = [{
  title: "DATE"
}, {
  title: "PROD1"
}, {
  title: "PROD2"
}, {
  title: "PROD3"
}]
```

<p>I managed to create this by doing the following </p>

```var columns = [{ "title":"DATE" }];

$.each(my_json, function(index, element) {
  columns.push({ "title": element.PRODUCT_NAME })
});
```

<p>The second array should be in this format:</p>

```var data = [
  [ "2020-02-01", 845", "1002" , "45"],
  [ "2020-02-02", "20", "",  "" ],
  [ "2020-02-03", "10", "230",  "" ],
];
```

<p>As you can see, on <code>Feb 1</code> we have a value for all products sold but on <code>Feb 2</code> it's only <code>PROD1</code>. Likewise on <code>Feb 3</code> only <code>PROD2</code> and <code>PROD3</code>. </p>

<p>Each row col should match the first array like bellow</p>

<p><img src="https://i.stack.imgur.com/uegg3.png" alt="enter image description here"></p>

<p>desired output of two arrays as bellow</p>

```         var Array1 = [{title: "DATE"},{title: "PROD1"},{title: "PROD2"},
                      {title: "PROD3"}]

         var Array2 = [
                       [ "2020-02-01", 845", "1002" , "45"],
                       [ "2020-02-02", "20", "",  "" ],
                       [ "2020-02-03", "10", "230",  "" ],
                    ];
```

答:
Please refer below code

var my_json = [{
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "845",
}, {
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD2",
  PRODUCT_QUANTITY_MT: "1002",
}, {
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD3",
  PRODUCT_QUANTITY_MT: "45",
}, {
  DATE: "2020-02-02",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "20",
}, {
  DATE: "2020-02-03",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "10",
}, {
  DATE: "2020-02-03",
  PRODUCT_NAME: "PROD2",
  PRODUCT_QUANTITY_MT: "230",
}];
var Array1 = [{
  title: "DATE"
}];
var Array2 = [];
for (var i = 0; i < my_json.length; i++) {
  add(Array1, my_json[i].PRODUCT_NAME);
  switch (my_json[i].PRODUCT_NAME) {
    case "PROD1":
      Array2.push([my_json[i].DATE, my_json[i].PRODUCT_QUANTITY_MT, "", ""])
      break;
    case "PROD2":
      Array2.push([my_json[i].DATE, "", my_json[i].PRODUCT_QUANTITY_MT, ""])
      break;
    case "PROD3":
      Array2.push([my_json[i].DATE, "", "", my_json[i].PRODUCT_QUANTITY_MT])
      break;
  }
}

function add(arr, name) {
  const {
    length
  } = arr;
  const id = length + 1;
  const found = arr.some(el => el.title === name);
  if (!found) arr.push({
    title: name
  });
  return arr;
}

for (var i = 0; i < Array2.length; i++) {
  if (i != Array2.length - 1 && Array2[i][0] == Array2[i + 1][0]) {
    Array2[i + 1][1] != "" ? Array2[i][1] = Array2[i + 1][1] : Array2[i][1];
    Array2[i + 1][2] != "" ? Array2[i][2] = Array2[i + 1][2] : Array2[i][2];
    Array2[i + 1][3] != "" ? Array2[i][3] = Array2[i + 1][3] : Array2[i][3];
    Array2.splice(i + 1, 1);
    i--;
  }
}
console.log(Array1);

console.log(Array2);```

Body:
I have the following array:

var my_json = [{
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "845",
}, {
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD2",
  PRODUCT_QUANTITY_MT: "1002",
}, {
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD3",
  PRODUCT_QUANTITY_MT: "45",
}, {
  DATE: "2020-02-02",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "20",
}, {
  DATE: "2020-02-03",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "10",
}, {
  DATE: "2020-02-03",
  PRODUCT_NAME: "PROD2",
  PRODUCT_QUANTITY_MT: "230",
}]

From the above array I want to create two new arrays, for each day for each product how much was sold. The final array should look like this.

The first value would be a default value call DATE followed by each product name.

var final = [{
  title: "DATE"
}, {
  title: "PROD1"
}, {
  title: "PROD2"
}, {
  title: "PROD3"
}]

I managed to create this by doing the following

var columns = [{ "title":"DATE" }];

$.each(my_json, function(index, element) {
  columns.push({ "title": element.PRODUCT_NAME })
});

The second array should be in this format:

var data = [
  [ "2020-02-01", 845", "1002" , "45"],
  [ "2020-02-02", "20", "",  "" ],
  [ "2020-02-03", "10", "230",  "" ],
];

As you can see, on Feb 1 we have a value for all products sold but on Feb 2 it's only PROD1. Likewise on Feb 3 only PROD2 and PROD3.

Each row col should match the first array like bellow

desired output of two arrays as bellow

         var Array1 = [{title: "DATE"},{title: "PROD1"},{title: "PROD2"},
                      {title: "PROD3"}]

         var Array2 = [
                       [ "2020-02-01", 845", "1002" , "45"],
                       [ "2020-02-02", "20", "",  "" ],
                       [ "2020-02-03", "10", "230",  "" ],
                    ];


问:
Calculate columns from multiple CSV files and save results into a new file
I'm new to Python and trying to do the following with python/pandas.

I have four CSV files that look like this (the only difference is the date value in the first column):

First_week.csv:

```<code>     date       id   name   total_unitCount   total_orderCount   total_invoiceCount
  2020-02-12     1   Guitar        300              600                   500
  2020-02-12     2   Drums         500              600                   500
  2020-02-12     3   Piano         700              1000                  400
</code>```

Second_week.csv:

```<code>     date       id   name   total_unitCount   total_orderCount   total_invoiceCount
  2020-02-05     1   Guitar        300              800                   500
  2020-02-05     2   Drums         500              300                   500
  2020-02-05     3   Piano         700              350                  400
</code>```

I need to calculate the % difference between two numbers in each csv file/between each weeks (first_week.total_orderCount vs second_week.total_orderCount, second vs third, third vs fourth):

Example of calculation:
Difference = ((total_orderCount[where date is 2020-02-12] - total_orderCount[where date is 2020-12-05] ) / Units[where date is 2020-12-05]) * 100%

Then save results to a new CSV file for each week (here I provided results only for the week1vsweek2):

```<code>    id   name   %difference_week1vsweek2  %difference_week2vsweek3  %difference_week3vsweek4
    1   Guitar             -0.25
    2   Drums                1
    3   Piano               0.65
</code>```

Would someone be able to help or give me some step by step instructions?
Thank you in advance!

答:
Pseudo-code on how to do column calculations from multiple CSV files and save the results to a new file using pandas in python is

```<code>import pandas as pd
df1 = pd.read_csv('First.csv')
df2 = pd.read_csv('Second.csv')
output_df = pd.DataFrame(columns = ["col1", "col2"])
output_df['result'] = df1['col2'] -df2['col2'] # some column calculation
df3.to_format("output.format")
</code>```

Here is the actual code for the given example in the Question

```<code>#import libraries
import pandas as pd

#read files
df1 = pd.read_csv('First_week.csv')
df2 = pd.read_csv('Second_week.csv')

#Create new file and save results
column_names = ["id", "name"]
df3 = pd.DataFrame(columns = column_names)
df3[['id', 'name']] = df1[['id', 'name']]
df3['%difference_week1vsweek2'] = (df1['total_orderCount']-df2['total_orderCount'])/df2['total_orderCount']*100
print(df3)

df3.to_csv("output.csv")
</code>```

Hope it helps.

Body:
I'm new to Python and trying to do the following with python/pandas.

I have four CSV files that look like this (the only difference is the date value in the first column):

First_week.csv:

     date       id   name   total_unitCount   total_orderCount   total_invoiceCount
  2020-02-12     1   Guitar        300              600                   500
  2020-02-12     2   Drums         500              600                   500
  2020-02-12     3   Piano         700              1000                  400

Second_week.csv:

     date       id   name   total_unitCount   total_orderCount   total_invoiceCount
  2020-02-05     1   Guitar        300              800                   500
  2020-02-05     2   Drums         500              300                   500
  2020-02-05     3   Piano         700              350                  400

I need to calculate the % difference between two numbers in each csv file/between each weeks (first_week.total_orderCount vs second_week.total_orderCount, second vs third, third vs fourth):

Example of calculation:
Difference = ((total_orderCount[where date is 2020-02-12] - total_orderCount[where date is 2020-12-05] ) / Units[where date is 2020-12-05]) * 100%

Then save results to a new CSV file for each week (here I provided results only for the week1vsweek2):

    id   name   %difference_week1vsweek2  %difference_week2vsweek3  %difference_week3vsweek4
    1   Guitar             -0.25
    2   Drums                1
    3   Piano               0.65

Would someone be able to help or give me some step by step instructions?
Thank you in advance!

Body:
Pseudo-code on how to do column calculations from multiple CSV files and save the results to a new file using pandas in python is

import pandas as pd
df1 = pd.read_csv('First.csv')
df2 = pd.read_csv('Second.csv')
output_df = pd.DataFrame(columns = ["col1", "col2"])
output_df['result'] = df1['col2'] -df2['col2'] # some column calculation
df3.to_format("output.format")

Here is the actual code for the given example in the Question

#import libraries
import pandas as pd

#read files
df1 = pd.read_csv('First_week.csv')
df2 = pd.read_csv('Second_week.csv')

#Create new file and save results
column_names = ["id", "name"]
df3 = pd.DataFrame(columns = column_names)
df3[['id', 'name']] = df1[['id', 'name']]
df3['%difference_week1vsweek2'] = (df1['total_orderCount']-df2['total_orderCount'])/df2['total_orderCount']*100
print(df3)

df3.to_csv("output.csv")

Hope it helps.


问:
sum values with case insensitive join not grouping correctly
I have two tables I want to join in a case insensitive way. Thanks to other topics on SO this is working using lower(). However, the result is not grouped by the lower case values but still appears to be case sensitive. How do I adjust the query so that the grouping is case insensitive?

Example data:
Table 1 (only using 1 column right now of this table, there is more metadata though ;):

```<code>keyword
TEST
ABC
ASF
QWERTY
</code>```

Table 2:

```<code>Date - term - value
2020-01-01 - test - 3
2020-01-01 - Test - 2
2020-01-03 - TEST - 4
2020-01-01 - abc - 6
2020-01-02 - ABC - 7
2020-01-02 - abc - 3
</code>```

Desired output:

```<code>keyword - sum(value)
test - 9
abc - 16
</code>```

Current output:

```<code>keyword - sum(value)
test - 3
test - 2
test - 4
abc - 9
abc - 7
</code>```

Query I'm using:

```<code>select distinct lower(keyword), value
FROM Table1 t1
join (select lower(term) term, sum(value) value from Table2 group by term) t2 on lower(t1.keyword) = lower(t2.term)
GROUP BY t2.term, t1.keyword, t2.value
</code>```

It seems all the output needs is (another) group by, but whether I group or not it doesn't change the result. What am I missing here?

答:
Use lower() in GROUP BY too, if you want to group by the lowered value. Also you query can be simplified. There's no need for the derived table or DISTINCT.

```<code>SELECT lower(t1.keyword),
       sum(t2.value) value
       FROM table1 t1
            INNER JOIN table2 t2
                       ON lower(t1.keyword) = lower(t2.term)
       GROUP BY lower(t1.keyword);
</code>```

Body:
I have two tables I want to join in a case insensitive way. Thanks to other topics on SO this is working using lower(). However, the result is not grouped by the lower case values but still appears to be case sensitive. How do I adjust the query so that the grouping is case insensitive?

Example data:
Table 1 (only using 1 column right now of this table, there is more metadata though ;):

keyword
TEST
ABC
ASF
QWERTY

Table 2:

Date - term - value
2020-01-01 - test - 3
2020-01-01 - Test - 2
2020-01-03 - TEST - 4
2020-01-01 - abc - 6
2020-01-02 - ABC - 7
2020-01-02 - abc - 3

Desired output:

keyword - sum(value)
test - 9
abc - 16

Current output:

keyword - sum(value)
test - 3
test - 2
test - 4
abc - 9
abc - 7

Query I'm using:

select distinct lower(keyword), value
FROM Table1 t1
join (select lower(term) term, sum(value) value from Table2 group by term) t2 on lower(t1.keyword) = lower(t2.term)
GROUP BY t2.term, t1.keyword, t2.value

It seems all the output needs is (another) group by, but whether I group or not it doesn't change the result. What am I missing here?

Body:
Use lower() in GROUP BY too, if you want to group by the lowered value. Also you query can be simplified. There's no need for the derived table or DISTINCT.

SELECT lower(t1.keyword),
       sum(t2.value) value
       FROM table1 t1
            INNER JOIN table2 t2
                       ON lower(t1.keyword) = lower(t2.term)
       GROUP BY lower(t1.keyword);


问:
Spring boot project with Gradle does not runs spring
i'm working with Ubuntu, IntelliJ and Gradle 4.8.1

Onece the project created, if i try to debug it, the Gradle Daemon starts, build the projet ends up without run the spring boot

my Gradle properties ARE:

```<code>distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.8.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
</code>```

and the console log is:

```<code>8:32:06: Executing task...

Starting Gradle Daemon...
Connected to the target VM, address: '127.0.0.1:39247', transport: 'socket'
Gradle Daemon started in 5 s 356 ms

> Task :help

Welcome to Gradle 4.8.1.

To run a build, run gradle <task> ...

To see a list of available tasks, run gradle tasks

To see a list of command-line options, run gradle --help

To see more detail about a task, run gradle help --task <task>

For troubleshooting, visit https://help.gradle.org

BUILD SUCCESSFUL in 17s
1 actionable task: 1 executed
8:32:23: Task execution finished.
Disconnected from the target VM, address: '127.0.0.1:39247', transport: 'socket'
</code>```

and it is how my build.gradle looks like:

```<code>plugins {
    id 'org.springframework.boot' version '2.2.0.RELEASE'
    id 'io.spring.dependency-management' version '1.0.8.RELEASE'
    id 'java'
}

group = 'com.ITAcademy'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compileOnly 'org.projectlombok:lombok'
    runtimeOnly 'mysql:mysql-connector-java'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation('org.springframework.boot:spring-boot-starter-test')/* {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine' //ojo que en 2.1.9 esto no sale
    }
}

test {
    useJUnitPlatform()*/
}
</code>```

thanks

答:
Given that the Gradle output indicates that the :help task was run, that is the help task on the root project, the issue is most likely that you did not specify which task to run.

You can add the task to run to the command line or the IntelliJ configuration. For a Spring boot project, it is most likely something like bootRun.

You can define the default task in your project

And please, do not use clean in Gradle, you will slow your build for no good reasons as incremental builds is at the core of the Gradle features.

Body:
i'm working with Ubuntu, IntelliJ and Gradle 4.8.1

Onece the project created, if i try to debug it, the Gradle Daemon starts, build the projet ends up without run the spring boot

my Gradle properties ARE:

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.8.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

and the console log is:

8:32:06: Executing task...

Starting Gradle Daemon...
Connected to the target VM, address: '127.0.0.1:39247', transport: 'socket'
Gradle Daemon started in 5 s 356 ms

> Task :help

Welcome to Gradle 4.8.1.

To run a build, run gradle <task> ...

To see a list of available tasks, run gradle tasks

To see a list of command-line options, run gradle --help

To see more detail about a task, run gradle help --task <task>

For troubleshooting, visit https://help.gradle.org

BUILD SUCCESSFUL in 17s
1 actionable task: 1 executed
8:32:23: Task execution finished.
Disconnected from the target VM, address: '127.0.0.1:39247', transport: 'socket'

and it is how my build.gradle looks like:

plugins {
    id 'org.springframework.boot' version '2.2.0.RELEASE'
    id 'io.spring.dependency-management' version '1.0.8.RELEASE'
    id 'java'
}

group = 'com.ITAcademy'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compileOnly 'org.projectlombok:lombok'
    runtimeOnly 'mysql:mysql-connector-java'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation('org.springframework.boot:spring-boot-starter-test')/* {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine' //ojo que en 2.1.9 esto no sale
    }
}

test {
    useJUnitPlatform()*/
}

thanks


问:
Pentaho Text File Input Stuck
I got a TextFile that has Data parsed in a certain Format per line.

Its one of many and this one is quite small with only 34504 lines. Size is 274KB.
The same problem happens with every each of them.

I used the Text File Input Step in  and put ${line.seperator} as Seperator (Didn't actually found it in the Variable List but I found it in other answers for line breaks). Get Fields got me Field_00 and the Preview showed me all Data in each row as I wanted.

Now if I want to execute the Transformation it gets stuck in that Step and doesn't finish ever.
I put a Write to Log File Step after it that never gets reached and even alone the Step never finishes.
Even changing the File from "filename.ges" to ".txt" or ".csv" doesn't change the outcome.

If I Stop the Transformation it gets put into Infinite Halting condition and I need to restart the PDI.

I also upped the Java MaxPermSize in the spoon.bat because I got a Null Pointer Exception the first Time:

```<code>if "%PENTAHO_DI_JAVA_OPTIONS%"=="" set PENTAHO_DI_JAVA_OPTIONS="-Xms1024m" "-Xmx2048m" "-XX:MaxPermSize=8000m"
</code>```

PDI Version 8.3.0.0-371

Does someone have ideas how I can resolve this?

Content of the Step and the Preview Rows:

答:
You are configuring the field separator with the value of line separator. It's probably trying to construct one string with 34504 lines worth of characters.

If you want to read lines into a single field each, use the Fixed width filetype (top item in the configuration) and define 1 field with length 9999999999 or whatever fits.

Title: Pentaho Text File Input Stuck

Body:
I got a TextFile that has Data parsed in a certain Format per line.

Its one of many and this one is quite small with only 34504 lines. Size is 274KB.
The same problem happens with every each of them.

I used the Text File Input Step in  and put ${line.seperator} as Seperator (Didn't actually found it in the Variable List but I found it in other answers for line breaks). Get Fields got me Field_00 and the Preview showed me all Data in each row as I wanted.

Now if I want to execute the Transformation it gets stuck in that Step and doesn't finish ever.
I put a Write to Log File Step after it that never gets reached and even alone the Step never finishes.
Even changing the File from "filename.ges" to ".txt" or ".csv" doesn't change the outcome.

If I Stop the Transformation it gets put into Infinite Halting condition and I need to restart the PDI.

I also upped the Java MaxPermSize in the spoon.bat because I got a Null Pointer Exception the first Time:

if "%PENTAHO_DI_JAVA_OPTIONS%"=="" set PENTAHO_DI_JAVA_OPTIONS="-Xms1024m" "-Xmx2048m" "-XX:MaxPermSize=8000m"

PDI Version 8.3.0.0-371

Does someone have ideas how I can resolve this?

Content of the Step and the Preview Rows:


问:
How to get the value of a jquery slider to follow the handle, but not all the way?
I have a jQuery slider that is supposed to be placed in a narrow column on a page. The idea is that the value should follow the handle in a tooltip like fashion underneath the slider. I've gotten that to work pretty good by using the pageX attribute of the "event object" in the jquery slider slide event.

```<code>$(element).css("left", event.pageX - ($(element).width() / 2)).text(ui.value);
</code>```

But the problem is that due to the fact that the column in quite narrow so when I drag the slider to max the displayed value will be placed outside the column. Or a part of it will anyway.

The solution I've come up with is either make the slider shorter. But my designer will probably complain. The other solution is to make sure that the value I'm displaying have a narrower field of movement than the slider. But I'm not sure how to accomplish this.

Any suggestions on how I can get my value to neatly follow the handle. But in a way that it won't "fall out"?

EDIT:
Here is a jsFiddle that explains how my situation looks today. The value that follows along on the bottom ends up outside the width of the column. That I've represented with a blue box.

http://jsfiddle.net/nuPYa/2/

答:
First cache your $ object.

$element = $(element);

Then, instead of using the event.pageX attribute, use $element.position().left. Remember this is relative to the parent relative element. So you may want to use $element.offset().left

Body:
I have a jQuery slider that is supposed to be placed in a narrow column on a page. The idea is that the value should follow the handle in a tooltip like fashion underneath the slider. I've gotten that to work pretty good by using the pageX attribute of the "event object" in the jquery slider slide event.

$(element).css("left", event.pageX - ($(element).width() / 2)).text(ui.value);

But the problem is that due to the fact that the column in quite narrow so when I drag the slider to max the displayed value will be placed outside the column. Or a part of it will anyway.

The solution I've come up with is either make the slider shorter. But my designer will probably complain. The other solution is to make sure that the value I'm displaying have a narrower field of movement than the slider. But I'm not sure how to accomplish this.

Any suggestions on how I can get my value to neatly follow the handle. But in a way that it won't "fall out"?

EDIT:
Here is a jsFiddle that explains how my situation looks today. The value that follows along on the bottom ends up outside the width of the column. That I've represented with a blue box.

http://jsfiddle.net/nuPYa/2/