问:
Using raycaster to select specific elements of gltf & add event listeners
I'm building an interactive web app. I've loaded a glb file to a scene and now I want to add 2 functionalities:

onMouseover on one of the elements from the object I would like to change the color of that element.

The 3D object consists of a Texture_Group[Object3D] as shown in the console log below. The texture group are essentially 3D letters(objects) that spell out HAJDUK, but I've imported them as a grouped .glb file, I want to add an event listener so when clicked on the individual letter(object) a different link is loaded for each individual object.

My confusion is if I can do this somehow just by using raycaster or do I need to further traverse the Texture_Group and develop a sort of if else logic for that, and how to do any of those?

 I'm guessing I need to use the raycaster and traverse the scene but I'm kind of stuck. Thank you for any of your help and if I need to provide anything else let me now, it's my first question.

I've traversed my scene in the console.log with the help of some code I've found online and adjusted it a bit to my case.

This is my app.js code:

```<code>/*jshint esversion: 6 */
let scene, camera, renderer, h, controls, raycaster, mouse;

function init() {
  scene = new THREE.Scene();

  //Camera
  camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
  camera.position.set(0, 6, 6);

  const myCanvas = document.getElementById('myCanvas');

  //Renderer
  renderer = new THREE.WebGLRenderer({
    canvas: myCanvas,
    antialias: true,
  });
  renderer.setClearColor(0xcfd4d8);
  renderer.setPixelRatio(window.deviceSPixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

  //Controls
  controls = new THREE.OrbitControls(camera, myCanvas);
  controls.target.set(0, 6, 0);
  controls.update();

  controls.enableDamping = true;

  controls.dampingFactor = 0.25;

  controls.screenSpacePanning = false;

  controls.minDistance = -20;
  controls.maxDistance = 100;

  controls.maxPolarAngle = Math.PI;
  controls.enableZoom = true;

  controls.rotateSpeed = 0.3;
  controls.zoomSpeed = 10.0;

  //Lights
  const light = new THREE.AmbientLight(0xffffff, 0.5);
  scene.add(light);

  const light2 = new THREE.PointLight(0xffffff, 0.5);
  scene.add(light2);

  //Loader
  const loader = new THREE.GLTFLoader();
  loader.load(
    'content/hajdukzagltf.glb',
    function (gltf) {
      h = scene.add(gltf.scene);
      h.position.set(6, -2, 1);
      console.log(dumpObject(h).join('\n'));
      console.log(gltf);
    }
  );

}

init();

//Render Loop
render();

function render() {

  requestAnimationFrame(render);

  controls.update();
  renderer.render(scene, camera);
}

//windowResize
function windowResize() {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
}

window.addEventListener('resize', windowResize, false);

//consol log traverse
function dumpVec3(v3, precision = 3) {
  return `${v3.x.toFixed(precision)}, ${v3.y.toFixed(precision)}, ${v3.z.toFixed(precision)}`;
}

function dumpObject(obj, lines = [], isLast = true, prefix = '') {
  const localPrefix = isLast ? '└─' : '├─';
  lines.push(`${prefix}${prefix ? localPrefix : ''}${obj.name || '*no-name*'} [${obj.type}]`);
  const dataPrefix = obj.children.length
     ? (isLast ? '  │ ' : '│ │ ')
     : (isLast ? '    ' : '│   ');
  lines.push(`${prefix}${dataPrefix}  pos: ${dumpVec3(obj.position)}`);
  lines.push(`${prefix}${dataPrefix}  rot: ${dumpVec3(obj.rotation)}`);
  lines.push(`${prefix}${dataPrefix}  scl: ${dumpVec3(obj.scale)}`);
  const newPrefix = prefix + (isLast ? '  ' : '│ ');
  const lastNdx = obj.children.length - 1;
  obj.children.forEach((child, ndx) => {
    const isLast = ndx === lastNdx;
    dumpObject(child, lines, isLast, newPrefix);
  });

  return lines;
}
</code>```

console.log:

```<code>*no-name* [Scene]
  │   pos: 6.0000, -2.0000, 1.0000
  │   rot: 0.0000, 0.0000, 0.0000
  │   scl: 1.0000, 1.0000, 1.0000
  ├─*no-name* [AmbientLight]
  │     pos: 0.0000, 0.0000, 0.0000
  │     rot: 0.0000, 0.0000, 0.0000
  │     scl: 1.0000, 1.0000, 1.0000
  ├─*no-name* [PointLight]
  │     pos: 0.0000, 0.0000, 0.0000
  │     rot: 0.0000, 0.0000, 0.0000
  │     scl: 1.0000, 1.0000, 1.0000
  └─*no-name* [Scene]
    │   pos: 0.0000, 0.0000, 0.0000
    │   rot: 0.0000, 0.0000, 0.0000
    │   scl: 1.0000, 1.0000, 1.0000
    ├─Camera_(2) [PerspectiveCamera]
    │     pos: -12.5626, 8.9117, -9.9300
    │     rot: -0.1273, -0.2253, -0.0286
    │     scl: 1.0000, 1.0000, 1.0000
    ├─Texture_Group [Object3D]
    │     pos: 0.0000, 0.0000, 0.0000
    │     rot: 0.0000, 0.0000, 0.0000
    │     scl: 1.0000, 1.0000, 1.0000
    ├─b [Mesh]
    │     pos: 2.6200, 3.9200, -19.2000
    │     rot: 0.0000, 0.0000, 0.0000
    │     scl: 1.0000, 1.0000, 1.0000
    ├─z [Mesh]
    │     pos: 0.0000, 0.0000, 0.0000
    │     rot: 0.0000, 0.0000, 0.0000
    │     scl: 1.0000, 1.0000, 1.0000
    └─bg [Mesh]
          pos: 0.0000, 0.0000, 0.0000
          rot: 0.0000, 0.0000, 0.0000
          scl: 1.0000, 1.0000, 1.0000
</code>```

答:
As discussed on the comment section, all of the functionalities can be implemented using a simple Raycaster.

In order to detect when the mouse hovers over a set of objects in the scene you can group them together in either a THREE.Group or THREE.Object3D containing children meshes.

You bind a mousemove event to a function that update a global variable mouse containing the viewport mouse position.

```<code>function onMouseMove( event ) {

  event.preventDefault();

  mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
  mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;

}
</code>```

Inside your animation loop, you perform the raycast given the current mouse position and check if that intersects any objects contained by said group. You, then, deal with updating the color of these objects or reverting those when not intersecting.

```<code>function raycast() {

  raycaster.setFromCamera( mouse, camera );

  var intersects = raycaster.intersectObjects( group.children );

  if ( intersects.length > 0 ) {

    if ( INTERSECTED != intersects[ 0 ].object ) {

      if ( INTERSECTED ) INTERSECTED.material.color.setHex( INTERSECTED.currentHex );

      INTERSECTED = intersects[ 0 ].object;
      INTERSECTED.currentHex = INTERSECTED.material.color.getHex();
      INTERSECTED.material.color.setHex( 0xd4d4d4 );

    }

  } else {

    if ( INTERSECTED ) INTERSECTED.material.color.setHex( INTERSECTED.currentHex );

    INTERSECTED = null;

  }

}
</code>```

Finally you bind a click event to another function that performs the desired function if an object is currently intersecting the ray.

```<code>function onMouseClick( event ) {

  if ( INTERSECTED !== null ) clickFunction( INTERSECTED ); // perform object operation

}
</code>```

This JSFiddle example show those functionalities working.

Let me know if something is unclear.

If the objects inside your TEXTURE_GROUP aren't neatly organized in meshes, I suggest that you first pack each letter into a single mesh and, when traversing, you add those to an Object3D or Group if those aren't already in one.

Body:
I'm building an interactive web app. I've loaded a glb file to a scene and now I want to add 2 functionalities:

onMouseover on one of the elements from the object I would like to change the color of that element.

The 3D object consists of a Texture_Group[Object3D] as shown in the console log below. The texture group are essentially 3D letters(objects) that spell out HAJDUK, but I've imported them as a grouped .glb file, I want to add an event listener so when clicked on the individual letter(object) a different link is loaded for each individual object.

My confusion is if I can do this somehow just by using raycaster or do I need to further traverse the Texture_Group and develop a sort of if else logic for that, and how to do any of those?

 I'm guessing I need to use the raycaster and traverse the scene but I'm kind of stuck. Thank you for any of your help and if I need to provide anything else let me now, it's my first question.

I've traversed my scene in the console.log with the help of some code I've found online and adjusted it a bit to my case.

This is my app.js code:

/*jshint esversion: 6 */
let scene, camera, renderer, h, controls, raycaster, mouse;

