问:
Issue in converting received ajax data
Ajax is used to retrieve data from server.

Data is displayed successfully on alert as

```<code>data: {"status": "Active","broadcastmsg": "msg"}
</code>```

But in html i.e.

 it is displayed as undefined.

Looks like a minor issue , though I have been trying to solve this since last 24 hours and nothing seems to be working. Please suggest what's going wrong.

Client.php

```<code><!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<body>
<script>
    function myFunction(val) {

            $.post("test.php",
            {
              d_id: 1,
              date: val
            },
            function(hstatus){
                alert(hstatus);
                myJSON = JSON.stringify(hstatus);
                localStorage.setItem("testJSON", myJSON);

                //Retrieving data:
                text = localStorage.getItem("testJSON");
                obj = JSON.parse(text);
                document.getElementById("demo").innerHTML = obj.status;
            });
        }

    </script>
        <p id="demo"></p>
        <div id="future_date" style="display:block;" class="col-xs-12">
            <input type="date" name="txt" value="" onchange="myFunction(this.value)">
        </div>

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

EDIT

if we pass hstatus = {"status": "Active","broadcastmsg": "msg"} manually it's showing result.

Thus issue is in converting from

data: {"status": "Active","broadcastmsg": "msg"}

to

{"status": "Active","broadcastmsg": "msg"}

答:
You could try this:

document.getElementById("demo").innerHTML = obj.data.status;

Title: Issue in converting received ajax data

Body:
Ajax is used to retrieve data from server.

Data is displayed successfully on alert as

data: {"status": "Active","broadcastmsg": "msg"}

But in html i.e.

 it is displayed as undefined.

Looks like a minor issue , though I have been trying to solve this since last 24 hours and nothing seems to be working. Please suggest what's going wrong.

Client.php

<!DOCTYPE html>

            <input type="date" name="txt" value="" onchange="myFunction(this.value)">

EDIT

if we pass hstatus = {"status": "Active","broadcastmsg": "msg"} manually it's showing result.

Thus issue is in converting from

data: {"status": "Active","broadcastmsg": "msg"}

to

{"status": "Active","broadcastmsg": "msg"}


来源: stackexchange

问:
How to change JSON array to another format
Array has objects. Example is below;

```<code>  [{
    "Id": 1,
    "ParentId": -1,
    "Name": "Mobilya",
    "Slug": "",
    "Content": "",
    "Icon": "",
    "Code": "",
    "Order": 1,
    "IsShowing": true
  },
  {
    "Id": 2,
    "ParentId": -1,
    "Name": "Televizyon",
    "Slug": "",
    "Content": "",
    "Icon": "",
    "Code": "",
    "Order": 2,
    "IsShowing": true
  },
  {
    "Id": 16,
    "ParentId": 1,
    "Name": "Köşe Takımları",
    "Slug": "",
    "Content": "",
    "Icon": "",
    "Code": "",
    "Order": 5,
    "IsShowing": true
  }]
</code>```

I want to change it to

```<code>  [{
    "id": 1,
    "label": "Mobilya",
    "clickableId": "ndMainCategory",
    "icon": "",
    "items": [{
              "id": 16,
              "label": "Köşe Takımları"
              }]
   },
   {
    "id": 2,
    "label": "Mobilya",
    "clickableId": "ndMainCategory",
    "icon": ""
   }]
</code>```

Here if ParentId is -1 it means it is main category.clickableId":"ndMainCategory" this is static for every main category.
    First array comes from api and I have to change it to another one but I couldn't do it . How can I do it.

Thanks

in advance;

答:
I think this is what you're looking for

console.log(changeList([{"Id": 1,"ParentId": -1,"Name": "Mobilya","Slug": "","Content": "","Icon": "","Code": "","Order": 1,"IsShowing": true},{"Id": 2,"ParentId": -1,"Name": "Televizyon","Slug": "","Content": "","Icon": "","Code": "","Order": 2,"IsShowing": true},{"Id": 16,"ParentId": 1,"Name": "Köşe Takımları","Slug": "","Content": "","Icon": "","Code": "","Order": 5,"IsShowing": true}]));

/**
 * @param {string|Array<object>} input
 * @returns {string|Array<object>}
 */
function changeList(input) {
  // Below lines check if input is in string or array form
  var isList = input instanceof Array;
  var list = isList ? input : JSON.parse(String(input));

  // The list that stores all the items
  var result = {};

  // Returns an empty JSON list if input is invalid
  if (!(list instanceof Array)) return "[]";

  // Loop for all the items in the list
  for (var index = 0; index < list.length; index++) {
    var item = list[index]; // the item
    var id = item["Id"]; // item id
    var parentId = item["ParentId"]; // item parent id

    // if the parent Id is not -1 and there is an item in the list with that id
    if (parentId !== -1 && result.hasOwnProperty(parentId)) {

      var parent = result[parentId]; // get the parent
      // get parent's item or if it doesn't have any instantiate a new array
      var items = parent["items"] || [];
      // add the item to the list
      items.push({
        "id": id,
        "label": item["Name"]
      });
      // add the array to the parent
      parent["items"] = items;

    } else if(!result.hasOwnProperty(id)){

      // if it doesn't have a parent and it doesn't already exist in the list, create it and add it

      result[id] = {
        "id": id,
        "label": item["Name"],
        "clickableId": "ndMainCategory",
        "icon": item["Icon"]
      };
    }
  }
  // Finally convert the object into a list and return it in the form it was entered
  var resultList = Object.values(result);
  return isList ? resultList : JSON.stringify(resultList);
}```

ContentLicense: CC BY-SA 3.0

Body:
Array has objects. Example is below;

  [{
    "Id": 1,
    "ParentId": -1,
    "Name": "Mobilya",
    "Slug": "",
    "Content": "",
    "Icon": "",
    "Code": "",
    "Order": 1,
    "IsShowing": true
  },
  {
    "Id": 2,
    "ParentId": -1,
    "Name": "Televizyon",
    "Slug": "",
    "Content": "",
    "Icon": "",
    "Code": "",
    "Order": 2,
    "IsShowing": true
  },
  {
    "Id": 16,
    "ParentId": 1,
    "Name": "Köşe Takımları",
    "Slug": "",
    "Content": "",
    "Icon": "",
    "Code": "",
    "Order": 5,
    "IsShowing": true
  }]

I want to change it to

  [{
    "id": 1,
    "label": "Mobilya",
    "clickableId": "ndMainCategory",
    "icon": "",
    "items": [{
              "id": 16,
              "label": "Köşe Takımları"
              }]
   },
   {
    "id": 2,
    "label": "Mobilya",
    "clickableId": "ndMainCategory",
    "icon": ""
   }]

Here if ParentId is -1 it means it is main category.clickableId":"ndMainCategory" this is static for every main category.
    First array comes from api and I have to change it to another one but I couldn't do it . How can I do it.

Thanks

in advance;


问:
How do I use enums in TSQL without hard coding magic number all over my SQL scripts/procs?
We have enums in our C# code:

```<code>public enum JobStatus
{
  Ready = 0,
  Running = 1,
  Cancelling = 2,
}
</code>```

These values are also stored in database fields, and we have lots of TSQL (mostly stored procs, as well as some batches and SSIS) that also processes the data:

```<code>SELECT TOP 1 @JobSID = JobSID
FROM Job
WHERE Status = 0 /* JobStatus.Ready */
ORDER BY SubmitDate ASC

CREATE TABLE ImportCrossEffect(
    /* lots deleted */
    Source tinyint
      DEFAULT 1 NOT NULL -- 0: Unknown (default), 1:Imported, 2:Keyed
)
</code>```

How do I avoid hard coding the “magic numbers” in the TSQL?

How do I remove the risk of the enumerations not matching on the C# and TSQL sides?

(I have included the C# tag, as I would like solution that “single sourced”  the definitions of the enums on both the C# and TSQL sides)

Updates:

We don't have tables in the database with the Enum names in them, the values are just stored in tiny int columns.

I was hoping for something like a SQL pre-processor that would "expand" all the enum to there "magic value".

答:
Perhaps you could implement managed code on the SQL server instead of using normal TSQL?  Not 100% sure if this would work, but it might be an option to explore.

Possible Solution here...

ContentLicense: CC BY-SA 2.5

Body:
We have enums in our C# code:

public enum JobStatus
{
  Ready = 0,
  Running = 1,
  Cancelling = 2,
}

These values are also stored in database fields, and we have lots of TSQL (mostly stored procs, as well as some batches and SSIS) that also processes the data:

SELECT TOP 1 @JobSID = JobSID
FROM Job
WHERE Status = 0 /* JobStatus.Ready */
ORDER BY SubmitDate ASC

CREATE TABLE ImportCrossEffect(
    /* lots deleted */
    Source tinyint
      DEFAULT 1 NOT NULL -- 0: Unknown (default), 1:Imported, 2:Keyed
)

How do I avoid hard coding the “magic numbers” in the TSQL?

How do I remove the risk of the enumerations not matching on the C# and TSQL sides?

(I have included the C# tag, as I would like solution that “single sourced”  the definitions of the enums on both the C# and TSQL sides)

Updates:

We don't have tables in the database with the Enum names in them, the values are just stored in tiny int columns.

I was hoping for something like a SQL pre-processor that would "expand" all the enum to there "magic value".


问:
three.js memory management shader material
I'm trying to create textual labels. I need to use shader material to better control the label during rendering.

I've noticed that the memory keeps increasing even though I clean up old labels.

I've created a jsfiddle example that is not unlike: https://threejs.org/examples/#webgl_test_memory

The following code uses a canvas object to generate a texture, which contains the text to be depicted as a label:

Please be careful, these computations are heavy and make the tab quite unresponsive.

var container;

var camera, scene, renderer;

var labels;

var canvas;

init();
animate();

function init() {

  container = document.createElement( 'div' );
  document.body.appendChild( container );

  camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 10000 );
  camera.position.z = 200;

  scene = new THREE.Scene();

  renderer = new THREE.WebGLRenderer();
  renderer.setPixelRatio( window.devicePixelRatio );
  renderer.setSize( window.innerWidth, window.innerHeight );
  container.appendChild( renderer.domElement );

  labels = new THREE.Object3D();

  canvas = document.createElement('canvas');
  var context = canvas.getContext('2d');

  // get text metrics
  var fontface = 'Arial';
  var fontSize = 60;
  context.font = fontSize + "px " + fontface;

  var width = context.measureText(text).width;

  // add text
  var text = 'abcdef';
  canvas.width = width;
  canvas.height = fontSize*1.3;
  context.textAlign = "center";
  context.font = fontSize + "px " + fontface;
  context.fillStyle = "white";
  context.fillText(text, canvas.width / 2, canvas.height / 2);
}

function createLabels() {
  for(var i = 0; i < 10000 ; i++) {
    createTextMesh();
  }

  scene.add( labels );
}

function createTextMesh() {
  // canvas contents will be used for a texture
  var texture = new THREE.Texture(canvas);
  texture.needsUpdate = true;

  var uniforms = {
    text: {
      type: 't',
      value: texture
    }
  };

  var material = new THREE.ShaderMaterial( {
    uniforms: uniforms,
    vertexShader: document.getElementById( 'vertex-shader' ).textContent,
    fragmentShader: document.getElementById( 'fragment-shader' ).textContent
  } );

  var geometry = new THREE.PlaneBufferGeometry(15, 15);

  var label = new THREE.Mesh( geometry, material );

  labels.add(label);
}

function clearLabels() {
  for(var i = 0; i < labels.children.length; i++) {
    var label = labels.children[i];

    if(label.material.uniforms) {
      label.material.uniforms.text.value.dispose();
    }
    label.material.dispose();
    label.geometry.dispose();

    labels.remove(label);
  }

  scene.remove( labels );
}

function animate() {
  requestAnimationFrame( animate );
  render();
}

function render() {
  // build GL objects
  createLabels();

  renderer.render( scene, camera );

  // clean up
  clearLabels();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin:0;
}</code>```

<canvas></canvas>```

You can use's chromes dev tools to evaluate the perceptual memory utilisation increase.

I'd recommend using something like Window's own task manager to see the memory increase.

You can decrease the label creation speed, although this will naturally mean that it will take longer for the tab do run out of memory.

Am I doing the resource clean-up wrongly?

Cheers

答:
Hi try out following code
as I have added time gap in animate function which calls render function.

there is one variable fps currently 24, you can change it.

<!DOCTYPE html>

 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>three.js - shader material memory leak</title>
  <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

   <canvas width="1920" height="974" style="width: 1920px; height: 974px;"></canvas>

```

Body:
I'm trying to create textual labels. I need to use shader material to better control the label during rendering.

I've noticed that the memory keeps increasing even though I clean up old labels.

I've created a jsfiddle example that is not unlike: https://threejs.org/examples/#webgl_test_memory

The following code uses a canvas object to generate a texture, which contains the text to be depicted as a label:

Please be careful, these computations are heavy and make the tab quite unresponsive.

var container;

var camera, scene, renderer;

var labels;

var canvas;

init();
animate();

function init() {

  container = document.createElement( 'div' );
  document.body.appendChild( container );

  camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 10000 );
  camera.position.z = 200;

  scene = new THREE.Scene();

  renderer = new THREE.WebGLRenderer();
  renderer.setPixelRatio( window.devicePixelRatio );
  renderer.setSize( window.innerWidth, window.innerHeight );
  container.appendChild( renderer.domElement );

  labels = new THREE.Object3D();

  canvas = document.createElement('canvas');
  var context = canvas.getContext('2d');

  // get text metrics
  var fontface = 'Arial';
  var fontSize = 60;
  context.font = fontSize + "px " + fontface;

  var width = context.measureText(text).width;

  // add text
  var text = 'abcdef';
  canvas.width = width;
  canvas.height = fontSize*1.3;
  context.textAlign = "center";
  context.font = fontSize + "px " + fontface;
  context.fillStyle = "white";
  context.fillText(text, canvas.width / 2, canvas.height / 2);
}

function createLabels() {
  for(var i = 0; i < 10000 ; i++) {
    createTextMesh();
  }

  scene.add( labels );
}

function createTextMesh() {
  // canvas contents will be used for a texture
  var texture = new THREE.Texture(canvas);
  texture.needsUpdate = true;

  var uniforms = {
    text: {
      type: 't',
      value: texture
    }
  };

  var material = new THREE.ShaderMaterial( {
    uniforms: uniforms,
    vertexShader: document.getElementById( 'vertex-shader' ).textContent,
    fragmentShader: document.getElementById( 'fragment-shader' ).textContent
  } );

  var geometry = new THREE.PlaneBufferGeometry(15, 15);

  var label = new THREE.Mesh( geometry, material );

  labels.add(label);
}

function clearLabels() {
  for(var i = 0; i < labels.children.length; i++) {
    var label = labels.children[i];

    if(label.material.uniforms) {
      label.material.uniforms.text.value.dispose();
    }
    label.material.dispose();
    label.geometry.dispose();

    labels.remove(label);
  }

  scene.remove( labels );
}

function animate() {
  requestAnimationFrame( animate );
  render();
}

function render() {
  // build GL objects
  createLabels();

  renderer.render( scene, camera );

  // clean up
  clearLabels();
}

body {
  margin:0;
}

<canvas></canvas>

You can use's chromes dev tools to evaluate the perceptual memory utilisation increase.

I'd recommend using something like Window's own task manager to see the memory increase.

You can decrease the label creation speed, although this will naturally mean that it will take longer for the tab do run out of memory.

Am I doing the resource clean-up wrongly?

Cheers

Body:
Hi try out following code
as I have added time gap in animate function which calls render function.

there is one variable fps currently 24, you can change it.

<!DOCTYPE html>
<html lang="en">
 <head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>three.js - shader material memory leak</title>
  <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  <style>
   body {
    background:#fff;
    padding:0;
    margin:0;
    overflow:hidden;
   }
  </style>
 </head>
 <body>
  <script src="https://threejs.org/build/three.js"></script>
  <script id="fragment-shader" type="x-shader/x-fragment">
   uniform sampler2D text;

   varying vec2 vUv;

   void main() {
    vec4 finalColor = texture2D(text, vUv);
    gl_FragColor = finalColor;
   }
  </script>
  <script id="vertex-shader" type="x-shader/x-fragment">
   varying vec2 vUv;

   void main() {
    vUv = uv;
    vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
    gl_Position = projectionMatrix * mvPosition;
   }
  </script>
  <script>
   var container,
                camera, scene, renderer,
                labels,
                canvas,
                lastTime, fps = 24;

   init();
   animate();

   function init() {

    container = document.createElement( 'div' );
    document.body.appendChild( container );

    camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 10000 );
    camera.position.z = 200;

    scene = new THREE.Scene();

    renderer = new THREE.WebGLRenderer();
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth, window.innerHeight );
    container.appendChild( renderer.domElement );

    labels = new THREE.Object3D();

    canvas = document.createElement('canvas');
    var context = canvas.getContext('2d');

    // get text metrics
    var fontface = 'Arial';
    var fontSize = 60;
    context.font = fontSize + "px " + fontface;

    var width = context.measureText(text).width;

    // add text
    var text = 'abcdef';
    canvas.width = width;
    canvas.height = fontSize*1.3;
    context.textAlign = "center";
    context.font = fontSize + "px " + fontface;
    context.fillStyle = "white";
    context.fillText(text, canvas.width / 2, canvas.height / 2);
   }

   function createLabels() {
    for(var i = 0; i < 10000 ; i++) {
     createTextMesh();
    }

    scene.add( labels );
   }

   function createTextMesh() {
    // canvas contents will be used for a texture
    var texture = new THREE.Texture(canvas);
    texture.needsUpdate = true;

    var uniforms = {
     text: {
      type: 't',
      value: texture
     }
    };

    var material = new THREE.ShaderMaterial( {
     uniforms: uniforms,
     vertexShader: document.getElementById( 'vertex-shader' ).textContent,
     fragmentShader: document.getElementById( 'fragment-shader' ).textContent
    } );

    var geometry = new THREE.PlaneBufferGeometry(15, 15);

    var label = new THREE.Mesh( geometry, material );

    labels.add(label);
   }

   function clearLabels() {
    for(var i = 0; i < labels.children.length; i++) {
     var label = labels.children[i];

     if(label.material.uniforms) {
      label.material.uniforms.text.value.dispose();
     }
     label.material.dispose();
     label.geometry.dispose();

     labels.remove(label);
    }

    scene.remove( labels );
   }
   // Add time gap render will call with 24 fps. or you can slow down speed to check.
   function animate() {
               var curTime = new Date();
                           if(lastTime === undefined || (Math.round(curTime - lastTime)/1000) >= fps)
                           {
                       render();
                                   lastTime = curTime;
                           }
                           requestAnimationFrame( animate );
   }

   function render() {
    // build GL objects
    createLabels();

    renderer.render( scene, camera );

    // clean up
    clearLabels();
   }

  </script>
  <div>
   <canvas width="1920" height="974" style="width: 1920px; height: 974px;"></canvas>
  </div>
 </body>
</html>


问:
Curious about how to specify the number of core for MPI in order to get the fastest scientific computation
I have been running several scientific program package in conjunction with MPI by using the following command

```<code>nohup mpirun -np N -x OMP_NUM_THREADS=M program.exe < input > output &
</code>```

where the value of N and M depend on the physical CPU cores of my machine. For example, my machine has the specification like this

```<code>Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                24
On-line CPU(s) list:   0-23
Thread(s) per core:    2
Core(s) per socket:    6
Socket(s):             2
NUMA node(s):          2
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 45
Model name:            Intel(R) Xeon(R) CPU E5-2440 0 @ 2.40GHz
Stepping:              7
</code>```

In this case, I first tried setting with N = 24 and M = 1, so the calculation ran very slowly. Then I changed N and M to 12 and 2 respectively. So I found that the latter had obviously provided me the fastest computation.

I was wondering that why did I set N & M are 12 and 2 provide more performance higher than the first case ?

答:
there is no absolute rule on how to run MPI+OpenMP application.
the only advice is not to run an OpenMP process on more than one socket
(OpenMP was designed for SMP machines with flat memory access, but today, most systems are NUMA)

then just experiment.

some apps run best in flat MPI (e.g. one thread per task), while some other work best with one MPI task per socket, and all available cores for OpenMP.

last but not least, if you run more than one OpenMP thread per MPI task, make sure your MPI library bound the MPI tasks as expected.
for example, if you run with 12 OpenMP threads but MPI bind tasks to one core, you will end up doing time sharing and performance will be horrible.
or if you run with 12 OpenMP threads, and MPI task was bound to 12 cores, make sure the 12 cores are on the same socket (and not 6 on each socket)

Body:
I have been running several scientific program package in conjunction with MPI by using the following command

nohup mpirun -np N -x OMP_NUM_THREADS=M program.exe < input > output &

where the value of N and M depend on the physical CPU cores of my machine. For example, my machine has the specification like this

Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                24
On-line CPU(s) list:   0-23
Thread(s) per core:    2
Core(s) per socket:    6
Socket(s):             2
NUMA node(s):          2
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 45
Model name:            Intel(R) Xeon(R) CPU E5-2440 0 @ 2.40GHz
Stepping:              7

In this case, I first tried setting with N = 24 and M = 1, so the calculation ran very slowly. Then I changed N and M to 12 and 2 respectively. So I found that the latter had obviously provided me the fastest computation.

I was wondering that why did I set N & M are 12 and 2 provide more performance higher than the first case ?


问:
error: incompatible types: Object cannot be converted to MyClass
I want to use @Parcel annotation instead of implementing Parcelable.

So my class is :

```<code>@Parcel
public class UserSkillSpec {
    private final String TAG = getClass().getSimpleName();

    private Skill skill;
    private int endorses = 0;
    private boolean endorsed = false;
    private List<User> endorsers = new LinkedList<>();
    private int proficiency = 0;
    private boolean verified = false;

    @ParcelConstructor
    public UserSkillSpec(Skill skill, int proficiency) {
        this.skill = skill;
        this.proficiency = proficiency;
    }

}
</code>```

when I want to build project, this error will appears in MessageBox

```<code>Error:(62, 109) error: incompatible types: Object cannot be converted to User
</code>```

and User source code is :

```<code>@Parcel
@RealmClass
public class User extends RealmObject {
    @PrimaryKey
    private String id;

    private String firstName;
    private String lastName;
    private String name;
   //and something else

    public User() {
    }
}
</code>```

Apparently this issue related to List.

How can I fix my problem?

Thanks.

EDIT1:
I changed User class as below code:

```<code>@Parcel(implementations = {UserRealmProxy.class},
        value = Parcel.Serialization.BEAN,
        analyze = {User.class})
@RealmClass
public class User implements RealmModel {
    @PrimaryKey
    private String id;

    private String firstName;
    private String lastName;
    private String name;
    //somethings else

    public User() {
    }
}
</code>```

in automatically generated class UserSkillSpec$$Parcelable by Parceler library,the error happened in for section :

```<code>public static void write(UserSkillSpec userSkillSpec$$1, android.os.Parcel parcel$$1, int flags$$0, IdentityCollection identityMap$$0) {
        int identity$$0 = identityMap$$0 .getKey(userSkillSpec$$1);
        if (identity$$0 != -1) {
            parcel$$1 .writeInt(identity$$0);
        } else {
            parcel$$1 .writeInt(identityMap$$0 .put(userSkillSpec$$1));
            Skill$$Parcelable.write(InjectionUtil.getField(Skill.class, UserSkillSpec.class, userSkillSpec$$1, "skill"), parcel$$1, flags$$0, identityMap$$0);
            parcel$$1 .writeInt(InjectionUtil.getField(int.class, UserSkillSpec.class, userSkillSpec$$1, "proficiency"));
            if (InjectionUtil.getField(List.class, UserSkillSpec.class, userSkillSpec$$1, "endorsers") == null) {
                parcel$$1 .writeInt(-1);
            } else {
                parcel$$1 .writeInt(InjectionUtil.getField(List.class, UserSkillSpec.class, userSkillSpec$$1, "endorsers").size());
                for (User user$$0 : InjectionUtil.getField(List.class, UserSkillSpec.class, userSkillSpec$$1, "endorsers")) {
                    User$$Parcelable.write(user$$0, parcel$$1, flags$$0, identityMap$$0);
                }
            }
            parcel$$1 .writeInt((InjectionUtil.getField(boolean.class, UserSkillSpec.class, userSkillSpec$$1, "verified")? 1 : 0));
            parcel$$1 .writeInt(InjectionUtil.getField(int.class, UserSkillSpec.class, userSkillSpec$$1, "endorses"));
            parcel$$1 .writeString(InjectionUtil.getField(String.class, UserSkillSpec.class, userSkillSpec$$1, "TAG"));
            parcel$$1 .writeInt((InjectionUtil.getField(boolean.class, UserSkillSpec.class, userSkillSpec$$1, "endorsed")? 1 : 0));
        }
    }
</code>```

答:
Finally I could solve my problem,and decide to share it.

Tips:
 1. List must be as Generic.List<Item> not List

 2. use @ParcelPropertyConverter(ItemListParcelConverter.class) in declaration of List<Item>

so my code is like below now:

```<code>@Parcel(implementations = {UserRealmProxy.class},
        value = Parcel.Serialization.BEAN,
        analyze = {User.class})
public class User extends RealmObject {
    @PrimaryKey
    private String id;

    private String firstName;
    private String lastName;
    private String name;}
</code>```

and this one:

```<code>@Parcel
public class UserSkillSpec {
    private Skill skill;
    private int endorses = 0;
    private boolean endorsed = false;
    @ParcelPropertyConverter(ItemListParcelConverter.class)
    private List<User> endorsers = new LinkedList<>();
    private int proficiency = 0;
    private boolean verified = false;

    public UserSkillSpec() {
    }
}
</code>```

and this is parcelConvertor class:

```<code>public class ItemListParcelConverter<T> extends ArrayListParcelConverter<T> {
    @Override
    public void itemToParcel(T item, Parcel parcel) {
        parcel.writeParcelable(Parcels.wrap(item), 0);
    }

    @Override
    public T itemFromParcel(Parcel parcel) {
        return Parcels.unwrap(parcel.readParcelable(getClass().getClassLoader()));
    }
}
</code>```

Body:
I want to use @Parcel annotation instead of implementing Parcelable.

So my class is :

@Parcel
public class UserSkillSpec {
    private final String TAG = getClass().getSimpleName();

    private Skill skill;
    private int endorses = 0;
    private boolean endorsed = false;
    private List<User> endorsers = new LinkedList<>();
    private int proficiency = 0;
    private boolean verified = false;

    @ParcelConstructor
    public UserSkillSpec(Skill skill, int proficiency) {
        this.skill = skill;
        this.proficiency = proficiency;
    }

}

when I want to build project, this error will appears in MessageBox

Error:(62, 109) error: incompatible types: Object cannot be converted to User

and User source code is :

@Parcel
@RealmClass
public class User extends RealmObject {
    @PrimaryKey
    private String id;

    private String firstName;
    private String lastName;
    private String name;
   //and something else

    public User() {
    }
}

Apparently this issue related to List.

How can I fix my problem?

Thanks.

EDIT1:
I changed User class as below code:

@Parcel(implementations = {UserRealmProxy.class},
        value = Parcel.Serialization.BEAN,
        analyze = {User.class})
@RealmClass
public class User implements RealmModel {
    @PrimaryKey
    private String id;

    private String firstName;
    private String lastName;
    private String name;
    //somethings else

    public User() {
    }
}

in automatically generated class UserSkillSpec$$Parcelable by Parceler library,the error happened in for section :

public static void write(UserSkillSpec userSkillSpec$$1, android.os.Parcel parcel$$1, int flags$$0, IdentityCollection identityMap$$0) {
        int identity$$0 = identityMap$$0 .getKey(userSkillSpec$$1);
        if (identity$$0 != -1) {
            parcel$$1 .writeInt(identity$$0);
        } else {
            parcel$$1 .writeInt(identityMap$$0 .put(userSkillSpec$$1));
            Skill$$Parcelable.write(InjectionUtil.getField(Skill.class, UserSkillSpec.class, userSkillSpec$$1, "skill"), parcel$$1, flags$$0, identityMap$$0);
            parcel$$1 .writeInt(InjectionUtil.getField(int.class, UserSkillSpec.class, userSkillSpec$$1, "proficiency"));
            if (InjectionUtil.getField(List.class, UserSkillSpec.class, userSkillSpec$$1, "endorsers") == null) {
                parcel$$1 .writeInt(-1);
            } else {
                parcel$$1 .writeInt(InjectionUtil.getField(List.class, UserSkillSpec.class, userSkillSpec$$1, "endorsers").size());
                for (User user$$0 : InjectionUtil.getField(List.class, UserSkillSpec.class, userSkillSpec$$1, "endorsers")) {
                    User$$Parcelable.write(user$$0, parcel$$1, flags$$0, identityMap$$0);
                }
            }
            parcel$$1 .writeInt((InjectionUtil.getField(boolean.class, UserSkillSpec.class, userSkillSpec$$1, "verified")? 1 : 0));
            parcel$$1 .writeInt(InjectionUtil.getField(int.class, UserSkillSpec.class, userSkillSpec$$1, "endorses"));
            parcel$$1 .writeString(InjectionUtil.getField(String.class, UserSkillSpec.class, userSkillSpec$$1, "TAG"));
            parcel$$1 .writeInt((InjectionUtil.getField(boolean.class, UserSkillSpec.class, userSkillSpec$$1, "endorsed")? 1 : 0));
        }
    }

Body:
Finally I could solve my problem,and decide to share it.

Tips:
 1. List must be as Generic.List<Item> not List

 2. use @ParcelPropertyConverter(ItemListParcelConverter.class) in declaration of List<Item>

so my code is like below now:

@Parcel(implementations = {UserRealmProxy.class},
        value = Parcel.Serialization.BEAN,
        analyze = {User.class})
public class User extends RealmObject {
    @PrimaryKey
    private String id;

    private String firstName;
    private String lastName;
    private String name;}

and this one:

@Parcel
public class UserSkillSpec {
    private Skill skill;
    private int endorses = 0;
    private boolean endorsed = false;
    @ParcelPropertyConverter(ItemListParcelConverter.class)
    private List<User> endorsers = new LinkedList<>();
    private int proficiency = 0;
    private boolean verified = false;

    public UserSkillSpec() {
    }
}

and this is parcelConvertor class:

public class ItemListParcelConverter<T> extends ArrayListParcelConverter<T> {
    @Override
    public void itemToParcel(T item, Parcel parcel) {
        parcel.writeParcelable(Parcels.wrap(item), 0);
    }

    @Override
    public T itemFromParcel(Parcel parcel) {
        return Parcels.unwrap(parcel.readParcelable(getClass().getClassLoader()));
    }
}


问:
Re-rendering Vue component
I have something like this in my .vue template:

```<code><plasmid id='p1' plasmidheight="800" plasmidwidth="800" v-bind:sequencelength="sequenceLength">
</code>```

I use Vue.js to manipulate the sequencelength attribute and then add a piece of code that manipulates that to create an svg element.

Now when sequenceLength changes, Vue doesn't update the view because it is no longer the <plasmid> tag but an svg component.

I therefore need to re-render the component, my attempts to use $forceUpdate() have not worked.

答:
If <plasmid> is your Vue component, inside it you should have a method that draws your svg graphics, let's call it drawPlasmid(). Now, you have to trigger this method whenever sequenceLength is changed. You can do it either with an event handler:

```<code><template>
  <div @change-sequence-length=changeSequenceLength"></div>
</template>

<script>
  methods: {
    changeSequenceLength(e) {
      this.drawPlasmid(e.detail.sequenceLength)
    }
    drawPlasmid(sequenceLength) {
      // Render svg graphics
    }
  }
<script>
</code>```

or a watcher:

```<code>watch: {
  sequenceLength: function() {
    this.drawPlasmid(this.sequenceLength)
  }
}
</code>```

I hope this puts you on the right track.

Title: Re-rendering Vue component

Body:
I have something like this in my .vue template:

<plasmid id='p1' plasmidheight="800" plasmidwidth="800" v-bind:sequencelength="sequenceLength">

I use Vue.js to manipulate the sequencelength attribute and then add a piece of code that manipulates that to create an svg element.

Now when sequenceLength changes, Vue doesn't update the view because it is no longer the <plasmid> tag but an svg component.

I therefore need to re-render the component, my attempts to use $forceUpdate() have not worked.

Body:
If <plasmid> is your Vue component, inside it you should have a method that draws your svg graphics, let's call it drawPlasmid(). Now, you have to trigger this method whenever sequenceLength is changed. You can do it either with an event handler:

<template>
  <div @change-sequence-length=changeSequenceLength"></div>
</template>

<script>
  methods: {
    changeSequenceLength(e) {
      this.drawPlasmid(e.detail.sequenceLength)
    }
    drawPlasmid(sequenceLength) {
      // Render svg graphics
    }
  }
<script>

or a watcher:

watch: {
  sequenceLength: function() {
    this.drawPlasmid(this.sequenceLength)
  }
}

I hope this puts you on the right track.


答:
You need to access your status property via obj.data.status instead of obj.status

```<code> document.getElementById("demo").innerHTML = obj.data.status;
</code>```

Title: Issue in converting received ajax data

Body:
You need to access your status property via obj.data.status instead of obj.status

 document.getElementById("demo").innerHTML = obj.data.status;


问:
LOAD DATA INFILE within PHPmyadmin
I'm running the following command within PHPmyadmin:

```<code>LOAD DATA INFILE '/test3.csv' INTO TABLE temp_car FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 LINES (recloc,divdept)
</code>```

AND

```<code>LOAD DATA INFILE '/var/www/vhosts/domain.com/httpdocs/admin/server/test3.csv' INTO TABLE temp_car FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 LINES (recloc,divdept)
</code>```

i get this error:

```<code>#1045 - Access denied for user 'db_admin'@'%' (using password: YES)
</code>```

I've tried changing the permissions to the file to 777 and the containing folder to 777.

Any ideas? I'm having a terrible time getting a working test with LOAD DATA INFILE

答: "For security reasons, when reading text files located on the server, the files must either reside in the database directory or be readable by all. Also, to use LOAD DATA INFILE on server files, you must have the FILE privilege."</p>

Title: LOAD DATA INFILE within PHPmyadmin

Body:
I'm running the following command within PHPmyadmin:

LOAD DATA INFILE '/test3.csv' INTO TABLE temp_car FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 LINES (recloc,divdept)

AND

LOAD DATA INFILE '/var/www/vhosts/domain.com/httpdocs/admin/server/test3.csv' INTO TABLE temp_car FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 LINES (recloc,divdept)

i get this error:

#1045 - Access denied for user 'db_admin'@'%' (using password: YES)

I've tried changing the permissions to the file to 777 and the containing folder to 777.

Any ideas? I'm having a terrible time getting a working test with LOAD DATA INFILE


问:
Why variable not renders on page?
I have following thymeleaf snippet:

```<code>    ...
    <p>///////</p>
    ${userName}
    <p>///////</p>
    ...
</code>```

And I have followinf controller:

```<code>GetMapping(value = {"/main"})
    public String showPersonsPage(Model model) {
        // don't fill models here. All data got via web socket's subscription.
        model.addAttribute("userName", startupHouseKeeper.getUser().getUserName());
        return "main";
    }
</code>```

But on page I see:

What did I wrong?

答:
Output your variable using:</p>

```<code><p th:text="${userName}"></p>
</code>```

Title: Why variable not renders on page?

Body:
I have following thymeleaf snippet:

    ...

///////

    ${userName}

///////

    ...

And I have followinf controller:

GetMapping(value = {"/main"})
    public String showPersonsPage(Model model) {
        // don't fill models here. All data got via web socket's subscription.
        model.addAttribute("userName", startupHouseKeeper.getUser().getUserName());
        return "main";
    }

But on page I see:

What did I wrong?

Body:
Output your variable using:

<p th:text="${userName}"></p>


问:
copy/paste functionality in fabric.js
In currently I have added code for copy and paste object in fabric js.But while selecting group of objects its not working.
Is there any way to implement copy/paste functionality for group of objects on canvas with fabric.js framework?

here is my code for paste

```<code>pasteSelectedObjs: function() {
    cur_canvas = canvasObjArr[this.page];
    if (clipboard.length < 1) {
        return;
    }
    if (cur_canvas.getActiveObject()) {
        clipboard.set('active', true);
        cur_canvas.add(clipboard);
        cur_canvas.setActiveObject(clipboard);
    }
    clipboard = [];
}
</code>```

答:
Here I got the proper solution.

```<code>if (cur_canvas.getActiveGroup()) {
    cur_canvas.discardActiveGroup();
    clipboard.forEachObject(function(obj) {
        obj.set('active', true);
        cur_canvas.add(obj);
    });
    cur_canvas.setActiveGroup(clipboard).renderAll();
}
</code>```

Thank you all.

Title: copy/paste functionality in fabric.js

Body:
In currently I have added code for copy and paste object in fabric js.But while selecting group of objects its not working.
Is there any way to implement copy/paste functionality for group of objects on canvas with fabric.js framework?

here is my code for paste

pasteSelectedObjs: function() {
    cur_canvas = canvasObjArr[this.page];
    if (clipboard.length < 1) {
        return;
    }
    if (cur_canvas.getActiveObject()) {
        clipboard.set('active', true);
        cur_canvas.add(clipboard);
        cur_canvas.setActiveObject(clipboard);
    }
    clipboard = [];
}

Body:
Here I got the proper solution.

if (cur_canvas.getActiveGroup()) {
    cur_canvas.discardActiveGroup();
    clipboard.forEachObject(function(obj) {
        obj.set('active', true);
        cur_canvas.add(obj);
    });
    cur_canvas.setActiveGroup(clipboard).renderAll();
}

Thank you all.


问:
How to check time performances in a C++ program on Zedboard
I have implemented a C++ code on a Zedboard. It compiles and runs perfectly, but now i would like to check the performances in order to optimize some functions.
I have checked some threads here (Testing the performance of a C++ app) and here (Timer function to provide time in nano seconds using C++), but i don't really understand how to apply it mon code ...

To make things clear : I'm not good at C++, I have never really learned the language formally but only used it several times with specific libraries. I am not even the author of the code I'm using (given to me by the professors).

My goal here is to check the time spent on each functions and globally when I execute the program on the Zedboard. The code is on Linux image on an SD card, the board booting on this image. It is using the opencv library for anImage processing application. I'm using g++ 4.6.3 as a compiler.

Thanks in advance for your answer !

答:
You can create a simple timer class using the <chrono> header. Something like this:

```<code>class Timer
{
public:
    using clock = std::chrono::steady_clock;

    void clear() { start(); tse = tsb; }
    void start() { tsb = clock::now(); }
    void stop()  { tse = clock::now(); }

    auto nsecs() const
    {
        using namespace std::chrono;
        return duration_cast<nanoseconds>(tse - tsb).count();
    }

    double usecs() const { return double(nsecs()) / 1000.0; }
    double msecs() const { return double(nsecs()) / 1000000.0; }
    double  secs() const { return double(nsecs()) / 1000000000.0; }

    friend std::ostream& operator<<(std::ostream& o, Timer const& timer)
    {
        return o << timer.secs();
    }

private:
    clock::time_point tsb;
    clock::time_point tse;
};
</code>```

You can use it simply like this:

```<code>Timer timer;

timer.start();

// do some stuff
std::this_thread::sleep_for(std::chrono::milliseconds(600));

timer.stop();

std::cout << timer << " seconds" << '\n';
</code>```

EDIT: On POSIX systems you can use clock_gettime() if <chrono> is not available:

```<code>class Timer
{
public:
    void clear() { start(); tse = tsb; }
    void start() { clock_gettime(CLOCK_MONOTONIC, &tsb); }
    void stop() { clock_gettime(CLOCK_MONOTONIC, &tse); }

    long nsecs() const
    {
        long b = (tsb.tv_sec * 1000000000) + tsb.tv_nsec;
        long e = (tse.tv_sec * 1000000000) + tse.tv_nsec;
        return e - b;
    }

    double usecs() const { return double(nsecs()) / 1000.0; }
    double msecs() const { return double(nsecs()) / 1000000.0; }
    double  secs() const { return double(nsecs()) / 1000000000.0; }

    friend std::ostream& operator<<(std::ostream& o, Timer const& timer)
    {
        return o << timer.secs();
    }

private:
    timespec tsb;
    timespec tse;
};
</code>```

Body:
You can create a simple timer class using the <chrono> header. Something like this:

class Timer
{
public:
    using clock = std::chrono::steady_clock;

    void clear() { start(); tse = tsb; }
    void start() { tsb = clock::now(); }
    void stop()  { tse = clock::now(); }

    auto nsecs() const
    {
        using namespace std::chrono;
        return duration_cast<nanoseconds>(tse - tsb).count();
    }

    double usecs() const { return double(nsecs()) / 1000.0; }
    double msecs() const { return double(nsecs()) / 1000000.0; }
    double  secs() const { return double(nsecs()) / 1000000000.0; }

    friend std::ostream& operator<<(std::ostream& o, Timer const& timer)
    {
        return o << timer.secs();
    }

private:
    clock::time_point tsb;
    clock::time_point tse;
};

You can use it simply like this:

Timer timer;

timer.start();

// do some stuff
std::this_thread::sleep_for(std::chrono::milliseconds(600));

timer.stop();

std::cout << timer << " seconds" << '\n';

EDIT: On POSIX systems you can use clock_gettime() if <chrono> is not available:

class Timer
{
public:
    void clear() { start(); tse = tsb; }
    void start() { clock_gettime(CLOCK_MONOTONIC, &tsb); }
    void stop() { clock_gettime(CLOCK_MONOTONIC, &tse); }

    long nsecs() const
    {
        long b = (tsb.tv_sec * 1000000000) + tsb.tv_nsec;
        long e = (tse.tv_sec * 1000000000) + tse.tv_nsec;
        return e - b;
    }

    double usecs() const { return double(nsecs()) / 1000.0; }
    double msecs() const { return double(nsecs()) / 1000000.0; }
    double  secs() const { return double(nsecs()) / 1000000000.0; }

    friend std::ostream& operator<<(std::ostream& o, Timer const& timer)
    {
        return o << timer.secs();
    }

private:
    timespec tsb;
    timespec tse;
};

ContentLicense: CC BY-SA 4.0


问:
Awesome WM: some clients pop up floating and vertically and horizontally maximized
Some graphic clients such as firefox, thunderbird and sqlitebrowser pop up vertically and horizontally maximized automatically, and floating, without any specific rule in the rc.lua. Or at least I suppose they are so from the icons in the title bar, see screenshot. While others like thunar or blender work just fine.

This is annoying because I didn't find any way to remove this condition. I can make them non floating with mod + ctrl + space, but they are still maximized. Also, clients with such condition resize poorly, they are slightly wider than my main screen and step over to the next screen by a few pixels. I have to maximize them to make them fit the screen.

I did some research and couldn't find any answer to this problem.

Can this come from an obscure rule in the rc.lua? I didn't do much modification from the original example, and I believe this problem wasn't there before a recent awesome update.

I'm using awesome 4.1 on archlinux, with compton as compositing manager.

答:
I don't have a clear answer why it must be forced, but the solution of this forum that proposes to modify the default rule for clients by adding the four last lines works for me:</p>

```<code>{ rule = { },
  properties = { border_width = beautiful.border_width,
                 border_color = beautiful.border_normal,
                 focus = awful.client.focus.filter,
                 raise = true,
                 keys = clientkeys,
                 buttons = clientbuttons,
                 screen = awful.screen.preferred,
                 placement = awful.placement.no_overlap+awful.placement.no_offscreen,
                 maximized_vertical   = false,
                 maximized_horizontal = false,
                 floating = false,
                 maximized = false
 }
</code>```

Body:
I don't have a clear answer why it must be forced, but the solution of this forum that proposes to modify the default rule for clients by adding the four last lines works for me:

{ rule = { },
  properties = { border_width = beautiful.border_width,
                 border_color = beautiful.border_normal,
                 focus = awful.client.focus.filter,
                 raise = true,
                 keys = clientkeys,
                 buttons = clientbuttons,
                 screen = awful.screen.preferred,
                 placement = awful.placement.no_overlap+awful.placement.no_offscreen,
                 maximized_vertical   = false,
                 maximized_horizontal = false,
                 floating = false,
                 maximized = false
 }


问:
Retrieving the MethodInfo of of the correct overload of a generic method
I have this type that contains two overloads of a generic method. I like to retrieve one of the overloads (with the Func<T> parameter) using reflection. The problem however is that I can't find the correct parameter type to supply the Type.GetMethod(string, Type[]) method with.

Here is my class definition:

```<code>public class Foo
{
    public void Bar<T>(Func<T> f) { }
    public void Bar<T>(Action<T> a) { }
}
</code>```

And this is what I've come up with, unfortunately without succes:

```<code>[TestMethod]
public void Test1()
{
    Type parameterType = typeof(Func<>);

    var method = typeof(Foo).GetMethod("Bar", new Type[] { parameterType });

    Assert.IsNotNull(method); // Fails
}
</code>```

How can I get the MethodInfo of a generic method of which I know the parameters?

答:
You need to specify a concrete type using MethodInfo.MakeGenericMethod.

However, I should point out, that getting the right type to invoke MakeGenericMethod on is not easy when you have an overloaded generic method.

Here is an example:

```<code>var method = typeof(Foo)
                 .GetMethods()
                 .Where(x => x.Name == "Bar")
                 .Where(x => x.IsGenericMethod)
                 .Where(x => x.GetGenericArguments().Length == 1)
                 .Where(x => x.GetParameters().Length == 1)
                 .Where(x =>
                     x.GetParameters()[0].ParameterType ==
                     typeof(Action<>).MakeGenericType(x.GetGenericArguments()[0])
                 )
                 .Single();

 method = method.MakeGenericMethod(new Type[] { typeof(int) });

 Foo foo = new Foo();
 method.Invoke(foo, new Func<int>[] { () => return 42; });
</code>```

Body:
I have this type that contains two overloads of a generic method. I like to retrieve one of the overloads (with the Func<T> parameter) using reflection. The problem however is that I can't find the correct parameter type to supply the Type.GetMethod(string, Type[]) method with.

Here is my class definition:

public class Foo
{
    public void Bar<T>(Func<T> f) { }
    public void Bar<T>(Action<T> a) { }
}

And this is what I've come up with, unfortunately without succes:

[TestMethod]
public void Test1()
{
    Type parameterType = typeof(Func<>);

    var method = typeof(Foo).GetMethod("Bar", new Type[] { parameterType });

    Assert.IsNotNull(method); // Fails
}

How can I get the MethodInfo of a generic method of which I know the parameters?

Body:
You need to specify a concrete type using MethodInfo.MakeGenericMethod.

However, I should point out, that getting the right type to invoke MakeGenericMethod on is not easy when you have an overloaded generic method.

Here is an example:

var method = typeof(Foo)
                 .GetMethods()
                 .Where(x => x.Name == "Bar")
                 .Where(x => x.IsGenericMethod)
                 .Where(x => x.GetGenericArguments().Length == 1)
                 .Where(x => x.GetParameters().Length == 1)
                 .Where(x =>
                     x.GetParameters()[0].ParameterType ==
                     typeof(Action<>).MakeGenericType(x.GetGenericArguments()[0])
                 )
                 .Single();

 method = method.MakeGenericMethod(new Type[] { typeof(int) });

 Foo foo = new Foo();
 method.Invoke(foo, new Func<int>[] { () => return 42; });


问:
Don't understand this Invalid argument error

Traceback (most recent call last):
  File "C:\Users\한찬희\Desktop\졸업작품\indexer_test1.py", line 191, in
<module>
    with open('./searchJson2.json/') as data_file:
OSError: [Errno 22] Invalid argument: './searchJson2.json/
```

答:
Can you try this:</p>

```<code>dir_path = os.path.dirname(os.path.realpath(__file__))
with open('{0}/searchJson2.json'.format(dir_path),'r+') as data_file:
</code>```

Body:
Can you try this:

dir_path = os.path.dirname(os.path.realpath(__file__))
with open('{0}/searchJson2.json'.format(dir_path),'r+') as data_file:


问:
How to change tab bar item text color

How can I change the color of "More.." text in tabbar to match with its icon color.  (Right now Performance is selected in the tab bar)

I tried to set TitleTextAttributes.

```<code>[moreItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"HelveticaLTStd-Roman" size:10.0f], NSFontAttributeName,  [UIColor yellowColor],NSForegroundColorAttributeName , nil]
</code>```

But it the text color is always set to yellow. even when the item is selected. Like this

I am trying set to white when selected and when unselected it should match with icon color.
Thanks..
Any suggestions will be really helpful.

答:
This works correctly..</p>

```<code> [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                        [UIColor redColor], NSForegroundColorAttributeName,
                                                       nil] forState:UIControlStateSelected];

    [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                       [UIColor blackColor], NSForegroundColorAttributeName,
                                                       nil] forState:UIControlStateNormal];
</code>```

Title: How to change tab bar item text color

Body:
How can I change the color of "More.." text in tabbar to match with its icon color.  (Right now Performance is selected in the tab bar)

I tried to set TitleTextAttributes.

[moreItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"HelveticaLTStd-Roman" size:10.0f], NSFontAttributeName,  [UIColor yellowColor],NSForegroundColorAttributeName , nil]

But it the text color is always set to yellow. even when the item is selected. Like this

I am trying set to white when selected and when unselected it should match with icon color.
Thanks..
Any suggestions will be really helpful.

Body:
This works correctly..

 [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                        [UIColor redColor], NSForegroundColorAttributeName,
                                                       nil] forState:UIControlStateSelected];

    [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                       [UIColor blackColor], NSForegroundColorAttributeName,
                                                       nil] forState:UIControlStateNormal];