function init() {
  scene = new THREE.Scene();

  //Camera
  camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
  camera.position.set(0, 6, 6);

  const myCanvas = document.getElementById('myCanvas');

  //Renderer
  renderer = new THREE.WebGLRenderer({
    canvas: myCanvas,
    antialias: true,
  });
  renderer.setClearColor(0xcfd4d8);
  renderer.setPixelRatio(window.deviceSPixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

  //Controls
  controls = new THREE.OrbitControls(camera, myCanvas);
  controls.target.set(0, 6, 0);
  controls.update();

  controls.enableDamping = true;

  controls.dampingFactor = 0.25;

  controls.screenSpacePanning = false;

  controls.minDistance = -20;
  controls.maxDistance = 100;

  controls.maxPolarAngle = Math.PI;
  controls.enableZoom = true;

  controls.rotateSpeed = 0.3;
  controls.zoomSpeed = 10.0;

  //Lights
  const light = new THREE.AmbientLight(0xffffff, 0.5);
  scene.add(light);

  const light2 = new THREE.PointLight(0xffffff, 0.5);
  scene.add(light2);

  //Loader
  const loader = new THREE.GLTFLoader();
  loader.load(
    'content/hajdukzagltf.glb',
    function (gltf) {
      h = scene.add(gltf.scene);
      h.position.set(6, -2, 1);
      console.log(dumpObject(h).join('\n'));
      console.log(gltf);
    }
  );

}

init();

//Render Loop
render();

function render() {

  requestAnimationFrame(render);

  controls.update();
  renderer.render(scene, camera);
}

//windowResize
function windowResize() {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
}

window.addEventListener('resize', windowResize, false);

//consol log traverse
function dumpVec3(v3, precision = 3) {
  return `${v3.x.toFixed(precision)}, ${v3.y.toFixed(precision)}, ${v3.z.toFixed(precision)}`;
}

function dumpObject(obj, lines = [], isLast = true, prefix = '') {
  const localPrefix = isLast ? '└─' : '├─';
  lines.push(`${prefix}${prefix ? localPrefix : ''}${obj.name || '*no-name*'} [${obj.type}]`);
  const dataPrefix = obj.children.length
     ? (isLast ? '  │ ' : '│ │ ')
     : (isLast ? '    ' : '│   ');
  lines.push(`${prefix}${dataPrefix}  pos: ${dumpVec3(obj.position)}`);
  lines.push(`${prefix}${dataPrefix}  rot: ${dumpVec3(obj.rotation)}`);
  lines.push(`${prefix}${dataPrefix}  scl: ${dumpVec3(obj.scale)}`);
  const newPrefix = prefix + (isLast ? '  ' : '│ ');
  const lastNdx = obj.children.length - 1;
  obj.children.forEach((child, ndx) => {
    const isLast = ndx === lastNdx;
    dumpObject(child, lines, isLast, newPrefix);
  });

  return lines;
}

console.log:

*no-name* [Scene]
  │   pos: 6.0000, -2.0000, 1.0000
  │   rot: 0.0000, 0.0000, 0.0000
  │   scl: 1.0000, 1.0000, 1.0000
  ├─*no-name* [AmbientLight]
  │     pos: 0.0000, 0.0000, 0.0000
  │     rot: 0.0000, 0.0000, 0.0000
  │     scl: 1.0000, 1.0000, 1.0000
  ├─*no-name* [PointLight]
  │     pos: 0.0000, 0.0000, 0.0000
  │     rot: 0.0000, 0.0000, 0.0000
  │     scl: 1.0000, 1.0000, 1.0000
  └─*no-name* [Scene]
    │   pos: 0.0000, 0.0000, 0.0000
    │   rot: 0.0000, 0.0000, 0.0000
    │   scl: 1.0000, 1.0000, 1.0000
    ├─Camera_(2) [PerspectiveCamera]
    │     pos: -12.5626, 8.9117, -9.9300
    │     rot: -0.1273, -0.2253, -0.0286
    │     scl: 1.0000, 1.0000, 1.0000
    ├─Texture_Group [Object3D]
    │     pos: 0.0000, 0.0000, 0.0000
    │     rot: 0.0000, 0.0000, 0.0000
    │     scl: 1.0000, 1.0000, 1.0000
    ├─b [Mesh]
    │     pos: 2.6200, 3.9200, -19.2000
    │     rot: 0.0000, 0.0000, 0.0000
    │     scl: 1.0000, 1.0000, 1.0000
    ├─z [Mesh]
    │     pos: 0.0000, 0.0000, 0.0000
    │     rot: 0.0000, 0.0000, 0.0000
    │     scl: 1.0000, 1.0000, 1.0000
    └─bg [Mesh]
          pos: 0.0000, 0.0000, 0.0000
          rot: 0.0000, 0.0000, 0.0000
          scl: 1.0000, 1.0000, 1.0000

Body:
As discussed on the comment section, all of the functionalities can be implemented using a simple Raycaster.

In order to detect when the mouse hovers over a set of objects in the scene you can group them together in either a THREE.Group or THREE.Object3D containing children meshes.

You bind a mousemove event to a function that update a global variable mouse containing the viewport mouse position.

function onMouseMove( event ) {

  event.preventDefault();

  mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
  mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;

}

Inside your animation loop, you perform the raycast given the current mouse position and check if that intersects any objects contained by said group. You, then, deal with updating the color of these objects or reverting those when not intersecting.

function raycast() {

  raycaster.setFromCamera( mouse, camera );

  var intersects = raycaster.intersectObjects( group.children );

  if ( intersects.length > 0 ) {

    if ( INTERSECTED != intersects[ 0 ].object ) {

      if ( INTERSECTED ) INTERSECTED.material.color.setHex( INTERSECTED.currentHex );

      INTERSECTED = intersects[ 0 ].object;
      INTERSECTED.currentHex = INTERSECTED.material.color.getHex();
      INTERSECTED.material.color.setHex( 0xd4d4d4 );

    }

  } else {

    if ( INTERSECTED ) INTERSECTED.material.color.setHex( INTERSECTED.currentHex );

    INTERSECTED = null;

  }

}

Finally you bind a click event to another function that performs the desired function if an object is currently intersecting the ray.

function onMouseClick( event ) {

  if ( INTERSECTED !== null ) clickFunction( INTERSECTED ); // perform object operation

}

This JSFiddle example show those functionalities working.

Let me know if something is unclear.

If the objects inside your TEXTURE_GROUP aren't neatly organized in meshes, I suggest that you first pack each letter into a single mesh and, when traversing, you add those to an Object3D or Group if those aren't already in one.


来源: stackexchange

问:
How can i execute one by one statement after delaying some time in iphone?
I have a problem in iPhone programing.

In my app i want to execute one by one statement after delaying some time.

Example:

```<code>Label1.text =@"2";
</code>```

Then after delaying some time i want execute:

```<code>Label2.text =@"3";
</code>```

Then after delaying some time i want execute:

```<code>Label2.text =@"8";
</code>```

Then after delaying some time i want execute:

```<code>Label2.text =@"6";
</code>```

答:
A simpler approach than NSTimer is to simply sleep between the calls. However, you don't want to lock up the main thread.

```<code>[NSThread sleepForTimeInterval:1.0];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a problem in iPhone programing.

In my app i want to execute one by one statement after delaying some time.

Example:

Label1.text =@"2";

Then after delaying some time i want execute:

Label2.text =@"3";

Then after delaying some time i want execute:

Label2.text =@"8";

Then after delaying some time i want execute:

Label2.text =@"6";

Body:
A simpler approach than NSTimer is to simply sleep between the calls. However, you don't want to lock up the main thread.

[NSThread sleepForTimeInterval:1.0];


问:
Do-While won't repeat itself
I need the user to enter their age, then the program has to calculate how much money they are going to have when their age hit pension. The person is saving 500 or 1000 depending on the situation.

My code won't repeat the if and else statement even though I wrote a Do-While loop. Am I supposed to use a bool-statement? How or where? Or there something else I need to look at?

I've tried using only 'while' but I think I need to use a do-while.

```<code>static void Main(string[] args)
{
    Console.Write("Enter age");
    string str = Console.ReadLine();
    int MyAge = Convert.ToInt32(str);
    int money = 15000;
    {
        do
        {
            {
                if (money > 20000 || MyAge < 60)
                {
                    Console.Write("You are saving little");
                    money = money + 500;
                }
                else
                {
                    Console.Write("You are saving a lot");
                    money = money + 1000;
                }
                MyAge++;
            }
        }
        while (money > 20000 && MyAge > 65);
    }

    Console.Write("You are retired by the age of " + MyAge + " and you saved " + money + " dollars.");
}
</code>```

I expected the program to hit at least 65 but it ends by the age of 26 of I type down that I'm 25 years old. So it doesn't loop.

答:
If you want to hit it more times, when you say that you are 25 years old, you need to change conditions in your while statement.  It should look something like this under.

```<code>static void Main(string[] args)
        {
            Console.Write("Enter age");
            string str = Console.ReadLine();
            int MyAge = Convert.ToInt32(str);
            int money = 15000;
            {
                do
                {
                    {
                        if (money > 20000 || MyAge < 60)
                        {
                            Console.Write("You are saving little");
                            money = money + 500;
                        }
                        else
                        {
                            Console.Write("You are saving a lot");
                            money = money + 1000;
                        }
                        MyAge++;
                    }
                }
                while (money < 40000 && MyAge < 65);
            }

            Console.Write("You are retired by the age of " + MyAge + " and you saved " + money + " dollars.");
    }
</code>```

PS "money > 20000" is just to small number and you reach it very fast.

ContentLicense: CC BY-SA 4.0

Title: Do-While won't repeat itself

Body:
I need the user to enter their age, then the program has to calculate how much money they are going to have when their age hit pension. The person is saving 500 or 1000 depending on the situation.

My code won't repeat the if and else statement even though I wrote a Do-While loop. Am I supposed to use a bool-statement? How or where? Or there something else I need to look at?

I've tried using only 'while' but I think I need to use a do-while.

static void Main(string[] args)
{
    Console.Write("Enter age");
    string str = Console.ReadLine();
    int MyAge = Convert.ToInt32(str);
    int money = 15000;
    {
        do
        {
            {
                if (money > 20000 || MyAge < 60)
                {
                    Console.Write("You are saving little");
                    money = money + 500;
                }
                else
                {
                    Console.Write("You are saving a lot");
                    money = money + 1000;
                }
                MyAge++;
            }
        }
        while (money > 20000 && MyAge > 65);
    }

    Console.Write("You are retired by the age of " + MyAge + " and you saved " + money + " dollars.");
}

I expected the program to hit at least 65 but it ends by the age of 26 of I type down that I'm 25 years old. So it doesn't loop.

Body:
If you want to hit it more times, when you say that you are 25 years old, you need to change conditions in your while statement.  It should look something like this under.

static void Main(string[] args)
        {
            Console.Write("Enter age");
            string str = Console.ReadLine();
            int MyAge = Convert.ToInt32(str);
            int money = 15000;
            {
                do
                {
                    {
                        if (money > 20000 || MyAge < 60)
                        {
                            Console.Write("You are saving little");
                            money = money + 500;
                        }
                        else
                        {
                            Console.Write("You are saving a lot");
                            money = money + 1000;
                        }
                        MyAge++;
                    }
                }
                while (money < 40000 && MyAge < 65);
            }

            Console.Write("You are retired by the age of " + MyAge + " and you saved " + money + " dollars.");
    }

PS "money > 20000" is just to small number and you reach it very fast.


问:
How to annotate Express middlewares with JSDoc?
I'm trying to document an Express middleware, but the build-in validation tool in WebStorm tells me that types are incorrectly assigned in the following JSDoc block:

```<code>/**
 * My middleware.
 *
 * @param {Object} req
 * @param {Object} res
 * @param {Function} next
 * @return {Object}
 */
exports.show = function(req, res, next) {
    ...
};
</code>```

In Express sources, I didn't find any @typedefs to help me. Also, I want to avoid things like @param {*}.

What is the correct way to document Express middleware using JSDoc? Thanks for any help.

答:
You can document your middleware with

```<code>const express = require("express");

/**
 * @param {express.Request} req
 * @param {express.Response} res
 * @param {express.NextFunction} next
 */
function (req, res, next) {}
</code>```

when you have middleware that add attribute to req, you can also add them with

```<code>const express = require("express");

/**
 * @param {express.Request & {specialParam1 : string, specialParam2 : any}} req
 * @param {express.Response} res
 * @param {express.NextFunction} next
 */
function (req, res, next) {}
</code>```

or event better, create a typedef for each source of new elem added on "req" and use "&" to create a type combining them all.

Body:
I'm trying to document an Express middleware, but the build-in validation tool in WebStorm tells me that types are incorrectly assigned in the following JSDoc block:

/**
 * My middleware.
 *
 * @param {Object} req
 * @param {Object} res
 * @param {Function} next
 * @return {Object}
 */
exports.show = function(req, res, next) {
    ...
};

In Express sources, I didn't find any @typedefs to help me. Also, I want to avoid things like @param {*}.

What is the correct way to document Express middleware using JSDoc? Thanks for any help.

Body:
You can document your middleware with

const express = require("express");

/**
 * @param {express.Request} req
 * @param {express.Response} res
 * @param {express.NextFunction} next
 */
function (req, res, next) {}

when you have middleware that add attribute to req, you can also add them with

const express = require("express");

/**
 * @param {express.Request & {specialParam1 : string, specialParam2 : any}} req
 * @param {express.Response} res
 * @param {express.NextFunction} next
 */
function (req, res, next) {}

or event better, create a typedef for each source of new elem added on "req" and use "&" to create a type combining them all.


问:
Open activity from other app (My app to MiFit activity)
I want to open the MiFit app, in the Google Fit Syncronize, but i'm getting erros. How can i open clicking in a button?

Here is my code:

```<code>@OnClick(R.id.div_mi_band)
public void miBandIntegration() {
        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.xiaomi.hm.health.thirdbind",".thirdbind.ThirdBindActivity"));
        startActivity(intent);
}
</code>```

答:
Try this.</p>

```<code>Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.xiaomi.hm.health.thirdbind");
if (launchIntent != null) {
    startActivity(launchIntent);//null pointer check in case package name was not found
}
</code>```

Body:
I want to open the MiFit app, in the Google Fit Syncronize, but i'm getting erros. How can i open clicking in a button?

Here is my code:

@OnClick(R.id.div_mi_band)
public void miBandIntegration() {
        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.xiaomi.hm.health.thirdbind",".thirdbind.ThirdBindActivity"));
        startActivity(intent);
}

Body:
Try this.

Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.xiaomi.hm.health.thirdbind");
if (launchIntent != null) {
    startActivity(launchIntent);//null pointer check in case package name was not found
}


问:
IntelliSense is not working in SQL Server Management Studio
We use SQL Server Management Studio 2008 R2. IntelliSense works with SA account perfectly. But it is not working with Windows Authentication user. The user has access master db with db_owner role but it's not sysadmin.

How do I fix this issue?

答: If you have are seeing your text in red color, and have a bunch of statements, it could be because of a missing quote. Or a bad syntax check. Try typing a quote at the end. Then Intellisense should kick in again in your next statement.</p>


问:
EC2 SSH connection broken pipe; cannot reconnect
I successfully connected to an EC2 instance like so:

```<code>ssh -i .ssh/ec2docker.cer user@SOMEIP
</code>```

After about an hour of using the instance, I leave and come back further two hours to this:

```<code>$ packet_write_wait: Connection to xx port 22: Broken pipe
</code>```

Now, when trying to connect, nothing happens at all:

```<code>OpenSSH_7.9p1, OpenSSL 1.1.1b FIPS  26 Feb 2019
debug1: Reading configuration data /etc/ssh/ssh_config
debug3: /etc/ssh/ssh_config line 52: Including file /etc/ssh/ssh_config.d/05-redhat.conf depth 0
debug1: Reading configuration data /etc/ssh/ssh_config.d/05-redhat.conf
debug2: checking match for 'final all' host xxx originally xxx
debug3: /etc/ssh/ssh_config.d/05-redhat.conf line 3: not matched 'final'
debug2: match not found
debug3: /etc/ssh/ssh_config.d/05-redhat.conf line 5: Including file /etc/crypto-policies/back-ends/openssh.config depth 1 (parse only)
debug1: Reading configuration data /etc/crypto-policies/back-ends/openssh.config
debug3: gss kex names ok: [gss-gex-sha1-,gss-group14-sha1-,gss-group1-sha1-]
debug3: kex names ok: [curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1]
debug1: configuration requests final Match pass
debug1: re-parsing configuration
debug1: Reading configuration data /etc/ssh/ssh_config
debug3: /etc/ssh/ssh_config line 52: Including file /etc/ssh/ssh_config.d/05-redhat.conf depth 0
debug1: Reading configuration data /etc/ssh/ssh_config.d/05-redhat.conf
debug2: checking match for 'final all' host xxx originally xxx
debug3: /etc/ssh/ssh_config.d/05-redhat.conf line 3: matched 'final'
debug2: match found
debug3: /etc/ssh/ssh_config.d/05-redhat.conf line 5: Including file /etc/crypto-policies/back-ends/openssh.config depth 1
debug1: Reading configuration data /etc/crypto-policies/back-ends/openssh.config
debug3: gss kex names ok: [gss-gex-sha1-,gss-group14-sha1-,gss-group1-sha1-]
debug3: kex names ok: [curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1]
debug2: resolving "xxxx" port 22
debug2: ssh_connect_direct
debug1: Connecting to xxx [xx] port 22.
debug1: Connection established.
debug1: identity file .ssh/ec2docker.cer type -1
debug1: identity file .ssh/ec2docker.cer-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_7.9
</code>```

ssh does not terminate or give an error. The EC2 monitor shows that the instance is running with non-zero CPU utilization (around 25%) and non-zero network read and write.

答:
Broken Pipe means Connection was lost

1) Click on EC2- Instance
2) Click on connect
3) Use the command to connect and it should work

Body:
I successfully connected to an EC2 instance like so:

ssh -i .ssh/ec2docker.cer user@SOMEIP

After about an hour of using the instance, I leave and come back further two hours to this:

$ packet_write_wait: Connection to xx port 22: Broken pipe

Now, when trying to connect, nothing happens at all:

OpenSSH_7.9p1, OpenSSL 1.1.1b FIPS  26 Feb 2019
debug1: Reading configuration data /etc/ssh/ssh_config
debug3: /etc/ssh/ssh_config line 52: Including file /etc/ssh/ssh_config.d/05-redhat.conf depth 0
debug1: Reading configuration data /etc/ssh/ssh_config.d/05-redhat.conf
debug2: checking match for 'final all' host xxx originally xxx
debug3: /etc/ssh/ssh_config.d/05-redhat.conf line 3: not matched 'final'
debug2: match not found
debug3: /etc/ssh/ssh_config.d/05-redhat.conf line 5: Including file /etc/crypto-policies/back-ends/openssh.config depth 1 (parse only)
debug1: Reading configuration data /etc/crypto-policies/back-ends/openssh.config
debug3: gss kex names ok: [gss-gex-sha1-,gss-group14-sha1-,gss-group1-sha1-]
debug3: kex names ok: [curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1]
debug1: configuration requests final Match pass
debug1: re-parsing configuration
debug1: Reading configuration data /etc/ssh/ssh_config
debug3: /etc/ssh/ssh_config line 52: Including file /etc/ssh/ssh_config.d/05-redhat.conf depth 0
debug1: Reading configuration data /etc/ssh/ssh_config.d/05-redhat.conf
debug2: checking match for 'final all' host xxx originally xxx
debug3: /etc/ssh/ssh_config.d/05-redhat.conf line 3: matched 'final'
debug2: match found
debug3: /etc/ssh/ssh_config.d/05-redhat.conf line 5: Including file /etc/crypto-policies/back-ends/openssh.config depth 1
debug1: Reading configuration data /etc/crypto-policies/back-ends/openssh.config
debug3: gss kex names ok: [gss-gex-sha1-,gss-group14-sha1-,gss-group1-sha1-]
debug3: kex names ok: [curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1]
debug2: resolving "xxxx" port 22
debug2: ssh_connect_direct
debug1: Connecting to xxx [xx] port 22.
debug1: Connection established.
debug1: identity file .ssh/ec2docker.cer type -1
debug1: identity file .ssh/ec2docker.cer-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_7.9

ssh does not terminate or give an error. The EC2 monitor shows that the instance is running with non-zero CPU utilization (around 25%) and non-zero network read and write.


问:
IdentityServer4 - Is there a way to get the claims in response on connect/token endpoint?
I need to add some fields in the response of the connect/token endpoint  on identityserver. I want to add some claims. Is there any way to do that?

I dont want to use the connect/userinfo endpoint, My Client is using resource owner password flow. I just want the respose something like this

```<code>{
    "access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjcxQkQwM0MxRUFBOUM3NDc3RkEwMDhFMTY4M0VCMkI4NjQ3Mjg0QjgiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJjYjBEd2VxcHgwZF9vQWpoYUQ2eXVHUnloTGcifQ.eyJuYmYiOjE1NTg5NzMyMjAsImV4cCI6MTU1ODk3NjgyMCwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1NTgzOSIsImF1ZCI6WyJodHRwOi8vbG9jYWxob3N0OjU1ODM5L3Jlc291cmNlcyIsImFwaSJdLCJjbGllbnRfaWQiOiJyZWFscGxhemEuYnVkZ2V0Iiwic3ViIjoiamFpci50YXNheWNvQHJlYWxwbGF6YS5jb20ucGUiLCJhdXRoX3RpbWUiOjE1NTg5NzMyMjAsImlkcCI6ImxvY2FsIiwiZ2l2ZW5fbmFtZSI6IkpBSVIgQU5UT05JTyIsInVzZXJfbmFtZXMiOiJKQUlSIEFOVE9OSU8iLCJ1c2VyX2xhc3RuYW1lIjoiVEFTQVlDTyIsInVzZXJfbW90aGVyX2xhc3RuYW1lIjoiQkFVVElTVEEiLCJ1c2VyX3R5cGUiOiIyIiwidXNlcl9kb2N1bWVudF9udW1iZXIiOiI0NzEwMzMwMyIsImNvZGlnb191bmljbyI6IjQyNSIsInVzZXJfcmVkIjoiUlAwNjg5Iiwic2NvcGUiOlsiYXBpIl0sImFtciI6WyJBdXRlbnRpY2FkbyJdfQ.twCgMlcOTDsaBnwmxy_kNLHVE0vtMYA_bqAjIGjatTmkLPz7ozWltoMfrlw6XUmHtre3TAcMkkoUr7Ak7qWpAiWrcuvNVgHTyfKqSjloG18KyySrhW6qFSfOdtkcNuf7bhWsJYvtiZpdzRv70xC1XrGo8Vx9hhUEQxQVDa03kQdCkeCz_EgMnmQ5JL21lUM80GS3FikZHZ2UVRXdjXkFTARM7FOb6wKnasUyIPxSGfgFKgJmjYqhpjED8gSgmo2So_qc9gpc9f8nlQlTFhuulgJO_cOioOpDE8ywHpxXyjx5dbYp4JQ0hxRjtNTyyA7oA25YMwvNBpYIMzmvqyjDTQ",
    "expires_in": 3600,
    "token_type": "Bearer"
, "claim_1": "XXXXXX", "claim_2" : "SSSSSS" }
</code>```

答:
You can implement your ICustomTokenRequestValidator like the following:

public class YourCustomTokenRequestValidator: ICustomTokenRequestValidator
{
  public Task ValidateAsync(CustomTokenRequestValidationContext context)
  {
    context.Result.CustomResponse =
      new Dictionary<string, object>{{"claim_1", "XXXXXX"}, {"claim_2", "SSSSSS"}};
    return Task.CompletedTask;
  }
}
```

<p>and then in your startup:</p>

<pre class="lang-cs prettyprint-override"><code>services.AddIdentityServer()
   .AddCustomTokenRequestValidator<YourCustomTokenRequestValidator>();
</code>```

Body:
I need to add some fields in the response of the connect/token endpoint  on identityserver. I want to add some claims. Is there any way to do that?

I dont want to use the connect/userinfo endpoint, My Client is using resource owner password flow. I just want the respose something like this

{
    "access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjcxQkQwM0MxRUFBOUM3NDc3RkEwMDhFMTY4M0VCMkI4NjQ3Mjg0QjgiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJjYjBEd2VxcHgwZF9vQWpoYUQ2eXVHUnloTGcifQ.eyJuYmYiOjE1NTg5NzMyMjAsImV4cCI6MTU1ODk3NjgyMCwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1NTgzOSIsImF1ZCI6WyJodHRwOi8vbG9jYWxob3N0OjU1ODM5L3Jlc291cmNlcyIsImFwaSJdLCJjbGllbnRfaWQiOiJyZWFscGxhemEuYnVkZ2V0Iiwic3ViIjoiamFpci50YXNheWNvQHJlYWxwbGF6YS5jb20ucGUiLCJhdXRoX3RpbWUiOjE1NTg5NzMyMjAsImlkcCI6ImxvY2FsIiwiZ2l2ZW5fbmFtZSI6IkpBSVIgQU5UT05JTyIsInVzZXJfbmFtZXMiOiJKQUlSIEFOVE9OSU8iLCJ1c2VyX2xhc3RuYW1lIjoiVEFTQVlDTyIsInVzZXJfbW90aGVyX2xhc3RuYW1lIjoiQkFVVElTVEEiLCJ1c2VyX3R5cGUiOiIyIiwidXNlcl9kb2N1bWVudF9udW1iZXIiOiI0NzEwMzMwMyIsImNvZGlnb191bmljbyI6IjQyNSIsInVzZXJfcmVkIjoiUlAwNjg5Iiwic2NvcGUiOlsiYXBpIl0sImFtciI6WyJBdXRlbnRpY2FkbyJdfQ.twCgMlcOTDsaBnwmxy_kNLHVE0vtMYA_bqAjIGjatTmkLPz7ozWltoMfrlw6XUmHtre3TAcMkkoUr7Ak7qWpAiWrcuvNVgHTyfKqSjloG18KyySrhW6qFSfOdtkcNuf7bhWsJYvtiZpdzRv70xC1XrGo8Vx9hhUEQxQVDa03kQdCkeCz_EgMnmQ5JL21lUM80GS3FikZHZ2UVRXdjXkFTARM7FOb6wKnasUyIPxSGfgFKgJmjYqhpjED8gSgmo2So_qc9gpc9f8nlQlTFhuulgJO_cOioOpDE8ywHpxXyjx5dbYp4JQ0hxRjtNTyyA7oA25YMwvNBpYIMzmvqyjDTQ",
    "expires_in": 3600,
    "token_type": "Bearer"
, "claim_1": "XXXXXX", "claim_2" : "SSSSSS" }

Body:
You can implement your ICustomTokenRequestValidator like the following:

public class YourCustomTokenRequestValidator: ICustomTokenRequestValidator
{
  public Task ValidateAsync(CustomTokenRequestValidationContext context)
  {
    context.Result.CustomResponse =
      new Dictionary<string, object>{{"claim_1", "XXXXXX"}, {"claim_2", "SSSSSS"}};
    return Task.CompletedTask;
  }
}

and then in your startup:

services.AddIdentityServer()
   .AddCustomTokenRequestValidator<YourCustomTokenRequestValidator>();


问:
Loader for a specific section in HTML
I am kind of newbie in website development, so kind of confused with the behavior of web page.
I want to use loader to hide the image loading in the HTML. In index page I have used tabs view to show the product category and in every category, images are shown. So loading images is taking time and at first it shows all the product images of all categories which is not acceptable. I am talking about a section that is after slider.

```<code>                <ul class="nav nav-pills sort-source sort-source-style-3 justify-content-center" data-sort-id="portfolio" data-option-key="filter" data-plugin-options="{'layoutMode': 'fitRows', 'filter': '.custom'}">
                    <li class="nav-item active" data-option-value=".custom"><a class="nav-link text-1 text-uppercase active" href="#">Custom Point of Sale Displays</a></li>
                    <li class="nav-item" data-option-value=".wide-format"><a class="nav-link text-1 text-uppercase" href="#">Wide Format printing</a></li>
                    <li class="nav-item" data-option-value=".digital"><a class="nav-link text-1 text-uppercase" href="#">Digital small Format</a></li>
                    <li class="nav-item" data-option-value=".mailing"><a class="nav-link text-1 text-uppercase" href="#">Mailing</a></li>
                    <li class="nav-item" data-option-value=".kitting"><a class="nav-link text-1 text-uppercase" href="#">Kitting & Distribution with Online Tracking</a></li>
                    </ul>

                <div class="sort-destination-loader sort-destination-loader-showing mt-4 pt-2">
                    <div  class="row portfolio-list sort-destination lightbox" data-sort-id="portfolio" data-plugin-options="{'delegate': 'a.lightbox-portfolio', 'type': 'image', 'gallery': {'enabled': true}}">
                        <!-- custom point of sales display-->
                        <div class="col-sm-6 col-lg-3 isotope-item custom">
                            <div class="portfolio-item">
                                <span class="thumb-info thumb-info-no-borders thumb-info-bottom-info thumb-info-no-borders-rounded thumb-info-lighten thumb-info-bottom-info thumb-info-bottom-info-dark thumb-info-bottom-info-show-more thumb-info-centered-icons border-radius-0">
                                    <span class="thumb-info-wrapper border-radius-0">
                                        <img src="img/gallery/custom1.png" class="img-fluid border-radius-0" alt="">
                                        <!-- <span class=" thumb-info-title thumb-info line-height-1">Project Title</span>   -->
                                        <span class="thumb-info-action">
                                            <a href="img/gallery/custom1.png" class="lightbox-portfolio">
                                                <span class="thumb-info-action-icon thumb-info-action-icon-light"><i class="fas fa-search text-dark"></i></span>
                                            </a>
                                        </span>
                                    </span>
                                </span>
                            </div>
                        </div>
                        <div class="col-sm-6 col-lg-3 isotope-item custom">
                            <div class="portfolio-item">
                                <span class="thumb-info thumb-info-no-borders thumb-info-bottom-info thumb-info-no-borders-rounded thumb-info-lighten thumb-info-bottom-info thumb-info-bottom-info-dark thumb-info-bottom-info-show-more thumb-info-centered-icons border-radius-0">
                                    <span class="thumb-info-wrapper border-radius-0">
                                        <img src="img/gallery/custom2.png" class="img-fluid border-radius-0" alt="">
                                        <!-- <span class=" thumb-info-title thumb-info line-height-1">Project Title</span> -->
                                        <span class="thumb-info-action">
                                            <a href="img/gallery/custom2.png" class="lightbox-portfolio">
                                                <span class="thumb-info-action-icon thumb-info-action-icon-light"><i class="fas fa-search text-dark"></i></span>
                                            </a>
                                        </span>
                                    </span>
                                </span>
                            </div>
                        </div>
                        <!-- custom displays end-->
                        <!-- wide format starts-->
                        <div class="col-sm-6 col-lg-3 isotope-item wide-format">
                            <div class="portfolio-item">
                                <span class="thumb-info thumb-info-no-borders thumb-info-bottom-info thumb-info-no-borders-rounded thumb-info-lighten thumb-info-bottom-info thumb-info-bottom-info-dark thumb-info-bottom-info-show-more thumb-info-centered-icons border-radius-0">
                                    <span class="thumb-info-wrapper border-radius-0">
                                        <img src="img/gallery/corflutes.png" class="img-fluid border-radius-0" alt="">
                                        <span class=" thumb-info-title thumb-info line-height-1">Corflute Signs</span>
                                        <span class="thumb-info-action">
                                            <a href="img/gallery/corflutes.png" class="lightbox-portfolio">
                                                <span class="thumb-info-action-icon thumb-info-action-icon-light"><i class="fas fa-search text-dark"></i></span>
                                            </a>
                                        </span>
                                    </span>
                                </span>
                            </div>
                        </div>
                        <div class="col-sm-6 col-lg-3 isotope-item wide-format">
                            <div class="portfolio-item">
                                <span class="thumb-info thumb-info-no-borders thumb-info-bottom-info thumb-info-no-borders-rounded thumb-info-lighten thumb-info-bottom-info thumb-info-bottom-info-dark thumb-info-bottom-info-show-more thumb-info-centered-icons border-radius-0">
                                    <span class="thumb-info-wrapper border-radius-0">
                                        <img src="img/gallery/screenboard.png" class="img-fluid border-radius-0" alt="">
                                        <span class=" thumb-info-title thumb-info line-height-1">Screen Board Signs</span>
                                        <span class="thumb-info-action">
                                            <a href="img/gallery/screenboard.png" class="lightbox-portfolio">
                                                <span class="thumb-info-action-icon thumb-info-action-icon-light"><i class="fas fa-search text-dark"></i></span>
                                            </a>
                                        </span>
                                    </span>
                                </span>
                            </div>
                        </div>
                        <div class="col-sm-6 col-lg-3 isotope-item wide-format">
                            <div class="portfolio-item">
                                <span class="thumb-info thumb-info-no-borders thumb-info-bottom-info thumb-info-no-borders-rounded thumb-info-lighten thumb-info-bottom-info thumb-info-bottom-info-dark thumb-info-bottom-info-show-more thumb-info-centered-icons border-radius-0">
                                    <span class="thumb-info-wrapper border-radius-0">
                                        <img src="img/gallery/economy.png" class="img-fluid border-radius-0" alt="">
                                        <span class=" thumb-info-title thumb-info line-height-1">Economy Pull Up Banners</span>
                                        <span class="thumb-info-action">
                                            <a href="img/gallery/economy.png" class="lightbox-portfolio">
                                                <span class="thumb-info-action-icon thumb-info-action-icon-light"><i class="fas fa-search text-dark"></i></span>
                                            </a>
                                        </span>
                                    </span>
                                </span>
                            </div>
                        </div>

                        <!-- wide format ends-->

                        <!-- digital small format-->
                        <div class="col-sm-6 col-lg-3 isotope-item digital">
                            <div class="portfolio-item">
                                <span class="thumb-info thumb-info-no-borders thumb-info-bottom-info thumb-info-no-borders-rounded thumb-info-lighten thumb-info-bottom-info thumb-info-bottom-info-dark thumb-info-bottom-info-show-more thumb-info-centered-icons border-radius-0">
                                    <span class="thumb-info-wrapper border-radius-0">
                                        <img src="img/gallery/doorhangers.png" class="img-fluid border-radius-0" alt="">
                                        <span class=" thumb-info-title thumb-info line-height-1">Door Hangers</span>
                                        <span class="thumb-info-action">
                                            <a href="img/gallery/doorhangers.png" class="lightbox-portfolio">
                                                <span class="thumb-info-action-icon thumb-info-action-icon-light"><i class="fas fa-search text-dark"></i></span>
                                            </a>
                                        </span>
                                    </span>
                                </span>
                            </div>
                        </div>
                        <div class="col-sm-6 col-lg-3 isotope-item digital">
                            <div class="portfolio-item">
                                <span class="thumb-info thumb-info-no-borders thumb-info-bottom-info thumb-info-no-borders-rounded thumb-info-lighten thumb-info-bottom-info thumb-info-bottom-info-dark thumb-info-bottom-info-show-more thumb-info-centered-icons border-radius-0">
                                    <span class="thumb-info-wrapper border-radius-0">
                                        <img src="img/gallery/businesscards.png" class="img-fluid border-radius-0" alt="">
                                        <span class=" thumb-info-title thumb-info line-height-1">Business Cards</span>
                                        <span class="thumb-info-action">
                                            <a href="img/gallery/businesscards.png" class="lightbox-portfolio">
                                                <span class="thumb-info-action-icon thumb-info-action-icon-light"><i class="fas fa-search text-dark"></i></span>
                                            </a>
                                        </span>
                                    </span>
                                </span>
                            </div>
                        </div>
                        <div class="col-sm-6 col-lg-3 isotope-item digital">
                            <div class="portfolio-item">
                                <span class="thumb-info thumb-info-no-borders thumb-info-bottom-info thumb-info-no-borders-rounded thumb-info-lighten thumb-info-bottom-info thumb-info-bottom-info-dark thumb-info-bottom-info-show-more thumb-info-centered-icons border-radius-0">
                                    <span class="thumb-info-wrapper border-radius-0">
                                        <img src="img/gallery/flyers.png" class="img-fluid border-radius-0" alt="">
                                        <span class=" thumb-info-title thumb-info line-height-1">Flyers</span>
                                        <span class="thumb-info-action">
                                            <a href="img/gallery/flyers.png" class="lightbox-portfolio">
                                                <span class="thumb-info-action-icon thumb-info-action-icon-light"><i class="fas fa-search text-dark"></i></span>
                                            </a>
                                        </span>
                                    </span>
                                </span>
                            </div>
                        </div>
                        <!-- digital displays end-->

                        <!-- mailing -->
                        <div class="col-sm-6 col-lg-3 isotope-item mailing">
                            <div class="portfolio-item">
                                <span class="thumb-info thumb-info-no-borders thumb-info-bottom-info thumb-info-no-borders-rounded thumb-info-lighten thumb-info-bottom-info thumb-info-bottom-info-dark thumb-info-bottom-info-show-more thumb-info-centered-icons border-radius-0">
                                    <span class="thumb-info-wrapper border-radius-0">
                                        <img src="img/gallery/mailing.png" class="img-fluid border-radius-0" alt="">
                                        <span class="thumb-info-action">
                                            <a href="img/gallery/mailing.png" class="lightbox-portfolio">
                                                <span class="thumb-info-action-icon thumb-info-action-icon-light"><i class="fas fa-search text-dark"></i></span>
                                            </a>
                                        </span>
                                    </span>
                                </span>
                            </div>
                        </div>
                        <div class="col-sm-6 col-lg-3 isotope-item mailing">
                            <div class="portfolio-item">
                                <span class="thumb-info thumb-info-no-borders thumb-info-bottom-info thumb-info-no-borders-rounded thumb-info-lighten thumb-info-bottom-info thumb-info-bottom-info-dark thumb-info-bottom-info-show-more thumb-info-centered-icons border-radius-0">
                                    <span class="thumb-info-wrapper border-radius-0">
                                        <img src="img/gallery/mailing2.png" class="img-fluid border-radius-0" alt="">
                                        <span class="thumb-info-action">
                                            <a href="img/gallery/mailing2.png" class="lightbox-portfolio">
                                                <span class="thumb-info-action-icon thumb-info-action-icon-light"><i class="fas fa-search text-dark"></i></span>
                                            </a>
                                        </span>
                                    </span>
                                </span>
                            </div>
                        </div>
                        <!-- mailing ends-->

                    </div>
                </div>
            </div>
        </div>
    </div>
</section>
</code>```

答:
My first guess is that perhaps your client has not cleared his cache, and so is running old code. He can clear the cache by following these instructions.

If the above did not fix the problem:

This is a kludge, because I don't know your full HTML/javascript code, but:

Perhaps you can hide the section with the category images for a second or two, and then allow it to be displayed when appropriate:

```<code> .sort-destination-loader.sort-destination-loader-showing{display:none;}
</code>```

and in javascript:

```<code>setTimeout(function(){
    $('.sort-destination-loader.sort-destination-loader-showing').show();
},3000); //allow display after 3 seconds
</code>```

If that works, then step-back the ,3000 until it is as short a delay as possible:

```<code>},500); //allow display after 1/2 second
</code>```

Perhaps this would solve the problem temporarily while you are working on understanding the full problem?

Title: Loader for a specific section in HTML

Body:
I am kind of newbie in website development, so kind of confused with the behavior of web page.
I want to use loader to hide the image loading in the HTML. In index page I have used tabs view to show the product category and in every category, images are shown. So loading images is taking time and at first it shows all the product images of all categories which is not acceptable. I am talking about a section that is after slider.

Custom Point of Sale Displays

Wide Format printing

Digital small Format

Mailing

Kitting & Distribution with Online Tracking

                                        Corflute Signs

                                        Screen Board Signs

                                        Economy Pull Up Banners

                                        Door Hangers

                                        Business Cards

                                        Flyers

Body:
My first guess is that perhaps your client has not cleared his cache, and so is running old code. He can clear the cache by following these instructions.

If the above did not fix the problem:

This is a kludge, because I don't know your full HTML/javascript code, but:

Perhaps you can hide the section with the category images for a second or two, and then allow it to be displayed when appropriate:

 .sort-destination-loader.sort-destination-loader-showing{display:none;}

and in javascript:

setTimeout(function(){
    $('.sort-destination-loader.sort-destination-loader-showing').show();
},3000); //allow display after 3 seconds

If that works, then step-back the ,3000 until it is as short a delay as possible:

},500); //allow display after 1/2 second

Perhaps this would solve the problem temporarily while you are working on understanding the full problem?


问:
How to compute P values for increasing sample size using a loop?
I am having trouble creating a for loop.
I want to increase my sample size from 1 to 200 and calculate a p value after each newly added observation.
So that first I sample 1 observation - calculate first p value, then sample 2 observations - calculate second p value, then 3... up to 200 observations so that I get 200 p-values.

The observations will all be sampled from one column of a data frame (with replacing).

Lets say the column of the data frame is called data$column1.
The sample size increases by one in each "round" from 1:200.

How do I create a for loop so that for each "round", one more observation is being sampled and a new p value is being computed?
Finally I want to plot all p values.

```<code>n <- 1:200

for i in length(n) {
sample(data$column1,n, replace = TRUE)
pvalue <- t.test(data$column1, alternative = "greater")
}
</code>```

答:
Though I recognize you may want to use for loops, this is a good opportunity to use sapply or lapply. I'll demonstrate alternatives using iris. Though I'm going to use the simplified test of "not equal to 5" for iris$Sepal.Length for all samples, you should update alternative= and other arguments for your specific data.

Choice 1: if all you ever need is the p-value, we can capture just that ... or we can capture the whole model and do a second-stage retrieval of the p-values.

Choice 2: we can use one of the *apply functions, which reads well (once you get more accustomed to R vector code), or you can stick with the for loop. There are readability benefits of the first option, though you might be more comfortable with a for loop, in which case you should really pre-allocate the list/vector. (Reason for pre-defining a long but empty list/vector: while you can easily concatenate a vector out with out <- c(out, newstuff), doing this repeatedly is very inefficient in the long run. I highly discourage doing this in "large-ish scale".)

Up front, some notes:

I use set.seed(2) for each one so that the results are identical. You should not use it until/unless you need strict reproducibility. Typically not desired for production/academic reports.

I do seq_len instead of 2:length(...) because of habit patterns: when doing things programmatically, it's good to have it fail gracefully. If for some reason in your future you use 1:length(nrow(x)) and x turns out to have 0 rows, then 1:0 produces a vector of length 2, which is counter-intuitive (and will almost certainly break follow-on code). Instead, seq_len(0) produces a vector of length 2, which is a good thing. Again, less critical here, but a good habit to get into. (BTW: seq_along(0) still outputs a vector of length 1, so it is prone to this problem, too.)

I used seq_len(...)[-1] to discard the "1", because a t-test with a single datum cannot be done. One could also have done 1 + seq_len(nrow(x)-1).

1: for loop, p-value only

set.seed(2)
out <- rep(NA, nrow(iris))
for (i in seq_len(nrow(iris))[-1]) {
  thisdat <- sample(iris$Sepal.Length, size = i)
  out[i] <- t.test(thisdat, mu = 5)$p.value
}
summary(out)
#      Min.   1st Qu.    Median      Mean   3rd Qu.      Max.      NA's
# 0.0000000 0.0000000 0.0000000 0.0080013 0.0000001 0.4156151         1
```