问:
Parameterized IN clause using multiple columns with hibernate SQL query
How to set parameters to a hibernate SQL query in case of multiple columns IN clause?

For ex, the SQL query should be generate as like below:

SELECT * FROM TABLE TA WHERE (TA.COLUMN1 , TA.COLUMN2) IN ((C1v, C2v), (C1v, C2v), .....);
```

<p>I see this can be achieved with Spring jdbcTemplate as mentioned here,  but i want this in Hibernate SQL Query.</p>

<p>I tried below scenarios but none of them works for me:</p>

<pre class="lang-java prettyprint-override"><code>String sql = "SELECT * FROM TABLE TA WHERE (TA.COLUMN1 , TA.COLUMN2) IN (:ids)";
// 1. List of BigDecimal array's
List<BigDecimal[]> ids = new ArrayList<>();
BigDecimal[] bd1 = {new BigDecimal(100119401), new BigDecimal(2)};
BigDecimal[] bd2 = {new BigDecimal(100119000), new BigDecimal(1)};
ids.add(bd1);
ids.add(bd2);

Query query = session.createSQLQuery(sql);
query.setParameterList("ids", ids);

// 2. List of Object arrays
List<Object []> ids = new ArrayList<>();
Object [] bd1 = {new BigDecimal(100119401), new BigDecimal(2)};
Object [] bd2 = {new BigDecimal(100119000), new BigDecimal(1)};
ids.add(bd1);
ids.add(bd2);

Query query = session.createSQLQuery(sql);
query.setParameterList("ids", ids);

// 3. List of inner lists with ids
List<BigDecimal> ob1 = new ArrayList<BigDecimal>();
ob1.add(new BigDecimal(100119401));ob1.add(new BigDecimal(2));
List<BigDecimal> ob2 = new ArrayList<BigDecimal>();
ob2.add(new BigDecimal(100119401));ob2.add(new BigDecimal(2));
List<List<BigDecimal>> ids = new ArrayList<List<BigDecimal>>();
ids.add(ob1);ids.add(ob2);

Query query = session.createSQLQuery(sql);
query.setParameterList("ids", ids);
</code>```