<p>(You can assume that <code>out</code> is identical for all follow-on examples, so I won't show it.)</p>

<h2>2. <code>*apply</code>, p-value only</h2>

<pre class="lang-r prettyprint-override"><code>set.seed(2)
out <- sapply(seq_len(nrow(iris))[-1], function(i) {
  thisdat <- sample(iris$Sepal.Length, size = i)
  t.test(thisdat, mu = 5)$p.value
})
</code>```

sapply takes a vector and typically returns one of:

vector if all return values are perfectly length 1;

matrix if all return values are vectors of exactly the same length; or

list any other time.

Because of this, some programmers prefer lapply (which always returns a list) or vapply (for which you must declare what kind of return value you expect ... and it fails when something else pops up). One might do:

set.seed(2)
out <- vapply(seq_len(nrow(iris))[-1], function(i) {
  thisdat <- sample(iris$Sepal.Length, size = i)
  t.test(thisdat, mu = 5)$p.value
}, numeric(1))
```

<p>(Try changing <code>numeric(1)</code> to <code>numeric(2)</code> and you'll see the error of <code>values must be length 2, but FUN(X[[1]]) result is length 1</code>.)</p>

<p>For the <code>lapply</code> option, it is very similar to my fourth method, below.</p>

<p>Note that <code>length(out)</code> here will be <code>nrow(iris)-1</code>, because we skip it on the input vector of <code>seq_len(nrow(iris))[-1]</code>. This means that technically there will be a difference in <code>summary(out)</code>: there will not be the <code>NA</code>. All numbers are otherwise equal.</p>

<h2>3. <code>for</code> loop, full model</h2>

<p>Here, we need to store a lot more than just a single number, so we need to store it in the <code>list</code>.</p>

<pre class="lang-r prettyprint-override"><code>set.seed(2)
out <- vector("list", nrow(iris))
for (i in seq_len(nrow(iris))[-1]) {
  thisdat <- sample(iris$Sepal.Length, size = i)
  out[[i]] <- t.test(thisdat, mu = 5)
}
str(out[1:3])
# List of 3
#  $ : NULL
#  $ :List of 9
#   ..$ statistic  : Named num 1.31
#   .. ..- attr(*, "names")= chr "t"
#   ..$ parameter  : Named num 1
#   .. ..- attr(*, "names")= chr "df"
#   ..$ p.value    : num 0.416
#   ..$ conf.int   : num [1:2] -2.41 14.11
#   .. ..- attr(*, "conf.level")= num 0.95
#   ..$ estimate   : Named num 5.85
#   .. ..- attr(*, "names")= chr "mean of x"
#   ..$ null.value : Named num 5
#   .. ..- attr(*, "names")= chr "mean"
#   ..$ alternative: chr "two.sided"
#   ..$ method     : chr "One Sample t-test"
#   ..$ data.name  : chr "thisdat"
#   ..- attr(*, "class")= chr "htest"
#  $ :List of 9
#   ..$ statistic  : Named num 1.76
#   .. ..- attr(*, "names")= chr "t"
#   ..$ parameter  : Named num 2
#   .. ..- attr(*, "names")= chr "df"
#   ..$ p.value    : num 0.22
#   ..$ conf.int   : num [1:2] 3.61 8.33
#   .. ..- attr(*, "conf.level")= num 0.95
#   ..$ estimate   : Named num 5.97
#   .. ..- attr(*, "names")= chr "mean of x"
#   ..$ null.value : Named num 5
#   .. ..- attr(*, "names")= chr "mean"
#   ..$ alternative: chr "two.sided"
#   ..$ method     : chr "One Sample t-test"
#   ..$ data.name  : chr "thisdat"
#   ..- attr(*, "class")= chr "htest"
</code>```

The list is quite long, but you can see that (1) the first element is empty, not surprising since we skip i of 1; and (2) each of the elements after that contain everything you would expect a model to have.

Okay, let's walk through that. We first allocate the full list, and then run the for loop as we did before. The only difference in the loop is that we store the entire model (needing out[[i]] instead of out[i]) instead of just the $p.value. Now, to be able to get to the p-value, we can use a for loop or sapply, I'll demo the latter:

head(sapply(out[-1], `[[`, "p.value"))
# [1] 0.41561507 0.22019340 0.05766889 0.08544124 0.03243253 0.09059092

# more verbose, same thing though, showing the "anonymous-function" definition
head(sapply(out[-1], function(m) m$p.value))
```

<p>I used <code>out[-1]</code> because we know that the first one is empty. We could easily have done <code>out <- out[-1]</code> immediately after the <code>for</code> loop above.</p>

<p>One can grab any other property from the models, such as a model coefficient, by using the "anonymous-function" definition I demonstrated above.</p>

<h2>4. <code>*sapply</code>, full model</h2>

<p>This may not surprise you much.</p>

<pre class="lang-r prettyprint-override"><code>set.seed(2)
out <- lapply(seq_len(nrow(iris))[-1], function(i) {
  thisdat <- sample(iris$Sepal.Length, size = i)
  out[[i]] <- t.test(thisdat, mu = 5)
})
</code>```

If you look at these, the first element is not empty (similar to the sapply example above) because we didn't even run or pre-allocate for it.

One can then do whatever you want on individual list elements:

out[[1]]$p.value
# [1] 0.4156151

str(out[[17]])
# List of 9
#  $ statistic  : Named num 3.98
#   ..- attr(*, "names")= chr "t"
#  $ parameter  : Named num 17
#   ..- attr(*, "names")= chr "df"
#  $ p.value    : num 0.000974
#  $ conf.int   : num [1:2] 5.48 6.57
#   ..- attr(*, "conf.level")= num 0.95
#  $ estimate   : Named num 6.03
#   ..- attr(*, "names")= chr "mean of x"
#  $ null.value : Named num 5
#   ..- attr(*, "names")= chr "mean"
#  $ alternative: chr "two.sided"
#  $ method     : chr "One Sample t-test"
#  $ data.name  : chr "thisdat"
#  - attr(*, "class")= chr "htest"

out[[19]]$statistic
#        t
# 3.420489
```

<p>If you wanted to retrieve all test-statistics, similar to getting the p-values, you could just do:</p>

<pre class="lang-r prettyprint-override"><code>head(sapply(out, `[[`, "statistic"))
#        t        t        t        t        t        t
# 1.307692 1.761625 3.000000 2.273030 2.935307 2.014477
</code>```

Body:
I am having trouble creating a for loop.
I want to increase my sample size from 1 to 200 and calculate a p value after each newly added observation.
So that first I sample 1 observation - calculate first p value, then sample 2 observations - calculate second p value, then 3... up to 200 observations so that I get 200 p-values.

The observations will all be sampled from one column of a data frame (with replacing).

Lets say the column of the data frame is called data$column1.
The sample size increases by one in each "round" from 1:200.

How do I create a for loop so that for each "round", one more observation is being sampled and a new p value is being computed?
Finally I want to plot all p values.

n <- 1:200

for i in length(n) {
sample(data$column1,n, replace = TRUE)
pvalue <- t.test(data$column1, alternative = "greater")
}

Body:
Though I recognize you may want to use for loops, this is a good opportunity to use sapply or lapply. I'll demonstrate alternatives using iris. Though I'm going to use the simplified test of "not equal to 5" for iris$Sepal.Length for all samples, you should update alternative= and other arguments for your specific data.

Choice 1: if all you ever need is the p-value, we can capture just that ... or we can capture the whole model and do a second-stage retrieval of the p-values.

Choice 2: we can use one of the *apply functions, which reads well (once you get more accustomed to R vector code), or you can stick with the for loop. There are readability benefits of the first option, though you might be more comfortable with a for loop, in which case you should really pre-allocate the list/vector. (Reason for pre-defining a long but empty list/vector: while you can easily concatenate a vector out with out <- c(out, newstuff), doing this repeatedly is very inefficient in the long run. I highly discourage doing this in "large-ish scale".)

Up front, some notes:

I use set.seed(2) for each one so that the results are identical. You should not use it until/unless you need strict reproducibility. Typically not desired for production/academic reports.

I do seq_len instead of 2:length(...) because of habit patterns: when doing things programmatically, it's good to have it fail gracefully. If for some reason in your future you use 1:length(nrow(x)) and x turns out to have 0 rows, then 1:0 produces a vector of length 2, which is counter-intuitive (and will almost certainly break follow-on code). Instead, seq_len(0) produces a vector of length 2, which is a good thing. Again, less critical here, but a good habit to get into. (BTW: seq_along(0) still outputs a vector of length 1, so it is prone to this problem, too.)

I used seq_len(...)[-1] to discard the "1", because a t-test with a single datum cannot be done. One could also have done 1 + seq_len(nrow(x)-1).

1: for loop, p-value only

set.seed(2)
out <- rep(NA, nrow(iris))
for (i in seq_len(nrow(iris))[-1]) {
  thisdat <- sample(iris$Sepal.Length, size = i)
  out[i] <- t.test(thisdat, mu = 5)$p.value
}
summary(out)
#      Min.   1st Qu.    Median      Mean   3rd Qu.      Max.      NA's
# 0.0000000 0.0000000 0.0000000 0.0080013 0.0000001 0.4156151         1

(You can assume that out is identical for all follow-on examples, so I won't show it.)

2. *apply, p-value only

set.seed(2)
out <- sapply(seq_len(nrow(iris))[-1], function(i) {
  thisdat <- sample(iris$Sepal.Length, size = i)
  t.test(thisdat, mu = 5)$p.value
})

sapply takes a vector and typically returns one of:

vector if all return values are perfectly length 1;

matrix if all return values are vectors of exactly the same length; or

list any other time.

Because of this, some programmers prefer lapply (which always returns a list) or vapply (for which you must declare what kind of return value you expect ... and it fails when something else pops up). One might do:

set.seed(2)
out <- vapply(seq_len(nrow(iris))[-1], function(i) {
  thisdat <- sample(iris$Sepal.Length, size = i)
  t.test(thisdat, mu = 5)$p.value
}, numeric(1))

(Try changing numeric(1) to numeric(2) and you'll see the error of values must be length 2, but FUN(X[[1]]) result is length 1.)

For the lapply option, it is very similar to my fourth method, below.

Note that length(out) here will be nrow(iris)-1, because we skip it on the input vector of seq_len(nrow(iris))[-1]. This means that technically there will be a difference in summary(out): there will not be the NA. All numbers are otherwise equal.

3. for loop, full model

Here, we need to store a lot more than just a single number, so we need to store it in the list.

set.seed(2)
out <- vector("list", nrow(iris))
for (i in seq_len(nrow(iris))[-1]) {
  thisdat <- sample(iris$Sepal.Length, size = i)
  out[[i]] <- t.test(thisdat, mu = 5)
}
str(out[1:3])
# List of 3
#  $ : NULL
#  $ :List of 9
#   ..$ statistic  : Named num 1.31
#   .. ..- attr(*, "names")= chr "t"
#   ..$ parameter  : Named num 1
#   .. ..- attr(*, "names")= chr "df"
#   ..$ p.value    : num 0.416
#   ..$ conf.int   : num [1:2] -2.41 14.11
#   .. ..- attr(*, "conf.level")= num 0.95
#   ..$ estimate   : Named num 5.85
#   .. ..- attr(*, "names")= chr "mean of x"
#   ..$ null.value : Named num 5
#   .. ..- attr(*, "names")= chr "mean"
#   ..$ alternative: chr "two.sided"
#   ..$ method     : chr "One Sample t-test"
#   ..$ data.name  : chr "thisdat"
#   ..- attr(*, "class")= chr "htest"
#  $ :List of 9
#   ..$ statistic  : Named num 1.76
#   .. ..- attr(*, "names")= chr "t"
#   ..$ parameter  : Named num 2
#   .. ..- attr(*, "names")= chr "df"
#   ..$ p.value    : num 0.22
#   ..$ conf.int   : num [1:2] 3.61 8.33
#   .. ..- attr(*, "conf.level")= num 0.95
#   ..$ estimate   : Named num 5.97
#   .. ..- attr(*, "names")= chr "mean of x"
#   ..$ null.value : Named num 5
#   .. ..- attr(*, "names")= chr "mean"
#   ..$ alternative: chr "two.sided"
#   ..$ method     : chr "One Sample t-test"
#   ..$ data.name  : chr "thisdat"
#   ..- attr(*, "class")= chr "htest"

The list is quite long, but you can see that (1) the first element is empty, not surprising since we skip i of 1; and (2) each of the elements after that contain everything you would expect a model to have.

Okay, let's walk through that. We first allocate the full list, and then run the for loop as we did before. The only difference in the loop is that we store the entire model (needing out[[i]] instead of out[i]) instead of just the $p.value. Now, to be able to get to the p-value, we can use a for loop or sapply, I'll demo the latter:

head(sapply(out[-1], `[[`, "p.value"))
# [1] 0.41561507 0.22019340 0.05766889 0.08544124 0.03243253 0.09059092

# more verbose, same thing though, showing the "anonymous-function" definition
head(sapply(out[-1], function(m) m$p.value))

I used out[-1] because we know that the first one is empty. We could easily have done out <- out[-1] immediately after the for loop above.

One can grab any other property from the models, such as a model coefficient, by using the "anonymous-function" definition I demonstrated above.

4. *sapply, full model

This may not surprise you much.

set.seed(2)
out <- lapply(seq_len(nrow(iris))[-1], function(i) {
  thisdat <- sample(iris$Sepal.Length, size = i)
  out[[i]] <- t.test(thisdat, mu = 5)
})

If you look at these, the first element is not empty (similar to the sapply example above) because we didn't even run or pre-allocate for it.

One can then do whatever you want on individual list elements:

out[[1]]$p.value
# [1] 0.4156151

str(out[[17]])
# List of 9
#  $ statistic  : Named num 3.98
#   ..- attr(*, "names")= chr "t"
#  $ parameter  : Named num 17
#   ..- attr(*, "names")= chr "df"
#  $ p.value    : num 0.000974
#  $ conf.int   : num [1:2] 5.48 6.57
#   ..- attr(*, "conf.level")= num 0.95
#  $ estimate   : Named num 6.03
#   ..- attr(*, "names")= chr "mean of x"
#  $ null.value : Named num 5
#   ..- attr(*, "names")= chr "mean"
#  $ alternative: chr "two.sided"
#  $ method     : chr "One Sample t-test"
#  $ data.name  : chr "thisdat"
#  - attr(*, "class")= chr "htest"

out[[19]]$statistic
#        t
# 3.420489

If you wanted to retrieve all test-statistics, similar to getting the p-values, you could just do:

head(sapply(out, `[[`, "statistic"))
#        t        t        t        t        t        t
# 1.307692 1.761625 3.000000 2.273030 2.935307 2.014477


问:
Problem when trying to plot two histograms using fill aesthetic
I've been trying to plot two histograms by using the fill aesthetic and a specific column with two levels. However, instead of displaying both desired histograms, my code displays one histogram with the whole data and another only for the second classification. I don't know if there is a problem in my syntax neither if this is some kind of tricky issue.

```<code>    library(tidyverse)

    db1 <- data.frame(type=rep("A",100),val=rnorm(n=100,mean=50,sd=10))
    db2 <- data.frame(type=rep("B",150),val=rnorm(n=150,mean=50,sd=10))
    dbf <- bind_rows(db1,db2)

    P1 <- ggplot(db1, aes(x=val)) + geom_histogram()
    P2 <- ggplot(db2, aes(x=val)) + geom_histogram()
    PF <- ggplot(dbf, aes(x=val)) + geom_histogram()
</code>```

I want to get this, P1 and P2

```<code>ggplot(db1, aes(x=val)) + geom_histogram(fill="red", alpha=0.5) + geom_histogram(data=db2, aes(x=val),fill="green", alpha=0.5)
</code>```

What I want

But the code I think should work, P1 and P2 with the fill aesthetic for column val

```<code>ggplot(dbf, aes(x=val)) + geom_histogram(aes(fill=type), alpha=0.5)
</code>```

My code

Produces the combination of PF and P2

```<code>ggplot(dbf, aes(x=val)) + geom_histogram(fill="red", alpha=0.5) + geom_histogram(data=db2, aes(x=val),fill="green", alpha=0.5)
</code>```

What I get

Any help or idea will be highly appreciated!

答:
All you need is to pass position = "identity" to your geom_histogram function.

```<code>library(tidyverse)
library(ggplot2)

db1 <- data.frame(type=rep("A",100),val=rnorm(n=100,mean=50,sd=10))
db2 <- data.frame(type=rep("B",150),val=rnorm(n=150,mean=50,sd=10))
dbf <- bind_rows(db1,db2)

ggplot(dbf, aes(x=val, fill = type)) + geom_histogram(alpha=0.5, position = "identity")
</code>```

Body:
I've been trying to plot two histograms by using the fill aesthetic and a specific column with two levels. However, instead of displaying both desired histograms, my code displays one histogram with the whole data and another only for the second classification. I don't know if there is a problem in my syntax neither if this is some kind of tricky issue.

    library(tidyverse)

    db1 <- data.frame(type=rep("A",100),val=rnorm(n=100,mean=50,sd=10))
    db2 <- data.frame(type=rep("B",150),val=rnorm(n=150,mean=50,sd=10))
    dbf <- bind_rows(db1,db2)

    P1 <- ggplot(db1, aes(x=val)) + geom_histogram()
    P2 <- ggplot(db2, aes(x=val)) + geom_histogram()
    PF <- ggplot(dbf, aes(x=val)) + geom_histogram()

I want to get this, P1 and P2

ggplot(db1, aes(x=val)) + geom_histogram(fill="red", alpha=0.5) + geom_histogram(data=db2, aes(x=val),fill="green", alpha=0.5)

What I want

But the code I think should work, P1 and P2 with the fill aesthetic for column val

ggplot(dbf, aes(x=val)) + geom_histogram(aes(fill=type), alpha=0.5)

My code

Produces the combination of PF and P2

ggplot(dbf, aes(x=val)) + geom_histogram(fill="red", alpha=0.5) + geom_histogram(data=db2, aes(x=val),fill="green", alpha=0.5)

What I get

Any help or idea will be highly appreciated!

Body:
All you need is to pass position = "identity" to your geom_histogram function.

library(tidyverse)
library(ggplot2)

db1 <- data.frame(type=rep("A",100),val=rnorm(n=100,mean=50,sd=10))
db2 <- data.frame(type=rep("B",150),val=rnorm(n=150,mean=50,sd=10))
dbf <- bind_rows(db1,db2)

ggplot(dbf, aes(x=val, fill = type)) + geom_histogram(alpha=0.5, position = "identity")


问:
Aws Sdk 2.12.3 TransferService Usage
We were using version 2.4.2 of Amazon SDK for file upload and downloads. Recently we updated it to 2.12.3.

In older versions, any upload or download task used to start TransferService internally in the background which handled network connectivity monitoring among other things.

But to support Android 8 optimizations of limiting background services, in the latest version, the SDK has stopped calling TransferService internally and encourages the developer to call it explicitly. One recommended place to call the service being Application class's onCreate. TransferService has been reduced to merely being an initializer for another class TransferNetworkLossHandler which extends BroadcastReceiver which handles pause/resume of downloads in case of connectivity changes.
One major difference in starting TransferService in older and newer SDK is that earlier it was started using startService method. But now Amazon docs recommend starting with "startForegroundService" with a Notification object on 8.0 device and above.

Our app uploads debugging logs every night in the background irrespective of whether the app is being used or not at that time. After the SDK update, we compulsorily have to set up a notification while TransferService is running on Oreo devices. We want to use Aws SDK to upload logs but do not want to show a notification as we feel it will give a bad experience to our users. Calling just startService without a notification object will work when the app is being started by the user. But when the app is not running or not in memory, our upload log task is triggered which calls Application class's onCreate which in turn calls startService which causes a crash as startService cannot be called when the app is in the background.

To avoid this, we tried to bypass the use of TransferService and initializing TransferNetworkLossHandler ourselves in Application class. This seems to work when the app is in use or in memory. But if we swipe out the app, log upload doesn't work when called in the background. Logs aren't helpful either. There are no error logs and we are getting proper observer ids but the files aren't being uploaded to the bucket.

We are using the following code to bypass TransferService and initialize TransferNetworkLossHandler in Application class's onCreate.

```<code>TransferNetworkLossHandler.getInstance(getApplicationContext());
</code>```

and to initiate a dummy network check after initialization, we use

```<code>TransferNetworkLossHandler.getInstance(getApplicationContext()).onReceive(context, new Intent().setAction(ConnectivityManager.CONNECTIVITY_ACTION));
</code>```

so that based on network connectivity, downloads can be paused or resumed by the SDK.

Is there any way we can use Amazon SDK to upload/download without using notification on 8.0 and above devices?.

Also, any links related to best practices for such use cases is highly appreciated.

答:
```<code>registerReceiver(TransferNetworkLossHandler.getInstance(getApplicationContext()), new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
</code>```

I put this code in my Application class or in the activity I need to listen for network updates.

I had a problem in which when I was offline, my uploads would hang in WAITING_FOR_NETWORK state and never resume. Now it works fine.

Source:
https://github.com/aws-amplify/aws-sdk-android/issues/899

Title: Aws Sdk 2.12.3 TransferService Usage

Body:
We were using version 2.4.2 of Amazon SDK for file upload and downloads. Recently we updated it to 2.12.3.

In older versions, any upload or download task used to start TransferService internally in the background which handled network connectivity monitoring among other things.

But to support Android 8 optimizations of limiting background services, in the latest version, the SDK has stopped calling TransferService internally and encourages the developer to call it explicitly. One recommended place to call the service being Application class's onCreate. TransferService has been reduced to merely being an initializer for another class TransferNetworkLossHandler which extends BroadcastReceiver which handles pause/resume of downloads in case of connectivity changes.
One major difference in starting TransferService in older and newer SDK is that earlier it was started using startService method. But now Amazon docs recommend starting with "startForegroundService" with a Notification object on 8.0 device and above.

Our app uploads debugging logs every night in the background irrespective of whether the app is being used or not at that time. After the SDK update, we compulsorily have to set up a notification while TransferService is running on Oreo devices. We want to use Aws SDK to upload logs but do not want to show a notification as we feel it will give a bad experience to our users. Calling just startService without a notification object will work when the app is being started by the user. But when the app is not running or not in memory, our upload log task is triggered which calls Application class's onCreate which in turn calls startService which causes a crash as startService cannot be called when the app is in the background.

To avoid this, we tried to bypass the use of TransferService and initializing TransferNetworkLossHandler ourselves in Application class. This seems to work when the app is in use or in memory. But if we swipe out the app, log upload doesn't work when called in the background. Logs aren't helpful either. There are no error logs and we are getting proper observer ids but the files aren't being uploaded to the bucket.

We are using the following code to bypass TransferService and initialize TransferNetworkLossHandler in Application class's onCreate.

TransferNetworkLossHandler.getInstance(getApplicationContext());

and to initiate a dummy network check after initialization, we use

TransferNetworkLossHandler.getInstance(getApplicationContext()).onReceive(context, new Intent().setAction(ConnectivityManager.CONNECTIVITY_ACTION));

so that based on network connectivity, downloads can be paused or resumed by the SDK.

Is there any way we can use Amazon SDK to upload/download without using notification on 8.0 and above devices?.

Also, any links related to best practices for such use cases is highly appreciated.

Body:
registerReceiver(TransferNetworkLossHandler.getInstance(getApplicationContext()), new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

I put this code in my Application class or in the activity I need to listen for network updates.

I had a problem in which when I was offline, my uploads would hang in WAITING_FOR_NETWORK state and never resume. Now it works fine.

Source:
https://github.com/aws-amplify/aws-sdk-android/issues/899


问:
How to return diff data from an Ansible action plugin
I'm writing an Ansible module implemented as an action plugin, similar to the Template module and plugin provided with the core of Ansible. I'd like to return diff data with before and after lines as a module would do. I can find examples of how to return this data from an actual module, but I'm stuck trying to extrapolate how to associate the same information with the return from an action plugin.

In the lineinfile module, diff data is returned as the diff keyword parameter in the call to module.exit_json(), like so:

module.exit_json(changed=changed, msg=msg, backup=backupdest, diff=difflist)
```

However, it appears that no plug-ins ever call exit_json(), nor could they, because they don't have a module data structure to work with.

The exit_json() method on module appears to be defined on line 2042 of module_utils/basic.py It calls, in turn, self._return_formatted() on line 2007, which appears to echo kwargs (after some clean-up) to stdout. So . . . just add a diff keyword to the existing result structure? I'll play with that.

答:
Yes, adding a diff keyword and value to the existing result dict returned from the plugin appears to be sufficient. Here is an incomplete, minimalist example:

class ActionModule(ActionBase):
    def run(self, tmp=None, task_vars=None):

        diff = {'before': 'old data\n',
                'after': 'new data\n'}

        result['diff'] = diff
        result['changed'] = True

        return result
```

Body:
I'm writing an Ansible module implemented as an action plugin, similar to the Template module and plugin provided with the core of Ansible. I'd like to return diff data with before and after lines as a module would do. I can find examples of how to return this data from an actual module, but I'm stuck trying to extrapolate how to associate the same information with the return from an action plugin.

In the lineinfile module, diff data is returned as the diff keyword parameter in the call to module.exit_json(), like so:

module.exit_json(changed=changed, msg=msg, backup=backupdest, diff=difflist)

However, it appears that no plug-ins ever call exit_json(), nor could they, because they don't have a module data structure to work with.

The exit_json() method on module appears to be defined on line 2042 of module_utils/basic.py It calls, in turn, self._return_formatted() on line 2007, which appears to echo kwargs (after some clean-up) to stdout. So . . . just add a diff keyword to the existing result structure? I'll play with that.


问:
how i can make a function that they update the content when user on the bottom of page ? jQuery
Like google reader and many other applicaton i want to make a function who update the page using ajax request.

means when user on the bottom of page then i send the request and append response to the exisitng content of page.

how i can do that in jQuery

答:
What you are looking for is "infinite scrolling".

http://www.infinite-scroll.com/infinite-scroll-jquery-plugin/

OwnerDisplayName: delete my account


问:
How to introduce new index values in a data frame?
I have the following dataframe, which the print(df_74034.head(10))is:

```<code>                          HumExamRoom                      HumTechRoom Machine  TempExamRoom TempTechRoom
                                   NaN  2017-08-18\t09:22:33\t65.9   74034           NaN          NaN
                                   NaN  2017-10-03\t11:08:26\t60.5   74034           NaN          NaN
2018-02-17\t01:45:24          NaN                             69.7   74034           NaN          NaN
2018-02-17\t01:45:55          NaN                             67.5   74034           NaN          NaN
2018-02-17\t01:46:29          NaN                             65.4   74034           NaN          NaN
2018-02-17\t01:47:20          NaN                             63.3   74034           NaN          NaN
2018-02-17\t01:48:35          NaN                             61.3   74034           NaN          NaN
2018-02-17\t01:49:08          NaN                             63.4   74034           NaN          NaN
2018-02-17\t01:49:31          NaN                             65.5   74034           NaN          NaN
2018-02-17\t01:49:55          NaN                             67.6   74034           NaN          NaN
</code>```

(The first two rows got a little messy)
As you can see, the first two cells in the index have no values at all because their values are in the second column, which is probably a fault of my code - which I don't want to change anymore. Therefore, I would like to introduce the values 2017-08-18\t09:22:33\t and `2017-08-18\t09:22:33\t' in the index cells, respectively, and sort it. In order to sort I also have to change it to its correct date/time format.

I've already tried df_74034.index.insert(0, '2017-08-18\t09:22:33') but it didn't work. I appretiate for the help!

答:
You can perform it in other way -

df = dataframe name which in your case is df_74034.

You may try df.reset_index() which will place the current index values with integer number and will create column of your existing index value.

Create a new column of the values you want to set as index. Lets say name of the column is ABC

Then, you can use df.set_index('ABC',inplace=True) which will create a new index with values those are in ABC column.

I hope it may be helpful to some extend.

Body:
I have the following dataframe, which the print(df_74034.head(10))is:

                          HumExamRoom                      HumTechRoom Machine  TempExamRoom TempTechRoom
                                   NaN  2017-08-18\t09:22:33\t65.9   74034           NaN          NaN
                                   NaN  2017-10-03\t11:08:26\t60.5   74034           NaN          NaN
2018-02-17\t01:45:24          NaN                             69.7   74034           NaN          NaN
2018-02-17\t01:45:55          NaN                             67.5   74034           NaN          NaN
2018-02-17\t01:46:29          NaN                             65.4   74034           NaN          NaN
2018-02-17\t01:47:20          NaN                             63.3   74034           NaN          NaN
2018-02-17\t01:48:35          NaN                             61.3   74034           NaN          NaN
2018-02-17\t01:49:08          NaN                             63.4   74034           NaN          NaN
2018-02-17\t01:49:31          NaN                             65.5   74034           NaN          NaN
2018-02-17\t01:49:55          NaN                             67.6   74034           NaN          NaN

(The first two rows got a little messy)
As you can see, the first two cells in the index have no values at all because their values are in the second column, which is probably a fault of my code - which I don't want to change anymore. Therefore, I would like to introduce the values 2017-08-18\t09:22:33\t and `2017-08-18\t09:22:33\t' in the index cells, respectively, and sort it. In order to sort I also have to change it to its correct date/time format.

I've already tried df_74034.index.insert(0, '2017-08-18\t09:22:33') but it didn't work. I appretiate for the help!


问:
Is there a function to convert hex color code text to a square in CSS with that color?
I need to convert a bunch of text with hex color code (eg #fff) into squares/thumbs with that color (a div with a CSS style).

Is there a jQuery function (or similar) to achieve this?

Thank you

答:
There is not an ready to use function in jQuery for that task, but it is simple to archive something like you described with the tools provided by jQuery:

function createColorSquares(colors) {
  for (let color of colors) {
    let square = $('', { class: 'colorSquare' }).css('background-color', color);
    $('body').append(square);
  }
}

let myColors = ['#f00', '#ff0', '#f0f', '#0ff'];
createColorSquares(myColors);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.colorSquare {
  display: inline-block;
  width: 16px;
  height: 16px;
  margin: 4px;
}</code>```

```

Body:
There is not an ready to use function in jQuery for that task, but it is simple to archive something like you described with the tools provided by jQuery:

function createColorSquares(colors) {
  for (let color of colors) {
    let square = $('<span>', { class: 'colorSquare' }).css('background-color', color);
    $('body').append(square);
  }
}

let myColors = ['#f00', '#ff0', '#f0f', '#0ff'];
createColorSquares(myColors);

.colorSquare {
  display: inline-block;
  width: 16px;
  height: 16px;
  margin: 4px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>


问:
Cannot change theme dynamically
I'm trying to change the theme of an app dynamically. But I can change it only when the app is alive. Means, when I kill the app and open it again, the default theme is applied.

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {
        public ArrayList<FTPFile> listfile=null;
        Intent men;
        @Override
        protected void onCreate(Bundle savedInstanceState) {

            SharedPreferences preferences=getSharedPreferences("ThemePreferences",MODE_PRIVATE);
            String choice=preferences.getString("CurrentTheme",null);

                Toast.makeText(getApplicationContext(),"Its"+ choice,Toast.LENGTH_SHORT).show();
           if(choice=="Light")
               this.setTheme(R.style.AppThemeLight);
           else
               this.setTheme(R.style.AppTheme);
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
}
</code>```

AndroidManifest.xml

```<code><application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"

    tools:ignore="GoogleAppIndexingWarning">
    <activity android:name=".MainActivity"  android:theme="@style/AppTheme">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".file_explorer"  android:theme="@style/AppTheme" />
    <activity android:name=".settings"  android:theme="@style/AppTheme" />
</application>
</code>```

Code that changes value to shared preferences

```<code>SharedPreferences preferences=getSharedPreferences("ThemePreferences",MODE_PRIVATE);
Editor editor=preferences.edit();
 RadioGroup rg=findViewById(R.id.radgrp);
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId)
                {
                    case R.id.light:
                        Log.d("MRR","Light");
                        editor.putString("CurrentTheme","Light");
                        editor.apply();
                        break;
                    case R.id.dark:
                        Log.d("MRR","Dark");
                        editor.putString("CurrentTheme","Dark");
                        editor.apply();
                }
            }
        });
</code>```

答:
I found the answer by myself!
I dont know how but I changed this

```<code>editor.putString("CurrentTheme","Light");
                        editor.apply();
</code>```

to this,

```<code>editor.putBoolean("CurrentTheme",true);
                        editor.apply();
</code>```

Title: Cannot change theme dynamically

Body:
I'm trying to change the theme of an app dynamically. But I can change it only when the app is alive. Means, when I kill the app and open it again, the default theme is applied.

MainActivity.java

public class MainActivity extends AppCompatActivity {
        public ArrayList<FTPFile> listfile=null;
        Intent men;
        @Override
        protected void onCreate(Bundle savedInstanceState) {

            SharedPreferences preferences=getSharedPreferences("ThemePreferences",MODE_PRIVATE);
            String choice=preferences.getString("CurrentTheme",null);

                Toast.makeText(getApplicationContext(),"Its"+ choice,Toast.LENGTH_SHORT).show();
           if(choice=="Light")
               this.setTheme(R.style.AppThemeLight);
           else
               this.setTheme(R.style.AppTheme);
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
}

AndroidManifest.xml

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"

    tools:ignore="GoogleAppIndexingWarning">
    <activity android:name=".MainActivity"  android:theme="@style/AppTheme">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".file_explorer"  android:theme="@style/AppTheme" />
    <activity android:name=".settings"  android:theme="@style/AppTheme" />
</application>

Code that changes value to shared preferences

SharedPreferences preferences=getSharedPreferences("ThemePreferences",MODE_PRIVATE);
Editor editor=preferences.edit();
 RadioGroup rg=findViewById(R.id.radgrp);
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId)
                {
                    case R.id.light:
                        Log.d("MRR","Light");
                        editor.putString("CurrentTheme","Light");
                        editor.apply();
                        break;
                    case R.id.dark:
                        Log.d("MRR","Dark");
                        editor.putString("CurrentTheme","Dark");
                        editor.apply();
                }
            }
        });

Body:
I found the answer by myself!
I dont know how but I changed this

editor.putString("CurrentTheme","Light");
                        editor.apply();

to this,

editor.putBoolean("CurrentTheme",true);
                        editor.apply();


问:
SSL3 Certificate Verify Failed when Connecting to JIRA API Using Python
I'm currently running into an error when attempting to connect to JIRA using Python2.7 and the JIRA REST API (http://jira-python.readthedocs.org/en/latest/).

When I execute the following:

```<code>from jira.client import JIRA

options = {
    'server': 'https://jira.companyname.com'
}
jira = JIRA(options)
</code>```

I get the following error message in console:

```<code>requests.exceptions.SSLError: [Errno 1] _ssl.c:507: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
</code>```

Is there something that I may have missed or am doing incorrectly?

Thanks!

答:
On Windows system please do the following:-

Go to the website using google chrome, then click on Lock button.

Now click on certificate, a new window pops up.

Next click on Certification Path, select first option from list which will be root, then select View Certificate, another window pops up.

Go to Details tab, click on Copy To File. Then click on Next, select Base-64 encoded x509.(CER) radio button, click on Next and save the .cer file locally.

Once the .cer file is obtained, add it to the python script as follows:-

```<code>jira_options = {
    'server': jira_server_name,
    'verify': 'path_to_directory_containing_certificate_file/certificate.cer'
}
</code>```

This should work without any security warnings.

Body:
I'm currently running into an error when attempting to connect to JIRA using Python2.7 and the JIRA REST API (http://jira-python.readthedocs.org/en/latest/).

When I execute the following:

from jira.client import JIRA

options = {
    'server': 'https://jira.companyname.com'
}
jira = JIRA(options)

I get the following error message in console:

requests.exceptions.SSLError: [Errno 1] _ssl.c:507: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

Is there something that I may have missed or am doing incorrectly?

Thanks!

Body:
On Windows system please do the following:-

Go to the website using google chrome, then click on Lock button.

Now click on certificate, a new window pops up.

Next click on Certification Path, select first option from list which will be root, then select View Certificate, another window pops up.

Go to Details tab, click on Copy To File. Then click on Next, select Base-64 encoded x509.(CER) radio button, click on Next and save the .cer file locally.

Once the .cer file is obtained, add it to the python script as follows:-

jira_options = {
    'server': jira_server_name,
    'verify': 'path_to_directory_containing_certificate_file/certificate.cer'
}

This should work without any security warnings.