In all the cases am getting “ORA-00920: invalid relational operator” error.

Exception:

```<code>Caused by: java.sql.SQLSyntaxErrorException: ORA-00920: invalid relational operator

    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:450)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:399)
    at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:1017)
    at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:655)
    at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:249)
    at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:566)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:215)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:58)
    at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:776)
    at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:897)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1034)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3820)
    at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3867)
    at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1502)
    at org.apache.tomcat.dbcp.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
    at org.apache.tomcat.dbcp.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:82)
    ... 141 more
</code>```

答:
Something like that should work:

```<code>String sql = "SELECT * FROM TABLE TA WHERE CONCAT(TA.COLUMN1, '|', TA.COLUMN2) IN (:values)";
List<String> values = new ArrayList<>();
values.add("100119401|2");
values.add("100119000|1");

// ...

Query query = session.createSQLQuery(sql);
query.setParameterList("values", values);
</code>```

NB: make sure the separator used, here |, is not in your data

Body:
How to set parameters to a hibernate SQL query in case of multiple columns IN clause?

For ex, the SQL query should be generate as like below:

SELECT * FROM TABLE TA WHERE (TA.COLUMN1 , TA.COLUMN2) IN ((C1v, C2v), (C1v, C2v), .....);

I see this can be achieved with Spring jdbcTemplate as mentioned here,  but i want this in Hibernate SQL Query.

I tried below scenarios but none of them works for me:

String sql = "SELECT * FROM TABLE TA WHERE (TA.COLUMN1 , TA.COLUMN2) IN (:ids)";
// 1. List of BigDecimal array's
List<BigDecimal[]> ids = new ArrayList<>();
BigDecimal[] bd1 = {new BigDecimal(100119401), new BigDecimal(2)};
BigDecimal[] bd2 = {new BigDecimal(100119000), new BigDecimal(1)};
ids.add(bd1);
ids.add(bd2);

Query query = session.createSQLQuery(sql);
query.setParameterList("ids", ids);

// 2. List of Object arrays
List<Object []> ids = new ArrayList<>();
Object [] bd1 = {new BigDecimal(100119401), new BigDecimal(2)};
Object [] bd2 = {new BigDecimal(100119000), new BigDecimal(1)};
ids.add(bd1);
ids.add(bd2);

Query query = session.createSQLQuery(sql);
query.setParameterList("ids", ids);

// 3. List of inner lists with ids
List<BigDecimal> ob1 = new ArrayList<BigDecimal>();
ob1.add(new BigDecimal(100119401));ob1.add(new BigDecimal(2));
List<BigDecimal> ob2 = new ArrayList<BigDecimal>();
ob2.add(new BigDecimal(100119401));ob2.add(new BigDecimal(2));
List<List<BigDecimal>> ids = new ArrayList<List<BigDecimal>>();
ids.add(ob1);ids.add(ob2);

Query query = session.createSQLQuery(sql);
query.setParameterList("ids", ids);

In all the cases am getting “ORA-00920: invalid relational operator” error.

Exception:

Caused by: java.sql.SQLSyntaxErrorException: ORA-00920: invalid relational operator

    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:450)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:399)
    at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:1017)
    at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:655)
    at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:249)
    at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:566)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:215)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:58)
    at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:776)
    at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:897)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1034)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3820)
    at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3867)
    at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1502)
    at org.apache.tomcat.dbcp.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
    at org.apache.tomcat.dbcp.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:82)
    ... 141 more

Body:
Something like that should work:

String sql = "SELECT * FROM TABLE TA WHERE CONCAT(TA.COLUMN1, '|', TA.COLUMN2) IN (:values)";
List<String> values = new ArrayList<>();
values.add("100119401|2");
values.add("100119000|1");

// ...

Query query = session.createSQLQuery(sql);
query.setParameterList("values", values);

NB: make sure the separator used, here |, is not in your data


问:
Are there any .NET data providers for Oracle that do not require the Oracle Client to be installed?
I am developing a rich client application that will use the Entity Framework (with DevArt's DotConnect for Oracle) to connect to a central Oracle database.  However, I have found that this scenario requires every client machine to have the Oracle client installed in order to connect to the Oracle 10g server.  Is there an easy way around this?  Do the other types of Oracle providers (ODP.NET, EntLib Data, MS .NET Oracle provider) have the same requirements?

EDIT: Thanks to tuinstoel, I've done more research and confirmed that DevArt's dotConnect can be run in Direct mode which does not require the Oracle Client software to be installed.  This should solve my issue of connecting to Oracle using the Entity Framework.  I also plan to connect to Oracle using a DbConnection, for which I can also use DevArt's Oracle provider.  My issue now is that I cannot get the Direct mode to work.

答:
odp.net requires the installation of the Oracle client.

I read on Devart's site that you don't (always) need a Oracle client when you use Dotconnect to Oracle:

dotConnect for Oracle offers two
  connection modes to the Oracle server:
  connection through the Oracle Call
  Interface and direct connection over
  TCP/IP. Applications written with
  dotConnect for Oracle are easy to
  deploy, do not require installation of
  Oracle Client Software, and tend to be
  faster than those that use other data
  connectivity solutions.

So why this question?

OwnerDisplayName: tuinstoel


问:
Predecessor in graphs?
Does the term "predecessor" of a node mean the node that IMMEDIATELY precedes that node ( i.e. is parent of the node) or does it refer to a node at a distance k above that node where k>=1.</p>

答:
From wikipedia:

If v is reachable from u, then u is a
  predecessor of v and v is a successor
  of u. If there is an arc from u to v,
  then u is a direct predecessor of v,
  and v is a direct successor of u.

Title: Predecessor in graphs?


问:
R data table: update join
Suppose I have two data tables:

```<code>X <- data.table(id = 1:5, L = letters[1:5])

   id L
1:  1 a
2:  2 b
3:  3 c
4:  4 d
5:  5 e

Y <- data.table(id = 3:5, L = c(NA, "g", "h"), N = c(10, NA, 12))

   id  L  N
1:  3 NA 10
2:  4  g NA
3:  5  h 12
</code>```

Would it be possible to do a left outer join of X and Y by id using data table built-in functions? If not, I would like build a function (e.g. leftOuterJoin) with the following expected output:

```<code>leftOuterJoin(X, Y, on = "id")

   id  L  N
1:  1  a NA
2:  2  b NA
3:  3 NA 10
4:  4  g NA
5:  5  h 12
</code>```

I have tried without success:

```<code>X[Y, on = "id"]

   id L i.L  N
1:  3 c  NA 10
2:  4 d   g NA
3:  5 e   h 12
</code>```

I have also tried this, which is almost what I am looking for:

```<code>setkey(X, id)
setkey(Y, id)
merge(X, Y, all.x = TRUE)

   id L.x L.y  N
1:  1   a  NA NA
2:  2   b  NA NA
3:  3   c  NA 10
4:  4   d   g NA
5:  5   e   h 12
</code>```

答:
It is an update join:

```<code>library(data.table)
X <- data.table(id = 1:5, L = letters[1:5])
Y <- data.table(id = 3:5, L = c(NA, "g", "h"), N = c(10, NA, 12))
X[Y, on=.(id), c("L", "N"):=.(i.L, i.N)][]
#    id  L  N
# 1:  1  a NA
# 2:  2  b NA
# 3:  3 NA 10
# 4:  4  g NA
# 5:  5  h 12
</code>```

gives you the desired result.

Here I found a solution for multiple columns:

```<code>library(data.table)
X <- data.table(id = 1:5, L = letters[1:5])
Y <- data.table(id = 3:5, L = c(NA, "g", "h"), N = c(10, NA, 12))

X[Y, on=.(id), names(Y)[-1]:=mget(paste0("i.", names(Y)[-1]))]
</code>```

Another variant:

```<code>n <- names(Y)
X[Y, on=.(id), (n):=mget(paste0("i.", n))]
</code>```

Title: R data table: update join

Body:
Suppose I have two data tables:

X <- data.table(id = 1:5, L = letters[1:5])

   id L
1:  1 a
2:  2 b
3:  3 c
4:  4 d
5:  5 e

Y <- data.table(id = 3:5, L = c(NA, "g", "h"), N = c(10, NA, 12))

   id  L  N
1:  3 NA 10
2:  4  g NA
3:  5  h 12

Would it be possible to do a left outer join of X and Y by id using data table built-in functions? If not, I would like build a function (e.g. leftOuterJoin) with the following expected output:

leftOuterJoin(X, Y, on = "id")

   id  L  N
1:  1  a NA
2:  2  b NA
3:  3 NA 10
4:  4  g NA
5:  5  h 12

I have tried without success:

X[Y, on = "id"]

   id L i.L  N
1:  3 c  NA 10
2:  4 d   g NA
3:  5 e   h 12

I have also tried this, which is almost what I am looking for:

setkey(X, id)
setkey(Y, id)
merge(X, Y, all.x = TRUE)

   id L.x L.y  N
1:  1   a  NA NA
2:  2   b  NA NA
3:  3   c  NA 10
4:  4   d   g NA
5:  5   e   h 12

Body:
It is an update join:

library(data.table)
X <- data.table(id = 1:5, L = letters[1:5])
Y <- data.table(id = 3:5, L = c(NA, "g", "h"), N = c(10, NA, 12))
X[Y, on=.(id), c("L", "N"):=.(i.L, i.N)][]
#    id  L  N
# 1:  1  a NA
# 2:  2  b NA
# 3:  3 NA 10
# 4:  4  g NA
# 5:  5  h 12

gives you the desired result.

Here I found a solution for multiple columns:

library(data.table)
X <- data.table(id = 1:5, L = letters[1:5])
Y <- data.table(id = 3:5, L = c(NA, "g", "h"), N = c(10, NA, 12))

X[Y, on=.(id), names(Y)[-1]:=mget(paste0("i.", names(Y)[-1]))]

Another variant:

n <- names(Y)
X[Y, on=.(id), (n):=mget(paste0("i.", n))]


问:
How do I read double quotes(") or single quotes(') through command line into my perl program?
I am trying to use use arguments passed as command line arguments into my script, But while doing so the double quotes(") and single quotes(') vanishes.
for example on running the following:

```<code>#!usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

my $argument_list = join(" ",@ARGV);

print "$argument\n";
</code>```

Upon running the above code:

```<code>perl test1.pl name1 "name2 and name3"
</code>```

I am getting the following output:

```<code>name1 name2 and name3
</code>```

Is there any way to include the double quotes along with the command line arguments so that the final argument is "name2 and name3" and not just name2 and name3 ?

I have tried using '\' to escape double quotes perl test1.pl name1 \"name2 and name3\" but it only makes it worse by considering "name2 as a separate argument and as a separate argument and name3" as another argument.

答:
There's two problems here - the first is that the shell is unwrapping your quotes first before passing them to perl. So you need to escape them.

The second is - @ARGV splits on whitespace.

So to do what you want:

```<code>#!/usr/bin/env perl
use strict;
use warnings;

use Data::Dumper;

use Text::ParseWords qw ( quotewords ) ;

my $input =  "name1 \"name2 and name3\"";
my @words = quotewords ( " ", 0, $input );

print Dumper \@words;
</code>```

Or reading @ARGV:

```<code>#!/usr/bin/env perl
use strict;
use warnings;

use Data::Dumper;
use Text::ParseWords qw ( quotewords ) ;

my @words = quotewords ( " ", 0, join (" ", @ARGV) );

print Dumper \@words;
</code>```

Body:
I am trying to use use arguments passed as command line arguments into my script, But while doing so the double quotes(") and single quotes(') vanishes.
for example on running the following:

#!usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

my $argument_list = join(" ",@ARGV);

print "$argument\n";

Upon running the above code:

perl test1.pl name1 "name2 and name3"

I am getting the following output:

name1 name2 and name3

Is there any way to include the double quotes along with the command line arguments so that the final argument is "name2 and name3" and not just name2 and name3 ?

I have tried using '\' to escape double quotes perl test1.pl name1 \"name2 and name3\" but it only makes it worse by considering "name2 as a separate argument and as a separate argument and name3" as another argument.

Body:
There's two problems here - the first is that the shell is unwrapping your quotes first before passing them to perl. So you need to escape them.

The second is - @ARGV splits on whitespace.

So to do what you want:

#!/usr/bin/env perl
use strict;
use warnings;

use Data::Dumper;

use Text::ParseWords qw ( quotewords ) ;

my $input =  "name1 \"name2 and name3\"";
my @words = quotewords ( " ", 0, $input );

print Dumper \@words;

Or reading @ARGV:

#!/usr/bin/env perl
use strict;
use warnings;

use Data::Dumper;
use Text::ParseWords qw ( quotewords ) ;

my @words = quotewords ( " ", 0, join (" ", @ARGV) );

print Dumper \@words;


问:
Spring multiple autowire candidates
I would like to solve the following problem. Working on a spring project where I have a spring bean configuration class.

```<code>package package.bean_config_java;

@Configuration
@ComponentScan("package.bean_config_java")
public class Beans {

  @Bean
  public Customer customerHashmark() {
    Customer c = new Customer();
    c.setFormatter(hashmarkNameFormatter());

    return c;
  }

  @Bean
  public Customer customerUnderscore() {
    Customer c = new Customer();
    c.setFormatter(underscoreNameFormatter());

    return c;
  }

  @Bean
  public Formatter hashmarkNameFormatter() {
    return new HashmarkNameFormatter();
  }

  @Primary
  @Bean
  public Formatter underscoreNameFormatter() {
    return new UnderscoreNameFormatter();
  }
}
</code>```

After I ask for any of the customers from the container it returns with a customer with underscoreNameFormatter.

I tried to debug this, and found that spring calls customer.setFormatter only once during app start and the origin is my configuration class, so that looks ok, but in the end, when i get back my bean from the ctx.getBean method the formater is underscoreNameFormatter in all cases.

So is it even possible to override the injected value?

Note: With xml config it's possible to do this

```<code><bean class="package.Customer">
  <property name="formatter">
    <bean class="package.HashmarkNameFormatter" />
  </property>
</bean>
</code>```

答:
Because the setter c.setFormatter(hashmarkNameFormatter()); is called in a @Configuration class this call will set the Formatter bean from the application context which in your case is not the object returned by the hashmarkNameFormatter method but the UnderscoreNameFormatter.

I think if you want to set the UnderscoreNameFormatter for customerUnderscore you could inject it as a parameter to the customerHashmark bean creation method by specifying the typed Formatter:

E.g.

```<code>@Bean
public Customer customerHashmark(HashmarkNameFormatter hashmarkNameFormatter) {
    Customer c = new Customer();
    c.setFormatter(hashmarkNameFormatter);

    return c;
}
</code>```

Title: Spring multiple autowire candidates

Body:
I would like to solve the following problem. Working on a spring project where I have a spring bean configuration class.

package package.bean_config_java;

@Configuration
@ComponentScan("package.bean_config_java")
public class Beans {

  @Bean
  public Customer customerHashmark() {
    Customer c = new Customer();
    c.setFormatter(hashmarkNameFormatter());

    return c;
  }

  @Bean
  public Customer customerUnderscore() {
    Customer c = new Customer();
    c.setFormatter(underscoreNameFormatter());

    return c;
  }

  @Bean
  public Formatter hashmarkNameFormatter() {
    return new HashmarkNameFormatter();
  }

  @Primary
  @Bean
  public Formatter underscoreNameFormatter() {
    return new UnderscoreNameFormatter();
  }
}

After I ask for any of the customers from the container it returns with a customer with underscoreNameFormatter.

I tried to debug this, and found that spring calls customer.setFormatter only once during app start and the origin is my configuration class, so that looks ok, but in the end, when i get back my bean from the ctx.getBean method the formater is underscoreNameFormatter in all cases.

So is it even possible to override the injected value?

Note: With xml config it's possible to do this

<bean class="package.Customer">
  <property name="formatter">
    <bean class="package.HashmarkNameFormatter" />
  </property>
</bean>

Body:
Because the setter c.setFormatter(hashmarkNameFormatter()); is called in a @Configuration class this call will set the Formatter bean from the application context which in your case is not the object returned by the hashmarkNameFormatter method but the UnderscoreNameFormatter.

I think if you want to set the UnderscoreNameFormatter for customerUnderscore you could inject it as a parameter to the customerHashmark bean creation method by specifying the typed Formatter:

E.g.

@Bean
public Customer customerHashmark(HashmarkNameFormatter hashmarkNameFormatter) {
    Customer c = new Customer();
    c.setFormatter(hashmarkNameFormatter);

    return c;
}


问:
how can I store different value in different ArrayList in android
I'm working with string value like this String result "aa,bb,cc,dd,ee".

And already split it into aa bb cc dd ee with

```<code>qrList = result.getContents().toString().split("\\,");
List<String> resultToString= new ArrayList(Arrays.asList(qrList));
</code>```

Then I create four ArrayLists.

```<code> ArrayList<String> strA = new ArrayList();
 ArrayList<String> strB = new ArrayList();
 ArrayList<String> strCD = new ArrayList();
 ArrayList<String> strE = new ArrayList();
</code>```

When I use this code below to store string into each new ArrayList.

```<code>for(int count=0; count<resultToString.size(); count++){
    //separate string to array list
    if(count%5==0){
        strA.add(resultToString.get(count));
    }else if(count%5==1){
        strB.add(resultToString.get(count));
    }else if(count%5==2||count%5==3){
        strCD.add(resultToString.get(count));
    }else if(count==4){
        strE.add(resultToString.get(count));
    }
</code>```

The correct result would be

strA stored aa

strB stored bb

strCD stored cc and dd

strE stored ee

It doesn't work because I only get the index value at 0 (strA stored aa).
What should I do to improve my code?

答:
Simply use startsWith and add appropriate values to list

```<code>    for(int count=0; count<resultToString.size(); count++){
        //separate string to array list
        String s = resultToString.get(count);

        if(s.startsWith("a")){
            strA.add(s);
        }else if(s.startsWith("b")){
            strB.add(s);
        }else if(s.startsWith("c")||s.startsWith("d")){
            strCD.add(s);
        }else if(s.startsWith("e")){
            strE.add(s);
        }
    }
</code>```

Body:
I'm working with string value like this String result "aa,bb,cc,dd,ee".

And already split it into aa bb cc dd ee with

qrList = result.getContents().toString().split("\\,");
List<String> resultToString= new ArrayList(Arrays.asList(qrList));

Then I create four ArrayLists.

 ArrayList<String> strA = new ArrayList();
 ArrayList<String> strB = new ArrayList();
 ArrayList<String> strCD = new ArrayList();
 ArrayList<String> strE = new ArrayList();

When I use this code below to store string into each new ArrayList.

for(int count=0; count<resultToString.size(); count++){
    //separate string to array list
    if(count%5==0){
        strA.add(resultToString.get(count));
    }else if(count%5==1){
        strB.add(resultToString.get(count));
    }else if(count%5==2||count%5==3){
        strCD.add(resultToString.get(count));
    }else if(count==4){
        strE.add(resultToString.get(count));
    }

The correct result would be

strA stored aa

strB stored bb

strCD stored cc and dd

strE stored ee

It doesn't work because I only get the index value at 0 (strA stored aa).
What should I do to improve my code?

Body:
Simply use startsWith and add appropriate values to list

    for(int count=0; count<resultToString.size(); count++){
        //separate string to array list
        String s = resultToString.get(count);

        if(s.startsWith("a")){
            strA.add(s);
        }else if(s.startsWith("b")){
            strB.add(s);
        }else if(s.startsWith("c")||s.startsWith("d")){
            strCD.add(s);
        }else if(s.startsWith("e")){
            strE.add(s);
        }
    }


问:
create a display alert function globally and call it from any view controller
```<code>func displayalert(title:String, message:String, vc:UIViewController)
{
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction((UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in

        self.dismiss(animated: true, completion: nil)

    })))

    vc.present(alert, animated: true, completion: nil)

}

this is the function i have used.i tried to call it like this,

 displayalert1(title:"dsfvasdcs", message:"easfSDXCSDZX", vc:validateOTPViewController())
</code>```

<p>it is returning error "BAD ACCESS". the vc.present is running like a loop. I cant understand what the problem is. </p>

答:
I run your code and it working fine. I thing you would pass self in vc.

```<code> self.displayalert(title: "Title", message: "Some Message", vc: self)
</code>```

You can also make an extension of UIViewController-

```<code>   extension UIViewController {
          // Your Function...
    }
</code>```

Now You can globally access this function from any view controller, Just by typing-

```<code>    self.displayalert(title: "Title", message: "Some Message", vc: self)
</code>```

Body:
func displayalert(title:String, message:String, vc:UIViewController)
{
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction((UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in

        self.dismiss(animated: true, completion: nil)

    })))

    vc.present(alert, animated: true, completion: nil)

}

this is the function i have used.i tried to call it like this,

 displayalert1(title:"dsfvasdcs", message:"easfSDXCSDZX", vc:validateOTPViewController())

it is returning error "BAD ACCESS". the vc.present is running like a loop. I cant understand what the problem is.

Body:
I run your code and it working fine. I thing you would pass self in vc.

 self.displayalert(title: "Title", message: "Some Message", vc: self)

You can also make an extension of UIViewController-

   extension UIViewController {
          // Your Function...
    }

Now You can globally access this function from any view controller, Just by typing-

    self.displayalert(title: "Title", message: "Some Message", vc: self)


问:
How to handle both a promise or variable return from a function
Here is a simplified version of what I have:

```<code>function test(thisBool){
   var response;
   if(thisBool){
      response = makeAPIrequest().then(function(){
      }, function(err){
         console.log(err)
      })
   } else {
      response = "doesntmatter"
   }
}
</code>```

So if the parameter is true, make the api request. If it's false, return the 'doesntmatter' string.

When I call this, I wish to use the response in either instance.

```<code>var testResponseTrue = test(true);
var testResponseFalse = test(false);
</code>```

Is there a way to do this? Or will I have to do some callback functions somehow? I'm not sure of the best way to do this, any advice would help :)

答:
You should use callback or promises to handle such kind of scenarios. Below is code snippet for the same using callback:</p>

```<code>function test(thisBool, callback) {
    var response;
    if(thisBool) {
        makeAPIrequest()
        .then(function(response) {
            callback(response);
        }, function(err) {
            callback(err);
        })
    } else {
        response = "doesntmatter";
        callback(response);
    }
}
test(true, function(testResponseTrue) {
    console.log(testResponseTrue);
});
test(false, function(testResponseFalse) {
    console.log(testResponseFalse);
});
</code>```

Body:
Here is a simplified version of what I have:

function test(thisBool){
   var response;
   if(thisBool){
      response = makeAPIrequest().then(function(){
      }, function(err){
         console.log(err)
      })
   } else {
      response = "doesntmatter"
   }
}

So if the parameter is true, make the api request. If it's false, return the 'doesntmatter' string.

When I call this, I wish to use the response in either instance.

var testResponseTrue = test(true);
var testResponseFalse = test(false);

Is there a way to do this? Or will I have to do some callback functions somehow? I'm not sure of the best way to do this, any advice would help :)

Body:
You should use callback or promises to handle such kind of scenarios. Below is code snippet for the same using callback:

function test(thisBool, callback) {
    var response;
    if(thisBool) {
        makeAPIrequest()
        .then(function(response) {
            callback(response);
        }, function(err) {
            callback(err);
        })
    } else {
        response = "doesntmatter";
        callback(response);
    }
}
test(true, function(testResponseTrue) {
    console.log(testResponseTrue);
});
test(false, function(testResponseFalse) {
    console.log(testResponseFalse);
});


问:
c++ grammar, return value type according to this code.
```<code>if(isRoot) isCutVertex[here] = (children>=2);
</code>```

I would like to know whether return value is bool type(1 or 0) or int type(according to the value of children)

答:
The type of the expression children >= 2 is bool in C++ (Cf. int in C).

The bool might be promoted depending on the type of isCutVertex. If isCutVertex is the std::vector<bool> specialisation, then no type conversion will occur (setting aside anything that might be done with here).

Body:
if(isRoot) isCutVertex[here] = (children>=2);

I would like to know whether return value is bool type(1 or 0) or int type(according to the value of children)


问:
Highlight a form select element if its value is empty
I have a form where people sign up for a shift. There are multiple shifts on the page, and I have an onchange event that sends the sign-up via Ajax.

```<code><select name="user" class="assign_user" id="user1">
   <option value="user1234" selected="selected">Joe Bloggs</option>
   <option value="">No-one</option>
   <option value="user1235">Jane Mahon</option>
   <option value="user1236">Ahmed Kitab</option>
   <option value="user1237">Dave Smew</option>
</select>
</code>```

If  <option value="">No-one</option> is selected, I want to highlight the select element in yellow.

I cannot think of a way to do this with just CSS. I tried

```<code>select[value=''] {
   background-color:lightyellow;
}
</code>```

but the attribute filter in the square brackets doesn't accept empty values, as far as I know.

EDIT: just to be clear, empty select elements should be highlighted when the page loads, as well as when the element changes

答:
This is my solution

jQuery

```<code>$(document).ready(function() {
    $('.assign_user').on('change', function() {
          var user_number = $(this).val();
          var shiftid = $(this).siblings('input[name=shiftid]').val();

          /*send data to database via Ajax*/
          $.ajax({
            url: "/admin/saveshift",
            type: "GET",
            data: { 'action': 'update', 'shiftid': shiftid, 'user_number': user_number },
            success: function()
                  {
                    console.log("added a shift ");
                    /* message to user to say the record is updated */
                    $('#assigned').html('Updated');
                    $('#assigned').show();
                    setTimeout(function () {
                        $('#assigned').fadeOut();
                        return false;
                    }, 10000);
                  }
          });
          /* if null is selected, add class unassigned */
          if ($(this).val() == '') {
              $(this).addClass('unassigned');
          } else {
              $(this).removeClass('unassigned');
          }

        });
        /* when page loads, if null is selected, add class unassigned */
        $('.assign_user').each(function() {
            if ($(this).val() == '') {
                $(this).addClass('unassigned');
            }
        });
});
</code>```

CSS

```<code>select.unassigned {
    background-color:lightyellow;
}
</code>```

I couldn't think of a way to do this with just CSS, hence the jQuery.

Body:
I have a form where people sign up for a shift. There are multiple shifts on the page, and I have an onchange event that sends the sign-up via Ajax.

<select name="user" class="assign_user" id="user1">
   <option value="user1234" selected="selected">Joe Bloggs</option>
   <option value="">No-one</option>
   <option value="user1235">Jane Mahon</option>
   <option value="user1236">Ahmed Kitab</option>
   <option value="user1237">Dave Smew</option>
</select>

If  <option value="">No-one</option> is selected, I want to highlight the select element in yellow.

I cannot think of a way to do this with just CSS. I tried

select[value=''] {
   background-color:lightyellow;
}

but the attribute filter in the square brackets doesn't accept empty values, as far as I know.

EDIT: just to be clear, empty select elements should be highlighted when the page loads, as well as when the element changes

Body:
This is my solution

jQuery

$(document).ready(function() {
    $('.assign_user').on('change', function() {
          var user_number = $(this).val();
          var shiftid = $(this).siblings('input[name=shiftid]').val();

          /*send data to database via Ajax*/
          $.ajax({
            url: "/admin/saveshift",
            type: "GET",
            data: { 'action': 'update', 'shiftid': shiftid, 'user_number': user_number },
            success: function()
                  {
                    console.log("added a shift ");
                    /* message to user to say the record is updated */
                    $('#assigned').html('Updated');
                    $('#assigned').show();
                    setTimeout(function () {
                        $('#assigned').fadeOut();
                        return false;
                    }, 10000);
                  }
          });
          /* if null is selected, add class unassigned */
          if ($(this).val() == '') {
              $(this).addClass('unassigned');
          } else {
              $(this).removeClass('unassigned');
          }

        });
        /* when page loads, if null is selected, add class unassigned */
        $('.assign_user').each(function() {
            if ($(this).val() == '') {
                $(this).addClass('unassigned');
            }
        });
});

CSS

select.unassigned {
    background-color:lightyellow;
}

I couldn't think of a way to do this with just CSS, hence the jQuery.


问:
Count the number of selected items in multiselect listbox of html using jquery and store that count in hiddenfield
I want the count of total selected value from html listbox using jquery and store that count in hidden field so that i can access that value server side.Data are dynamically bind to html control. In output it display 0.</p>

```<code>    here is my code:-

var rr = $('ddlAssignUser:selected').length;
     alert(rr);

<select id="ddlAssignUser" class="form-control"  runat="server" multiple="true">  </select>
</code>```

答:
you need to give some space like this in your selector '#ddlAssignUser :selected' and missing #

$(document).on('change','#ddlAssignUser',function(){

var rr = $('#ddlAssignUser :selected').length;
$('#count').val(rr);
     console.log(rr);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="ddlAssignUser" class="form-control"  runat="server" multiple="true">
<option value="1" >1</option>
<option value="2" >2</option>
<option value="3" >3</option>
<option value="4" >4</option>
</select>

<input type="hidden" id="count"></code>```

Body:
I want the count of total selected value from html listbox using jquery and store that count in hidden field so that i can access that value server side.Data are dynamically bind to html control. In output it display 0.

    here is my code:-

var rr = $('ddlAssignUser:selected').length;
     alert(rr);

<select id="ddlAssignUser" class="form-control"  runat="server" multiple="true">  </select>

Body:
you need to give some space like this in your selector '#ddlAssignUser :selected' and missing #

$(document).on('change','#ddlAssignUser',function(){

var rr = $('#ddlAssignUser :selected').length;
$('#count').val(rr);
     console.log(rr);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="ddlAssignUser" class="form-control"  runat="server" multiple="true">
<option value="1" >1</option>
<option value="2" >2</option>
<option value="3" >3</option>
<option value="4" >4</option>
</select>

<input type="hidden" id="count">


问:
Get the current device orientation
I know that this question was asked before and tried to implement the suggested solution, but it doesn't work for me. Perhaps I am doing smth wrong. Do you have any idea?

Here is my code:

```<code>import UIKit

class ViewController: UIViewController {

@IBOutlet weak var test: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    test.backgroundColor = UIColor.darkGray
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated) // No need for semicolon

    func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
        if UIDevice.current.orientation.isLandscape {
            test.backgroundColor = UIColor.purple
        } else {
            test.backgroundColor = UIColor.blue
        }
      }
    }
 }
</code>```

答:
** to those that need additional help see recommendations below
** this function will be called before the change in size and but you will know it from the arguments

Swift 3.x +

```<code>override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    if UIDevice.current.orientation.isLandscape {
        //Landscape

            print("before transition")
            print("w "+"\(width)")
            print("h "+"\(height)")
            print("to size")
            print("w "+"\(size.width)")
            print("h "+"\(size.height)")

    } else {
        //Portrait

            print("before transition")
            print("w "+"\(width)")
            print("h "+"\(height)")
            print("to size")
            print("w "+"\(size.width)")
            print("h "+"\(size.height)")

    }

}
</code>```

Title: Get the current device orientation

Body:
I know that this question was asked before and tried to implement the suggested solution, but it doesn't work for me. Perhaps I am doing smth wrong. Do you have any idea?

Here is my code:

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var test: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    test.backgroundColor = UIColor.darkGray
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated) // No need for semicolon

    func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
        if UIDevice.current.orientation.isLandscape {
            test.backgroundColor = UIColor.purple
        } else {
            test.backgroundColor = UIColor.blue
        }
      }
    }
 }

Body:
** to those that need additional help see recommendations below
** this function will be called before the change in size and but you will know it from the arguments

Swift 3.x +

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    if UIDevice.current.orientation.isLandscape {
        //Landscape

            print("before transition")
            print("w "+"\(width)")
            print("h "+"\(height)")
            print("to size")
            print("w "+"\(size.width)")
            print("h "+"\(size.height)")

    } else {
        //Portrait

            print("before transition")
            print("w "+"\(width)")
            print("h "+"\(height)")
            print("to size")
            print("w "+"\(size.width)")
            print("h "+"\(size.height)")

    }

}


问:
How do I get an XNA 4.0 game to run on other machines?
Whenever I try and run a game made in XNA 4.0 on a machine other than ones used for development, it just won't run. I've followed the instructions here to ensure that all the dependencies are present.

To be clear I've done the following:

Downloaded and installed the Microsoft .NET Framework 4 Client Profile.

Downloaded and installed the Microsoft XNA Framework Redistributable 4.0.

Made sure I am not using anything contained within GamerServices and Microsoft.Xna.Net.*, my references are as follows:

Microsoft.Xna.Framework

  Microsoft.Xna.Framework.Avatar

  Microsoft.Xna.Framework.Game

  Microsoft.Xna.Framework.Graphics

  Microsoft.Xna.Framework.Storage

  Microsoft.Xna.Framework.Video

  Microsoft.Xna.Framework.Xact

  mscorlib

  System System.Core

  System.Windows.Forms

  System.Xml

  System.Xml.Linq

I also followed the advice here to ensure the problem was not within the code itself.

I've tried the follow methods to get it to run (on both Vista and 7):

Use the built in publishing functionality. This results in an error saying that Microsoft.Xna.Input.Touch needs to be present in the GAC. I've tried adding Microsoft.Xna.Input.Touch to the references, and this does not fix the issue.

Copy the XNA dll files locally. This results in an error message stating that Microsoft.Xna.Game.dll or one of its dependencies could not be located.

Copy over everything contained in Release. This results in an Application X stopped working... or APPCRASH error message the second it starts. My code is never reached.

Is there any way to get this to work? I've been attempting to fix it, and with the deadline looming it has been a source of unneeded stress.

答: It turns out the XNA Beta assemblies were still kicking around on the dev machine, and VS opted to use those instead of the correct assemblies for some reason.</p>