问:
iOS recorded video is not playing in android device?

I am using react-native camera to record video.

Its play in iOS but not play in android

Extension is : .mov for iOS and .mp4 for android

<Video source={{uri:videoUri}} type="mp4"/>```

答:
Please use below code,</p>

```<code>import {Platform} from 'react-native';

<Video source={{uri:videoUri}} type=Platform.OS === 'ios'? "mov" : "mp4" />
</code>```

Body:
Please use below code,

import {Platform} from 'react-native';

<Video source={{uri:videoUri}} type=Platform.OS === 'ios'? "mov" : "mp4" />


来源: stackexchange

问:
Sending emails from google sheet with my outlook email
So I have an google script for a sheet where a I send emails to customers inside of the google sheet however now the emails come from my gmail adress and I would like to send it from my outlook email, is this possible?
Best regards, Jesper </p>

答:
You can add the Outlook email address as an alias in your main Gmail account. Next, when sending the email using the GmailApp or MailApp service of Apps Script, specify the alias in the sendEmail option as below.

```<code> GmailApp.sendEmail(to, subject, textBody, {
   from: "alias@outlook.com",
   name: "Your name"
 });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can add the Outlook email address as an alias in your main Gmail account. Next, when sending the email using the GmailApp or MailApp service of Apps Script, specify the alias in the sendEmail option as below.

 GmailApp.sendEmail(to, subject, textBody, {
   from: "alias@outlook.com",
   name: "Your name"
 });


问:
NotSupportedexception thrown for Isolated storage MVVM Silverlight
I am using Silverlight MVVM and IsolatedStorageSettings.SiteSettings for session  management. Everything is working fine and i am able to read the data in the next page , but design view is giving error as NotSupportedException.

P.S. : I am storing one single value and bot my view and view model are in different project.

答:
I got the solution at last....

Main reason was that the designer was searching for the Isolated Storage at design time, thats why only the designer was giving the error and other things were working fine.
What was needed was to put an if block when declaring and storing isolated storage in the code,  this if block will check if the application is in design time.

Hope this help others too...

ContentLicense: CC BY-SA 3.0


问:
passing the values through parameters in python list function
I'm starting to learn list.append by passing a string to the parameter in the function, However I'm getting an error, how can I solve this issue?

Here's my code:

def add_more(name):
    name.append(5)

name=[1,2,3,4]
print add_more(name)
```

答:
While the variable name does get altered as a pass by reference, if you're going to print it out, you'll need to add a return statement to your function</p>

```<code>def add_more(name):
    name.append(5)
    return name

name=[1,2,3,4]
print add_more(name)
</code>```

Body:
While the variable name does get altered as a pass by reference, if you're going to print it out, you'll need to add a return statement to your function

def add_more(name):
    name.append(5)
    return name

name=[1,2,3,4]
print add_more(name)


问:
Orchestrate execution of several Jenkinsfile using only declarative syntax
Is it possible to, from a Jenkinsfile, orchestrate the execution of another Jenkinsfile using for all of them declarative syntax?

I mean, I would like to have a Jenkinsfile like this one (to which I refer as the 'orchestrator'):

```<code>pipeline {
    agent any
    stages {
        stage('Invoke another Jenkinsfile') {
            ... code here to invoke folder1/Jenkinsfile ...
        }
    }
}
</code>```

The folder1/Jenkinsfile will be a regular Jenkinsfile like this one:

```<code>pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                echo 'Hello World'
            }
        }
    }
}
</code>```

As you might have guessed, the file structure of this example will be:

```<code>folder1
│   └── Jenkinsfile
└── Jenkinfile //this will be the 'orchestrator'
</code>```

How can I achieve this? Could you help me figuring out the code that should contain the orchestrator to invoke the other Jenkinsfile?

I expect a serial & sync process in which the orchestrator waits till the folder1/Jenkinsfile execution is finished to mark the step 'Invoke another Jenkinsfile' as green and then proceed with the remaining steps.

Thanks in advance!

答:
I have never tried to load an actual ".jenkinsfile" but I have made that with groovy scripts, which is what a jenkinsfile is in the end. I have made so like this:

```<code>   def outsider = load "outsider.groovy"
</code>```

As can be seen here: https://jenkins.io/doc/pipeline/steps/workflow-cps/

Body:
Is it possible to, from a Jenkinsfile, orchestrate the execution of another Jenkinsfile using for all of them declarative syntax?

I mean, I would like to have a Jenkinsfile like this one (to which I refer as the 'orchestrator'):

pipeline {
    agent any
    stages {
        stage('Invoke another Jenkinsfile') {
            ... code here to invoke folder1/Jenkinsfile ...
        }
    }
}

The folder1/Jenkinsfile will be a regular Jenkinsfile like this one:

pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                echo 'Hello World'
            }
        }
    }
}

As you might have guessed, the file structure of this example will be:

folder1
│   └── Jenkinsfile
└── Jenkinfile //this will be the 'orchestrator'

How can I achieve this? Could you help me figuring out the code that should contain the orchestrator to invoke the other Jenkinsfile?

I expect a serial & sync process in which the orchestrator waits till the folder1/Jenkinsfile execution is finished to mark the step 'Invoke another Jenkinsfile' as green and then proceed with the remaining steps.

Thanks in advance!

Body:
I have never tried to load an actual ".jenkinsfile" but I have made that with groovy scripts, which is what a jenkinsfile is in the end. I have made so like this:

   def outsider = load "outsider.groovy"

As can be seen here: https://jenkins.io/doc/pipeline/steps/workflow-cps/


问:
How to replace variable in user input with math operation?
I need replace variable in string from user. For example:

User input: Ssad asdsdqwdq jdiqwj diqw jd qwld j {price-40%} asd asd asd

I know how replace only {price} but I don't know how to replace other cases.

I need support these cases:

```<code>{price}
{price-xx%}
{price+xx%}
{price-xx}
{price+xx}
{price/xx}
{price*xx}
</code>```

And user can use variable {price} many times.

After user submit text, my app replace variable {price} or calc {price-xx%} and create a new string.

答:
https://github.com/davideicardi/DynamicExpresso/</p>

```<code>static void Main(string[] args)
{
    int price = 100;

    Regex regex = new Regex(@"(?<=\{).*?(?=\})");

    string userInput = "Hi. I want to buy your computer. I can't offer {price} USD, but I can offer {price-(price/100)*10} USD";

    string text = userInput;

    foreach (var item in regex.Matches(text))
    {
        string expression = item.ToString().Replace("price", price.ToString());
        var interpreter = new Interpreter();
        var result = interpreter.Eval(expression);
        text = regex.Replace(text, result.ToString(),1);
        text = ReplaceFirst(text, "{", string.Empty);
        text = ReplaceFirst(text, "}", string.Empty);
    }

    Console.WriteLine("Result: " + text);
}

public static string ReplaceFirst(string text, string search, string replace)
{
    int pos = text.IndexOf(search);

    if (pos < 0)
    {
        return text;
    }

    return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
}
</code>```

Body:
I need replace variable in string from user. For example:

User input: Ssad asdsdqwdq jdiqwj diqw jd qwld j {price-40%} asd asd asd

I know how replace only {price} but I don't know how to replace other cases.

I need support these cases:

{price}
{price-xx%}
{price+xx%}
{price-xx}
{price+xx}
{price/xx}
{price*xx}

And user can use variable {price} many times.

After user submit text, my app replace variable {price} or calc {price-xx%} and create a new string.

Body:
https://github.com/davideicardi/DynamicExpresso/

static void Main(string[] args)
{
    int price = 100;

    Regex regex = new Regex(@"(?<=\{).*?(?=\})");

    string userInput = "Hi. I want to buy your computer. I can't offer {price} USD, but I can offer {price-(price/100)*10} USD";

    string text = userInput;

    foreach (var item in regex.Matches(text))
    {
        string expression = item.ToString().Replace("price", price.ToString());
        var interpreter = new Interpreter();
        var result = interpreter.Eval(expression);
        text = regex.Replace(text, result.ToString(),1);
        text = ReplaceFirst(text, "{", string.Empty);
        text = ReplaceFirst(text, "}", string.Empty);
    }

    Console.WriteLine("Result: " + text);
}

public static string ReplaceFirst(string text, string search, string replace)
{
    int pos = text.IndexOf(search);

    if (pos < 0)
    {
        return text;
    }

    return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
}


问:
WebGL 2D Canvas Point convert to 3D world point
I have a problem with my code or I expect the wrong value. What I want to achieve is to convert 2D points from canvas to 3D world space point.

If I understand correctly, I should always get the same points regardless of the rotation of the camera because I don't want a VIEW SPACE but a WORLD SPACE point. So imagine that I click on facing wall of cube this between X and Z axis, then that what I think I should get constant Y value and it is working correctly until I make some rotation change to my camera. If we will make that camera is looking on that wall but with some angle then we will be got for each click different values for Y-axis which one should be constant because each point on that wall is on the same Y position.

```<code>var r = canvas.getBoundingClientRect();
var x = clientX - r.left;
var y = height - (clientY - r.top);

var projectionMatrix = matrix4.perspective(fov , ratio, near, far);
// convert to clip space
var xClipSpace = x / width * 2.0 - 1.0;
var yClipSpace = y / height * -2.0 + 1.0;
var zClipSpace = 1;
// convert back from clip space to world space
var xyzVec3 = vector3.create(xClipSpace ,yClipSpace ,zClipSpace);
var transfrom = matrix4.multiply(projectionMatrix,viewMatrix);
var inverse = matrix4.invert(transform);
var result = vector3.transformMat4(xyzVec3,inverse);
</code>```

What I doing wrong ?

答:
I'm not 100% sure I understand your diagram but otherwise your code looks fine.

In most WebGL math a frustum goes -Z in the distance. Of course you can rotate that based on the view. But in any case if you pass clip space [x, y, -1] through the inverse of the (projection * view) matrix then you'll get some point of the far plane of the view frustum. As the view rotates that point moves with the frustum.

If we will make that camera is looking on that wall but with some angle then we will be got for each click different values for Y-axis which one should be constant because each point on that wall is on the same Y position.

No: If you rotate the camera that entire wall will rotate so points on it will rotate.

Here's a diagram looking down on top of the view frustum in world space. The view is rotating. If clipX and clipY are 0 then the point being computed is on the center of the far plane of the frustum (Z = 1 in clip space). You can see that point rotating even though it stays on the plane. Its position in view space would not change but its position in world space changes because the entire view frustum is effectively being rotated.

Of course you'd get a different value for Y if you rotate the camera.

const v3 = twgl.v3;
const m4 = twgl.m4;
const ctx = document.querySelector('canvas').getContext('2d');

const boxTop = [
  [-1,  1, -1],
  [-1,  1,  1],
  [ 1,  1,  1],
  [ 1,  1, -1],
];

function render(time) {
  time *= 0.001;

  ctx.setTransform(1, 0, 0, 1, 0, 0);
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

  const fov = 60 * Math.PI / 180;
  const ratio = ctx.canvas.clientWidth / ctx.canvas.clientHeight;
  const near = 10;
  const far = 40;
  const projectionMatrix = m4.perspective(fov , ratio, near, far);
  const viewMatrix = m4.rotationY(time);
  // convert to clip space
  const xClipSpace = 0;
  const yClipSpace = 0;
  const zClipSpace = 1;
  // convert back from clip space to world space
  const xyzVec3 = v3.create(xClipSpace ,yClipSpace ,zClipSpace);
  const transform = m4.multiply(projectionMatrix, viewMatrix);
  const inverse = m4.inverse(transform);
  const result = m4.transformPoint(inverse, xyzVec3);

  // -------------

  ctx.setTransform(1, 0, 0, 1, 150.5, 75.5);

  // draw origin
  ctx.beginPath();
  for (let i = -200; i <= 200; i += 20) {
    ctx.moveTo(-400, i);
    ctx.lineTo( 400, i);
    ctx.moveTo(i, -400);
    ctx.lineTo(i,  400);
  }
  ctx.strokeStyle = '#DDD';
  ctx.stroke();

  ctx.beginPath();
  ctx.moveTo(-400, 0);
  ctx.lineTo( 400, 0);
  ctx.moveTo(0, -400);
  ctx.lineTo(0,  400);
  ctx.strokeStyle = '#444';
  ctx.stroke();

  ctx.fillStyle = '#888';
  ctx.fillText('x', 140, 10);
  ctx.fillText('z', 5, -65);

  // draw frustum
  ctx.beginPath();
  for (let i = 0; i < 4; ++i) {
    const v0 = m4.transformPoint(inverse, boxTop[i]);
    const v1 = m4.transformPoint(inverse, boxTop[(i + 1) % 4]);
    drawLine(ctx, v0, v1);
  }
  ctx.strokeStyle = 'black';
  ctx.stroke();

  {
    ctx.beginPath();
    ctx.arc(result[0], result[2], 3, 0, Math.PI * 2);
    ctx.fillStyle = 'red';
    ctx.fill();
    ctx.fillText(`${result[0].toFixed(2)}, ${result[2].toFixed(2)}`, result[0] + 5, result[2] + 3);
  }

  requestAnimationFrame(render);
}
requestAnimationFrame(render);

function drawLine(ctx, v0, v1) {
  ctx.moveTo(v0[0], v0[2]);
  ctx.lineTo(v1[0], v1[2]);
}

render();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas { border: 1px solid black; }</code>```

<canvas></canvas>
```

Body:
I have a problem with my code or I expect the wrong value. What I want to achieve is to convert 2D points from canvas to 3D world space point.

If I understand correctly, I should always get the same points regardless of the rotation of the camera because I don't want a VIEW SPACE but a WORLD SPACE point. So imagine that I click on facing wall of cube this between X and Z axis, then that what I think I should get constant Y value and it is working correctly until I make some rotation change to my camera. If we will make that camera is looking on that wall but with some angle then we will be got for each click different values for Y-axis which one should be constant because each point on that wall is on the same Y position.

var r = canvas.getBoundingClientRect();
var x = clientX - r.left;
var y = height - (clientY - r.top);

var projectionMatrix = matrix4.perspective(fov , ratio, near, far);
// convert to clip space
var xClipSpace = x / width * 2.0 - 1.0;
var yClipSpace = y / height * -2.0 + 1.0;
var zClipSpace = 1;
// convert back from clip space to world space
var xyzVec3 = vector3.create(xClipSpace ,yClipSpace ,zClipSpace);
var transfrom = matrix4.multiply(projectionMatrix,viewMatrix);
var inverse = matrix4.invert(transform);
var result = vector3.transformMat4(xyzVec3,inverse);

What I doing wrong ?

Body:
I'm not 100% sure I understand your diagram but otherwise your code looks fine.

In most WebGL math a frustum goes -Z in the distance. Of course you can rotate that based on the view. But in any case if you pass clip space [x, y, -1] through the inverse of the (projection * view) matrix then you'll get some point of the far plane of the view frustum. As the view rotates that point moves with the frustum.

If we will make that camera is looking on that wall but with some angle then we will be got for each click different values for Y-axis which one should be constant because each point on that wall is on the same Y position.

No: If you rotate the camera that entire wall will rotate so points on it will rotate.

Here's a diagram looking down on top of the view frustum in world space. The view is rotating. If clipX and clipY are 0 then the point being computed is on the center of the far plane of the frustum (Z = 1 in clip space). You can see that point rotating even though it stays on the plane. Its position in view space would not change but its position in world space changes because the entire view frustum is effectively being rotated.

Of course you'd get a different value for Y if you rotate the camera.

const v3 = twgl.v3;
const m4 = twgl.m4;
const ctx = document.querySelector('canvas').getContext('2d');

const boxTop = [
  [-1,  1, -1],
  [-1,  1,  1],
  [ 1,  1,  1],
  [ 1,  1, -1],
];

function render(time) {
  time *= 0.001;

  ctx.setTransform(1, 0, 0, 1, 0, 0);
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

  const fov = 60 * Math.PI / 180;
  const ratio = ctx.canvas.clientWidth / ctx.canvas.clientHeight;
  const near = 10;
  const far = 40;
  const projectionMatrix = m4.perspective(fov , ratio, near, far);
  const viewMatrix = m4.rotationY(time);
  // convert to clip space
  const xClipSpace = 0;
  const yClipSpace = 0;
  const zClipSpace = 1;
  // convert back from clip space to world space
  const xyzVec3 = v3.create(xClipSpace ,yClipSpace ,zClipSpace);
  const transform = m4.multiply(projectionMatrix, viewMatrix);
  const inverse = m4.inverse(transform);
  const result = m4.transformPoint(inverse, xyzVec3);

  // -------------

  ctx.setTransform(1, 0, 0, 1, 150.5, 75.5);

  // draw origin
  ctx.beginPath();
  for (let i = -200; i <= 200; i += 20) {
    ctx.moveTo(-400, i);
    ctx.lineTo( 400, i);
    ctx.moveTo(i, -400);
    ctx.lineTo(i,  400);
  }
  ctx.strokeStyle = '#DDD';
  ctx.stroke();

  ctx.beginPath();
  ctx.moveTo(-400, 0);
  ctx.lineTo( 400, 0);
  ctx.moveTo(0, -400);
  ctx.lineTo(0,  400);
  ctx.strokeStyle = '#444';
  ctx.stroke();

  ctx.fillStyle = '#888';
  ctx.fillText('x', 140, 10);
  ctx.fillText('z', 5, -65);

  // draw frustum
  ctx.beginPath();
  for (let i = 0; i < 4; ++i) {
    const v0 = m4.transformPoint(inverse, boxTop[i]);
    const v1 = m4.transformPoint(inverse, boxTop[(i + 1) % 4]);
    drawLine(ctx, v0, v1);
  }
  ctx.strokeStyle = 'black';
  ctx.stroke();

  {
    ctx.beginPath();
    ctx.arc(result[0], result[2], 3, 0, Math.PI * 2);
    ctx.fillStyle = 'red';
    ctx.fill();
    ctx.fillText(`${result[0].toFixed(2)}, ${result[2].toFixed(2)}`, result[0] + 5, result[2] + 3);
  }

  requestAnimationFrame(render);
}
requestAnimationFrame(render);

function drawLine(ctx, v0, v1) {
  ctx.moveTo(v0[0], v0[2]);
  ctx.lineTo(v1[0], v1[2]);
}

render();

canvas { border: 1px solid black; }

<canvas></canvas>
<script src="https://twgljs.org/dist/4.x/twgl-full.js"></script>


问:
Alamofire 5.0 with AlamofireNetworkActivityIndicator 2.4
I'm trying to use alamofire and AlamofireNetworkActivityIndicator, but at pod install(both latest versions) i get this:

```<code>Analyzing dependencies
[!] CocoaPods could not find compatible versions for pod "Alamofire":
  In Podfile:
    Alamofire (~> 5.0)

    AlamofireNetworkActivityIndicator (~> 2.4) was resolved to 2.4.0, which depends on
      Alamofire (~> 4.8)

</code>```

I don't want to downgrade alamofire to 4.8 as it will screw with code i already have written.
Am i doing smth wrong or i should just wait for AlamofireNetworkActivityIndicator to receive an update?

答: You need to use the latest version for your pod linking of AlamofireNetworkActivityIndicator (~> 3.0)

Body:
I'm trying to use alamofire and AlamofireNetworkActivityIndicator, but at pod install(both latest versions) i get this:

Analyzing dependencies
[!] CocoaPods could not find compatible versions for pod "Alamofire":
  In Podfile:
    Alamofire (~> 5.0)

    AlamofireNetworkActivityIndicator (~> 2.4) was resolved to 2.4.0, which depends on
      Alamofire (~> 4.8)

I don't want to downgrade alamofire to 4.8 as it will screw with code i already have written.
Am i doing smth wrong or i should just wait for AlamofireNetworkActivityIndicator to receive an update?


问:
are there any open source shopping carts that integrate with quickbooks
i am looking for a open source shopping card ecommerce solution that integrates with quick books.  I am currently hosting on windows IIS but would look at others based on suggestions.  is there any one that stands above the rest ?</p>

答:
use nopcommerce shopping cart, it includes most of the functionality

http://www.nopcommerce.com/default.aspx


问:
How to Handle 500 internal error while mapping JSON to POJO If one of attribute of POJO class is empty
Hi I am working on Rest API written in java and have come through the below doubt.

I have already written the code which takes post data and maps to pojo class and sends back the data in JSON form.

Correct Format:-

```<code>{
    "Name":"Rahul",
    "Address":"Mumbai",
    "Age": 27
}
</code>```

Output:

```<code>{
    "Pkid":"1",
    "Name":"Rahul",
    "Address":"Mumbai",
    "Age": 27
}
</code>```

But when I am passing empty value to one of the attribute I am getting 500 internal error can someone help me how to handle it and return the value in json format after handling it:

```<code>{
    "Name":,
    "Address":"Mumbai",
    "Age": 27
}
</code>```

Output:

```<code>500 Internal error
</code>```

答:
Understanding: you are trying to store an object and return the object details along with the primary key id generated
Following are two approaches for this:

1. Custom de-serializer with Jackson:
I would prefer this method because it provides you with additional security. In the current  scenario, you are exposed to cross-site scripting attacks
Using a custom de-serializer along with Jsoup api or Antisamy to filter the data would help you prevent XSS and also include null values.

You need to add your custom de-serializer to your pojo using:

```<code>    @JsonDeserialize(using = CustomDeserializer.class)
    public class User {
       private String id;

       private String name;
      // standard getters and setters
    }
</code>```

2. Using Jackson annotation:

```<code>public class User {

    @JsonInclude(Include.NON_NULL)
    private String id;

    private String name;

    // standard getters and setters
}
</code>```

Body:
Hi I am working on Rest API written in java and have come through the below doubt.

I have already written the code which takes post data and maps to pojo class and sends back the data in JSON form.

Correct Format:-

{
    "Name":"Rahul",
    "Address":"Mumbai",
    "Age": 27
}

Output:

{
    "Pkid":"1",
    "Name":"Rahul",
    "Address":"Mumbai",
    "Age": 27
}

But when I am passing empty value to one of the attribute I am getting 500 internal error can someone help me how to handle it and return the value in json format after handling it:

{
    "Name":,
    "Address":"Mumbai",
    "Age": 27
}

Output:

500 Internal error

Body:
Understanding: you are trying to store an object and return the object details along with the primary key id generated
Following are two approaches for this:

1. Custom de-serializer with Jackson:
I would prefer this method because it provides you with additional security. In the current  scenario, you are exposed to cross-site scripting attacks
Using a custom de-serializer along with Jsoup api or Antisamy to filter the data would help you prevent XSS and also include null values.

You need to add your custom de-serializer to your pojo using:

    @JsonDeserialize(using = CustomDeserializer.class)
    public class User {
       private String id;

       private String name;
      // standard getters and setters
    }

2. Using Jackson annotation:

public class User {

    @JsonInclude(Include.NON_NULL)
    private String id;

    private String name;

    // standard getters and setters
}


问:
How call a python script from a python process
I  have to call a long run process from a bottle script (web framework like Django).

So in a bottle script i have

```<code>os.system("python /home/tom/Documents/proc_test/main.py")
</code>```

Anyway the main.py script is not executed.
How can i call a python script from another running python program?

P.S: in python shell interpreter i have write os.system("python /home/tom/Documents/proc_test/main.py") and the file is called

答:
Like Dirk suggested, import the main.py from python then call the function.

Or if you need to actually run main.py as a separate process then use subprocess module.

```<code>import subprocess
subprocess.call(["python /home/tom/Documents/proc_test/main.py"])
</code>```

Hope this helps

Body:
I  have to call a long run process from a bottle script (web framework like Django).

So in a bottle script i have

os.system("python /home/tom/Documents/proc_test/main.py")

Anyway the main.py script is not executed.
How can i call a python script from another running python program?

P.S: in python shell interpreter i have write os.system("python /home/tom/Documents/proc_test/main.py") and the file is called

Body:
Like Dirk suggested, import the main.py from python then call the function.

Or if you need to actually run main.py as a separate process then use subprocess module.

import subprocess
subprocess.call(["python /home/tom/Documents/proc_test/main.py"])

Hope this helps


问:
Maximum height of the staircase
Given an integer A representing the square blocks. The height of each square block is 1. The task is to create a staircase of max height using these blocks. The first stair would require only one block, the second stair would require two blocks and so on. Find and return the maximum height of the staircase.

Your submission failed for the following input: A : 92761

Your function returned the following : 65536

The expected returned value : 430

```<code>Approach:
We are interested in the number of steps and we know that each step Si uses exactly Bi number of bricks. We can represent this problem as an equation:
n * (n + 1) / 2 = T (For Natural number series starting from 1, 2, 3, 4, 5 …)
n * (n + 1) = 2 * T
n-1 will represent our final solution because our series in problem starts from 2, 3, 4, 5…

Now, we just have to solve this equation and for that we can exploit binary search to find the solution to this equation. Lower and Higher bounds of binary search are 1 and T.
</code>```

CODE

```<code>public int solve(int A) {
        int l=1,h=A,T=2*A;
        while(l<=h)
        {
            int mid=l+(h-l)/2;
            if((mid*(mid+1))==T)
                return mid;
            if((mid*(mid+1))>T && (mid!=0 && (mid*(mid-1))<=T) )
                return mid-1;
            if((mid*(mid+1))>T)
                h=mid-1;
            else
                l=mid+1;
        }
        return 0;
    }
</code>```

答:
So this should do the job as it also returns the expected value. Correct me if im wrong.</p>

```<code>public int solve(int blocks) {
    int current; //Create Variables
    for (int x = 0; x < Integer.MAX_VALUE; x++) { //Increment until return
      current = 0; //Set current to 0

        //Implementation of the Gauss sum
        for (int i = 1; i <= x; i++) { //Sum up [1,*current height*]
            current += i;
        } //Now we have the amount of blocks required for the current height

        //Now we check if the amount of blocks is bigger than
        // the wanted amount, and if so we return the last one
        if (current > blocks) {
            return x - 1;
        }
    }
    return current;
}
</code>```

Title: Maximum height of the staircase

Body:
Given an integer A representing the square blocks. The height of each square block is 1. The task is to create a staircase of max height using these blocks. The first stair would require only one block, the second stair would require two blocks and so on. Find and return the maximum height of the staircase.

Your submission failed for the following input: A : 92761

Your function returned the following : 65536

The expected returned value : 430

Approach:
We are interested in the number of steps and we know that each step Si uses exactly Bi number of bricks. We can represent this problem as an equation:
n * (n + 1) / 2 = T (For Natural number series starting from 1, 2, 3, 4, 5 …)
n * (n + 1) = 2 * T
n-1 will represent our final solution because our series in problem starts from 2, 3, 4, 5…

Now, we just have to solve this equation and for that we can exploit binary search to find the solution to this equation. Lower and Higher bounds of binary search are 1 and T.

CODE

public int solve(int A) {
        int l=1,h=A,T=2*A;
        while(l<=h)
        {
            int mid=l+(h-l)/2;
            if((mid*(mid+1))==T)
                return mid;
            if((mid*(mid+1))>T && (mid!=0 && (mid*(mid-1))<=T) )
                return mid-1;
            if((mid*(mid+1))>T)
                h=mid-1;
            else
                l=mid+1;
        }
        return 0;
    }

Body:
So this should do the job as it also returns the expected value. Correct me if im wrong.

public int solve(int blocks) {
    int current; //Create Variables
    for (int x = 0; x < Integer.MAX_VALUE; x++) { //Increment until return
      current = 0; //Set current to 0

        //Implementation of the Gauss sum
        for (int i = 1; i <= x; i++) { //Sum up [1,*current height*]
            current += i;
        } //Now we have the amount of blocks required for the current height

        //Now we check if the amount of blocks is bigger than
        // the wanted amount, and if so we return the last one
        if (current > blocks) {
            return x - 1;
        }
    }
    return current;
}


问:
Accessing component's "key" prop
I want to update the Counter component to take onIncrement and onDecrement
callbacks as props and ensure they update the counter’s values
independently.

Each callback can only take a single integer as parameter
which tells the amount to increment the counter’s existing value.

I believe the best way to do this is to access the 'key' prop of the Counter component?

Sandbox: https://codesandbox.io/s/silly-sound-5ofef?from-embed
App.js

```<code>import Counter from './components/Counter'
import './App.css'

export class App extends Component {
  constructor(props, context) {
    super(props, context)
    this.state = {
      data: [
        { id: 1, value: 0 },
        { id: 2, value: 0 },
        { id: 3, value: 0 },
        { id: 4, value: 0 },
      ],
    }
  }

  onDecrement = e => {
    this.setState(state => {
      const data = state.data.map(item => {
        return { id: item.id, value: (item.value -= e) }
      })
      return {
        data,
      }
    })
  }

  onIncrement = e => {
    this.setState(state => {
      const data = state.data.map(item => {
        return { id: item.id, value: (item.value += e) }
      })
      return {
        data,
      }
    })
  }

  render() {
    return (
      <div>
        {this.state['data'].map(counter => (
          <Counter
            key={counter.id}
            value={counter.value}
            onIncrement={this.onIncrement}
            onDecrement={this.onDecrement}
          />
        ))}
      </div>
    )
  }
}

export default App
</code>```

Counter.js

```<code>
export class Counter extends Component {
  render() {
    const { value, onIncrement, onDecrement } = this.props
    return (
      <div className="counter test">
        <b>{value}</b>
        <div className="counter-controls">
          <button
            className="button btn-danger btn-sm"
            onClick={() => onDecrement(1)}
          >
            -
          </button>
          <button
            className="button btn-success btn-sm"
            onClick={() => onIncrement(1)}
          >
            +
          </button>
        </div>
      </div>
    )
  }
}

export default Counter
</code>```

答:
I have added a new prop called step which can be changed to suit the billing. The key props is not advisable because it's only used for the React stuff and you're even using the id of the counter. Using a new prop would be advisable here.

i made some changes to your sandbox below.

https://codesandbox.io/s/determined-shaw-fq6lc

Title: Accessing component's "key" prop

Body:
I want to update the Counter component to take onIncrement and onDecrement
callbacks as props and ensure they update the counter’s values
independently.

Each callback can only take a single integer as parameter
which tells the amount to increment the counter’s existing value.

I believe the best way to do this is to access the 'key' prop of the Counter component?

Sandbox: https://codesandbox.io/s/silly-sound-5ofef?from-embed
App.js

import Counter from './components/Counter'
import './App.css'

export class App extends Component {
  constructor(props, context) {
    super(props, context)
    this.state = {
      data: [
        { id: 1, value: 0 },
        { id: 2, value: 0 },
        { id: 3, value: 0 },
        { id: 4, value: 0 },
      ],
    }
  }

  onDecrement = e => {
    this.setState(state => {
      const data = state.data.map(item => {
        return { id: item.id, value: (item.value -= e) }
      })
      return {
        data,
      }
    })
  }

  onIncrement = e => {
    this.setState(state => {
      const data = state.data.map(item => {
        return { id: item.id, value: (item.value += e) }
      })
      return {
        data,
      }
    })
  }

  render() {
    return (

        {this.state['data'].map(counter => (
          <Counter
            key={counter.id}
            value={counter.value}
            onIncrement={this.onIncrement}
            onDecrement={this.onDecrement}
          />
        ))}

    )
  }
}

export default App

Counter.js

export class Counter extends Component {
  render() {
    const { value, onIncrement, onDecrement } = this.props
    return (

        {value}

          <button
            className="button btn-danger btn-sm"
            onClick={() => onDecrement(1)}
          >
            -
          </button>
          <button
            className="button btn-success btn-sm"
            onClick={() => onIncrement(1)}
          >
            +
          </button>

    )
  }
}

export default Counter


问:
vee-validate: Is it possible to change the fields-bag-name without changing the current name?
So I want to adapt the Autofill naming for Birthdays. However, this leads to several problems. Now I need to find out if I can force vee-validate to change the name of the field.

To understand it better. This is how it currently looks like:

```<code><select
    v-model="day"
    id="day"
    name="day"
    :class="{'invalid' : errors.has('day')}"
    v-validate="'required|excluded:0'"
>
    <option
        :disabled="true"
        value="0"
        v-text="trans('food.Day')"
    />
    <option
        v-for="n in 31"
        :key="n"
        :value="n"
        v-text="n"
    />
</select>

<span
    class="bar"
    :class="{'invalid' : errors.has('day')}"
/>
</code>```

The name for the select field is "day".
However, according to this, it should be named: "bday-day".

Since I'm using vee-validate, this leads to a rename of the field name to "bday-day". Now errors.has('day')} won't work anymore.

But even if I change this to errors.has('bday-day'), I cannot use my internal watcher for changes in values. I get the error:

Failed watching path: "bday-day" Watcher only accepts simple dot-delimited paths. For full control, use a function instead.

This is because I have to force the same name of the v-model name and vee-validate name. v-model="bday-day" cannot work.

To make it short. My end goal is something like this:

```<code><select
    v-model="day"
    id="day"
    name="bday-day"
    :class="{'invalid' : errors.has('day')}"
    v-validate="{required: true, excluded: 0, name: 'day'}"
>
    <option
        :disabled="true"
        value="0"
        v-text="trans('food.Day')"
    />
    <option
        v-for="n in 31"
        :key="n"
        :value="n"
        v-text="n"
    />
</select>

<span
    class="bar"
    :class="{'invalid' : errors.has('day')}"
/>
</code>```

I would use the name="bday-day" for autofill, but I would set the field name for vee validate to name: 'day'.

答:
With VeeValidate v3, you have two relevant options you can pass to ValidationProvider, name and vid.

VeeValidate's docs specify that:

name specifies a field name to be used in error messages.

vid is an identifier used for target/cross-field based rules.

From my tests though, vid is also used as the key for fields and errors in the ValidationObserver if provided, and if not, it falls back to name.

As a result, if you have multiple of the same fields in one form, and you're looking to have a unique key name (so that they don't clash and break), then use name purely just for the field name in error messages, and vid to provide a unique ID to be used by ValidationObserver in the fields and errors objects. For example:

```<code><ValidationProvider
  name="hours" // used for error messages
  :vid="hours-${unique-part}" // unique key to stop clashes
  rules="required"
  v-slot="{ errors }"
>...</ValidationProvider>
</code>```

Body:
So I want to adapt the Autofill naming for Birthdays. However, this leads to several problems. Now I need to find out if I can force vee-validate to change the name of the field.

To understand it better. This is how it currently looks like:

<select
    v-model="day"
    id="day"
    name="day"
    :class="{'invalid' : errors.has('day')}"
    v-validate="'required|excluded:0'"
>
    <option
        :disabled="true"
        value="0"
        v-text="trans('food.Day')"
    />
    <option
        v-for="n in 31"
        :key="n"
        :value="n"
        v-text="n"
    />
</select>

The name for the select field is "day".
However, according to this, it should be named: "bday-day".

Since I'm using vee-validate, this leads to a rename of the field name to "bday-day". Now errors.has('day')} won't work anymore.

But even if I change this to errors.has('bday-day'), I cannot use my internal watcher for changes in values. I get the error:

Failed watching path: "bday-day" Watcher only accepts simple dot-delimited paths. For full control, use a function instead.

This is because I have to force the same name of the v-model name and vee-validate name. v-model="bday-day" cannot work.

To make it short. My end goal is something like this:

<select
    v-model="day"
    id="day"
    name="bday-day"
    :class="{'invalid' : errors.has('day')}"
    v-validate="{required: true, excluded: 0, name: 'day'}"
>
    <option
        :disabled="true"
        value="0"
        v-text="trans('food.Day')"
    />
    <option
        v-for="n in 31"
        :key="n"
        :value="n"
        v-text="n"
    />
</select>

I would use the name="bday-day" for autofill, but I would set the field name for vee validate to name: 'day'.

Body:
With VeeValidate v3, you have two relevant options you can pass to ValidationProvider, name and vid.

VeeValidate's docs specify that:

name specifies a field name to be used in error messages.

vid is an identifier used for target/cross-field based rules.

From my tests though, vid is also used as the key for fields and errors in the ValidationObserver if provided, and if not, it falls back to name.

As a result, if you have multiple of the same fields in one form, and you're looking to have a unique key name (so that they don't clash and break), then use name purely just for the field name in error messages, and vid to provide a unique ID to be used by ValidationObserver in the fields and errors objects. For example:

<ValidationProvider
  name="hours" // used for error messages
  :vid="hours-${unique-part}" // unique key to stop clashes
  rules="required"
  v-slot="{ errors }"
>...</ValidationProvider>


问:
I used yarn to add these gsap libraries but the files appear disabled? What does this mean?
I am attempting to use the greensock library for animation, and used yarn to add the library to my project but the files are appearing as "disabled view"  (for lack of better word) in my directory. When I attempt to use the library in my JS file I am receiving a Missing plugin? gsap.registerPlugin() error in my browser console and the animation is not executing. I have ha ve attempted to solve this with gsap.registerPlugin(MotionPathPlugin, ScrollToPlugin, TextPlugin); but this results in an error (in browser console) that the plugin cannot be found. Any idea how to resolve this issue? What is going wrong? I have also tried to use the CDN delivery script in my HTML but and receiving the same Missing plugin? gsap.registerPlugin() error in the browser console.

Any insight and help is massively appreciated. Screenshot: screenshot of VS code

答:
You need to import the plugins that you want to use in every file that you want to use them in. So the code at the top of the file should be:

```<code>import { gsap } from "gsap";
import { MotionPathPlugin } from "gsap/MotionPathPlugin";
import { TextPlugin } from "gsap/TextPlugin";
import { ScrollToPlugin } from "gsap/ScrollToPlugin";

gsap.registerPlugin(MotionPathPlugin, TextPlugin, ScrollToPlugin);
</code>```

You can use the GSAP installation page, specifically the install helper, to help you get the correct formatting with your system.

Body:
You need to import the plugins that you want to use in every file that you want to use them in. So the code at the top of the file should be:

import { gsap } from "gsap";
import { MotionPathPlugin } from "gsap/MotionPathPlugin";
import { TextPlugin } from "gsap/TextPlugin";
import { ScrollToPlugin } from "gsap/ScrollToPlugin";

gsap.registerPlugin(MotionPathPlugin, TextPlugin, ScrollToPlugin);

You can use the GSAP installation page, specifically the install helper, to help you get the correct formatting with your system.


问:
Github APi to create and add user in Organization
Is there any way to create and add user in organization using API in Github?</p>

答: Refer https://developer.github.com/v3/users/ for user Apis of GitHub</p>


问:
What's the difference of name scope and a variable scope in tensorflow?
What's the differences between these functions?

tf.variable_op_scope(values, name, default_name, initializer=None)

Returns a context manager for defining an op that creates variables.
  This context manager validates that the given values are from the same graph, ensures that that graph is the default graph, and pushes a name scope and a variable scope.

tf.op_scope(values, name, default_name=None)

Returns a context manager for use when defining a Python op.
  This context manager validates that the given values are from the same graph, ensures that that graph is the default graph, and pushes a name scope.

tf.name_scope(name)

Wrapper for Graph.name_scope() using the default graph.
  See Graph.name_scope() for more details.

tf.variable_scope(name_or_scope, reuse=None, initializer=None)

Returns a context for variable scope.
  Variable scope allows to create new variables and to share already created ones while providing checks to not create or share by accident. For details, see the Variable Scope How To, here we present only a few basic examples.

答:
Tensorflow 2.0 Compatible Answer: The explanations of Andrzej Pronobis and Salvador Dali are very detailed about the Functions related to Scope.

Of the Scope Functions discussed above, which are active as of now (17th Feb 2020) are variable_scope and name_scope.

Specifying the 2.0 Compatible Calls for those functions, we discussed above, for the benefit of the community.

Function in 1.x:

tf.variable_scope

tf.name_scope

Respective Function in 2.x:

tf.compat.v1.variable_scope

tf.name_scope (tf.compat.v2.name_scope if migrated from 1.x to 2.x)

For more information about migration from 1.x to 2.x, please refer this Migration Guide.


问:
Google Sheets - Highlight cell if value exists in other sheet
I would like to highlight a cell if a value matches a cell in another sheet.

Proposed Solution

```<code>FOR EACH row in 'sheet1'

IF column C == TRUE
&& column D (value split by comma, only search values with 'tf' in) does not match any cell in 'sheet2'

Highlight the cell Red
</code>```

Example Value

CELL D9

"Platform,TF Platform,TF User"

Do not search "Platform" in sheet2

Search "TF Platform" in sheet2

Search "TF User" in sheet2

Example Sheet

https://docs.google.com/spreadsheets/d/1eI9FTVNuyMEzQTJnHzufz_gElE53AMmk-mxVEWKPdRk/edit?usp=sharing

答:
You can do the following in Apps Script:

Retrieve the values from sheet1 (columns C, D) with getRange and getValues. For each row, do the following:

Check that the checkbox in column C is checked.

Retrieve array with comma-separated values from column D and filter them so that only the ones that contain TF are kept. String.prototype.split() and Array.prototype.filter() are used for this.

Retrieve array with values from sheet2 (column E) with getRange and getValues.

Check that any value from the first array (comma-separated values from column D) matches any value from the second array (values from sheet2) with Array.prototype.some().

If a match is found, use setBackground(color) to change the cell background color.

It could be something along the following lines:

function highlightCells() {
  var ss = SpreadsheetApp.getActive();
  var sheet1 = ss.getSheetByName("sheet1");
  var sheet2 = ss.getSheetByName("sheet2");
  // Get the values from sheet1 (column C, D):
  var firstRow = 1;
  var firstCol = 3;
  var numRows = sheet1.getLastRow() - firstRow + 1;
  var numCols = 2;
  var originValues = sheet1.getRange(firstRow, firstCol, numRows, numCols).getValues();
  // Iterate through each row in sheet1:
  originValues.forEach(function(row, i) {
    var checkbox = row[0];
    if (checkbox === true) { // Check that checkbox in column C is checked
      var cellValue = row[1];
      // Get the comma-separated values in column D (only if the contain `TF`, capitalized):
      var values = cellValue.split(",").filter(function(value) {
        return value.indexOf("TF") !== -1;
      });
      // Get the values from sheet2:
      var firstRow2 = 1;
      var column = 5;
      var numRows2 = sheet2.getLastRow() - firstRow2 + 1;
      var valuesSheet2 = sheet2.getRange(firstRow2, column, numRows2).getValues().map(function(value) {
        return value[0];
      });
      // Look for any comma-separated value in column D (sheet1) that matches a value in column E (sheet2):
      var found = values.some(function(value) {
        return valuesSheet2.indexOf(value) > -1;
      });
      // If any value matches, change background color in to red:
      if (found) {
        sheet1.getRange(i + firstRow, 4).setBackground("red");
      }
    }
  });
}
```

I'm not sure whether you want to set the background color if a value matches o whether it doesn't match (it's not clear in your question). This changes the background color if a value matches. If you want it to change if it doesn't match, you should do this instead: if (!found) {.

Reference:

Range.setBackground(color)

Array.prototype.some()

Body:
I would like to highlight a cell if a value matches a cell in another sheet.

Proposed Solution

FOR EACH row in 'sheet1'

IF column C == TRUE
&& column D (value split by comma, only search values with 'tf' in) does not match any cell in 'sheet2'

Highlight the cell Red

Example Value

CELL D9

"Platform,TF Platform,TF User"

Do not search "Platform" in sheet2

Search "TF Platform" in sheet2

Search "TF User" in sheet2

Example Sheet

https://docs.google.com/spreadsheets/d/1eI9FTVNuyMEzQTJnHzufz_gElE53AMmk-mxVEWKPdRk/edit?usp=sharing

Body:
You can do the following in Apps Script:

Retrieve the values from sheet1 (columns C, D) with getRange and getValues. For each row, do the following:

Check that the checkbox in column C is checked.

Retrieve array with comma-separated values from column D and filter them so that only the ones that contain TF are kept. String.prototype.split() and Array.prototype.filter() are used for this.

Retrieve array with values from sheet2 (column E) with getRange and getValues.

Check that any value from the first array (comma-separated values from column D) matches any value from the second array (values from sheet2) with Array.prototype.some().

If a match is found, use setBackground(color) to change the cell background color.

It could be something along the following lines:

function highlightCells() {
  var ss = SpreadsheetApp.getActive();
  var sheet1 = ss.getSheetByName("sheet1");
  var sheet2 = ss.getSheetByName("sheet2");
  // Get the values from sheet1 (column C, D):
  var firstRow = 1;
  var firstCol = 3;
  var numRows = sheet1.getLastRow() - firstRow + 1;
  var numCols = 2;
  var originValues = sheet1.getRange(firstRow, firstCol, numRows, numCols).getValues();
  // Iterate through each row in sheet1:
  originValues.forEach(function(row, i) {
    var checkbox = row[0];
    if (checkbox === true) { // Check that checkbox in column C is checked
      var cellValue = row[1];
      // Get the comma-separated values in column D (only if the contain `TF`, capitalized):
      var values = cellValue.split(",").filter(function(value) {
        return value.indexOf("TF") !== -1;
      });
      // Get the values from sheet2:
      var firstRow2 = 1;
      var column = 5;
      var numRows2 = sheet2.getLastRow() - firstRow2 + 1;
      var valuesSheet2 = sheet2.getRange(firstRow2, column, numRows2).getValues().map(function(value) {
        return value[0];
      });
      // Look for any comma-separated value in column D (sheet1) that matches a value in column E (sheet2):
      var found = values.some(function(value) {
        return valuesSheet2.indexOf(value) > -1;
      });
      // If any value matches, change background color in to red:
      if (found) {
        sheet1.getRange(i + firstRow, 4).setBackground("red");
      }
    }
  });
}

I'm not sure whether you want to set the background color if a value matches o whether it doesn't match (it's not clear in your question). This changes the background color if a value matches. If you want it to change if it doesn't match, you should do this instead: if (!found) {.

Reference:

Range.setBackground(color)

Array.prototype.some()


问:
Where is Oracle APEX source code framework located
Recently i start learning Oracle APEX and i have a question (i'm familiar with plsql):

Where is the source code for APEX located, in which schema ?

EG: For this piece of code where can i find APEX_COLLECTION.COLLECTION_EXISTS souce code :

```<code>IF :P9_HOW_MANY is NOT NULL and :P9_HOW_MANY > 0 then
IF NOT APEX_COLLECTION.COLLECTION_EXISTS (p_collection_name => 'CHILDREN') THEN
APEX_COLLECTION.CREATE_OR_TRUNCATE_COLLECTION(
          p_collection_name => 'CHILDREN');
END IF;
APEX_COLLECTION.ADD_MEMBERS(
p_collection_name => 'CHILDREN',
p_c001 => apex_application.g_f01,
p_c002 => apex_application.g_f03,
p_c003 => apex_application.g_f04,
p_c004 => apex_application.g_f02
);
End IF;
</code>```

Thank you.

答:
I think i found the answer, i will leave this here in case it helps anyone:

APEX_COLLECTION

APEX_ITEM

ETC..

all are public synonyms located in SYS schema and the source code is in APEX_190200 schema on the WWV_FLOW_COLLECTION package.

Body:
Recently i start learning Oracle APEX and i have a question (i'm familiar with plsql):

Where is the source code for APEX located, in which schema ?

EG: For this piece of code where can i find APEX_COLLECTION.COLLECTION_EXISTS souce code :

IF :P9_HOW_MANY is NOT NULL and :P9_HOW_MANY > 0 then
IF NOT APEX_COLLECTION.COLLECTION_EXISTS (p_collection_name => 'CHILDREN') THEN
APEX_COLLECTION.CREATE_OR_TRUNCATE_COLLECTION(
          p_collection_name => 'CHILDREN');
END IF;
APEX_COLLECTION.ADD_MEMBERS(
p_collection_name => 'CHILDREN',
p_c001 => apex_application.g_f01,
p_c002 => apex_application.g_f03,
p_c003 => apex_application.g_f04,
p_c004 => apex_application.g_f02
);
End IF;

Thank you.


问:
How to know location (x,y) postion of content in web browser window?
I have a web view (web window). In JavaScript, we have a function
window.scrollTo(x,y).
So the content will move to (x,y) position. But now I want to do a opposite thing:
Assume that I have an anchor tag. When the content go to that tag. I want to know (x,y) moving position.

Can JavaScript do that?

答:
jQuery has an offset method which gives you the (x, y) co-ordinates relative to the document - I hope this is what you're after.

http://api.jquery.com/offset/


问:
How JOIN works internally in MySQL?
Here is my test script, there is no primary key as ID, test case is to join multiple rows having same key, and result in how many rows.

```<code>create table Test1(id integer, name varchar(100));
insert into Test1(id, name) values(1, "Vijay");
insert into Test1(id, name) values(1, "Sandy");
insert into Test1(id, name) values(1, "Rohit");

create table Test2(id integer, surname varchar(100));
insert into Test2(id, surname) values(1, "karma");
insert into Test2(id, surname) values(1, "sharma");
insert into Test2(id, surname) values(1, "yadav");

select Test1.id , Test1.name , Test2.surname from Test1
left outer join
Test2 on Test1.id = Test2.id;

1   Vijay   karma
1   Sandy   karma
1   Rohit   karma
1   Vijay   sharma
1   Sandy   sharma
1   Rohit   sharma
1   Vijay   yadav
1   Sandy   yadav
1   Rohit   yadav

select Test1.id , Test1.name , Test2.surname from Test1
right outer join
Test2 on Test1.id = Test2.id;

1   Vijay   karma
1   Vijay   sharma
1   Vijay   yadav
1   Sandy   karma
1   Sandy   sharma
1   Sandy   yadav
1   Rohit   karma
1   Rohit   sharma
1   Rohit   yadav
</code>```

How this works internally? Does is keep one table static and streams another table on it, and how pointers works in such cases and where the metadata gets stored while join process.

答:
How this works internally? Does is keep one table static and streams another table on it, and how pointers works in such cases and where the metadata gets stored while join process.

Relational database engines perform operations on the data in order to access, update, or delete it. Each engine has a smaller or wider repertoire of operations implemented in it.

For example, in your case, the MySQL engine may work as shown below:

Since there's no filtering predicate (aka WHERE clause) it may execute a "Full Table Scan" on one table, shown as "all" in the execution plan.

Then, it could access the related table using an "Index Range Scan", known as "index" in MySQL's lingo.

How are these operations decided? That's the job for the SQL planner and SQL optimizer. They read your SQL query and produce a tree of operations that will be carried out to produce the result you want. This tree may change in time according to MySQL's heuristics, and changes in the data.

How do you get the specific plan? Just get the plan using:

```<code>explain <query>
</code>```

You'll see the query plan in all its glory.

Title: How JOIN works internally in MySQL?

Body:
Here is my test script, there is no primary key as ID, test case is to join multiple rows having same key, and result in how many rows.

create table Test1(id integer, name varchar(100));
insert into Test1(id, name) values(1, "Vijay");
insert into Test1(id, name) values(1, "Sandy");
insert into Test1(id, name) values(1, "Rohit");

create table Test2(id integer, surname varchar(100));
insert into Test2(id, surname) values(1, "karma");
insert into Test2(id, surname) values(1, "sharma");
insert into Test2(id, surname) values(1, "yadav");

select Test1.id , Test1.name , Test2.surname from Test1
left outer join
Test2 on Test1.id = Test2.id;

1   Vijay   karma
1   Sandy   karma
1   Rohit   karma
1   Vijay   sharma
1   Sandy   sharma
1   Rohit   sharma
1   Vijay   yadav
1   Sandy   yadav
1   Rohit   yadav

select Test1.id , Test1.name , Test2.surname from Test1
right outer join
Test2 on Test1.id = Test2.id;

1   Vijay   karma
1   Vijay   sharma
1   Vijay   yadav
1   Sandy   karma
1   Sandy   sharma
1   Sandy   yadav
1   Rohit   karma
1   Rohit   sharma
1   Rohit   yadav

How this works internally? Does is keep one table static and streams another table on it, and how pointers works in such cases and where the metadata gets stored while join process.

Body:
How this works internally? Does is keep one table static and streams another table on it, and how pointers works in such cases and where the metadata gets stored while join process.

Relational database engines perform operations on the data in order to access, update, or delete it. Each engine has a smaller or wider repertoire of operations implemented in it.

For example, in your case, the MySQL engine may work as shown below:

Since there's no filtering predicate (aka WHERE clause) it may execute a "Full Table Scan" on one table, shown as "all" in the execution plan.

Then, it could access the related table using an "Index Range Scan", known as "index" in MySQL's lingo.

How are these operations decided? That's the job for the SQL planner and SQL optimizer. They read your SQL query and produce a tree of operations that will be carried out to produce the result you want. This tree may change in time according to MySQL's heuristics, and changes in the data.

How do you get the specific plan? Just get the plan using:

explain <query>

You'll see the query plan in all its glory.


问:
Main Loop for pygame doesn't work, pygame quits instantly
I have another issue. When I try to to run my code, pygame launches and then stops immediately.

Here's my code :

```<code>import pygame
import os
import time
import random

pygame.init()
pygame.font.init()

def main():

    clock = pygame.time.Clock()

    win = pygame.display.set_mode((Win_Width, Win_Height))

    run = True
    while run:

        clock.tick(40)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
</code>```

Thank you to help me. Bye !

答:
you need to call main()

so :

if __name__ == "__main__":
  main()

Body:
I have another issue. When I try to to run my code, pygame launches and then stops immediately.

Here's my code :

import pygame
import os
import time
import random

pygame.init()
pygame.font.init()

def main():

    clock = pygame.time.Clock()

    win = pygame.display.set_mode((Win_Width, Win_Height))

    run = True
    while run:

        clock.tick(40)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()

Thank you to help me. Bye !


问:
GCP OS Login creates user_domain account
I am testing OS login and created a instance with metadata "enable-oslogin=TRUE". I then added OS Login role to my account(user@mydomainname.com). When I tried:

```<code>user@original_host$ gcloud compute ssh my_instance --project my_project --zone my_zone
</code>```

GCP allowed me login, but as user user_mydomainname instead of my original account "user"

When I tried:

user@original_host$ ssh my_instance, it denied my login.

When I tried:

```<code>user@original_host$ ssh user_mydomainname@my_instance, it allowed me login, but as user_mydomainname of course.
</code>```

I read a bunch of OS login documents from Google and could not figure out the reason. IN one doc: https://cloud.google.com/compute/docs/instances/managing-instance-access#login_messages

At the Expected login behaviors section, it reads "If a username is not set by a G Suite administrator, OS Login generates a default Linux username by combining the username and domain from the email associated with the user's Google profile. This naming convention ensures uniqueness. For example, if the user email associated with the Google profile is user@example.com, then their generated username is user_example_com."

This looks like what I am getting, but I had set OS login role to my account.

I was expecting with the OS login role setup, I could login to the instance as my original account: user

Did I miss anything here or this is indeed the expected behavior? Is is possible to get my account "user" to use OS Login w/o getting user_mydomainname?

Thanks,
Philip

答:
At first, I've tried to check it OS Login feature on my test VM by following documentation:

create VM instance:

```<code>$ gcloud compute instances create os-login-instance-1 --machine-type=n1-standard-1 --zone=europe-west3-a
Created [https://www.googleapis.com/compute/v1/projects/test-prj/zones/europe-west3-a/instances/os-login-instance-1].
NAME                 ZONE            MACHINE_TYPE   PREEMPTIBLE  INTERNAL_IP    EXTERNAL_IP     STATUS
os-login-instance-1  europe-west3-a  n1-standard-1               10.156.15.226  35.XXX.236.XXX  RUNNING
</code>```

enable OS Login feature for VM:

```<code>$ cloud compute instances add-metadata os-login-instance-1 --metadata enable-oslogin=TRUE --zone=europe-west3-a
Updated [https://www.googleapis.com/compute/v1/projects/test-prj/zones/europe-west3-a/instances/os-login-instance-1].
</code>```

add role roles/compute.osAdminLogin for username@domain.com to make it able to use sudo command:

```<code>$ gcloud projects add-iam-policy-binding test-prj \
 --member='user:username@domain.com' \
 --role='roles/compute.osAdminLogin'
Updated IAM policy for project [test-prj].
</code>```

you can use roles/compute.osLogin for non-root access.

create SSH keys to connect:

```<code>$ ssh-keygen
Generating public/private rsa key pair.
</code>```

upload SSH key to the project:

```<code>gcloud compute os-login ssh-keys add --key-file .ssh/id_rsa.pub
</code>```

connect to your instance:

```<code>$ ssh username_domain_com@35.242.236.114

Linux os-login-instance-1 4.9.0-12-amd64 #1 SMP Debian 4.9.210-1 (2020-01-20) x86_64

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Creating directory '/home/username_domain_com'.
username_domain_com@os-login-instance-1:~$

$ gcloud compute ssh os-login-instance-1
Linux os-login-instance-1 4.9.0-12-amd64 #1 SMP Debian 4.9.210-1 (2020-01-20) x86_64

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Mon Feb 17 12:32:56 2020 from 104.132.189.65
username_domain_com@os-login-instance-1:~$ whoami
username_domain_com
</code>```

or you can use FQDN name (should be resolved) instead of IP.

As we expected full e-mail address was transformed and all dots and special characters was replaced by an underscore accordingly to the documentation:

If a username is not set by a G Suite administrator, OS Login
  generates a default Linux username by combining the username and
  domain from the email associated with the user's Google profile. This
  naming convention ensures uniqueness. For example, if the user email
  associated with the Google profile is user@example.com, then their
  generated username is user_example_com.

```<code>username@domain.com becomes -> username_domain_com
</code>```

and I was able to connect to VM, but with username_domain_com name.

Let's have a look at the documentation how to change username_domain_com into username in the same document:

G Suite organizations can optionally change their default to remove
  the domain suffix for newly generated usernames. For example, if the
  user email associated with the Google profile is user@example.com,
  then their generated username is user. For more information, see
  Managing the OS Login API.

and here you can find more details why it works in that way:

OS Login ties your Linux user account to your Google identity so that
  you have a consistent username, UID, and other posix information, in
  every VM you log into. This allows the VM to authorize your login
  using IAM permissions so that you can easily revoke access. The
  posix information is immutable for consumer identities (non-G Suite
  users). This prevents a bad actor from setting information in a
  malicious way that a project owner cannot manage. In order to prevent
  uniqueness conflicts across different organizations (user@gmail.com
  and user@example.com) the domain name is included by default.

So, you can use username instead of username_domain.com for your G Suite organization, and you can't if you're an individual customer.

Body:
I am testing OS login and created a instance with metadata "enable-oslogin=TRUE". I then added OS Login role to my account(user@mydomainname.com). When I tried:

user@original_host$ gcloud compute ssh my_instance --project my_project --zone my_zone

GCP allowed me login, but as user user_mydomainname instead of my original account "user"

When I tried:

user@original_host$ ssh my_instance, it denied my login.

When I tried:

user@original_host$ ssh user_mydomainname@my_instance, it allowed me login, but as user_mydomainname of course.

I read a bunch of OS login documents from Google and could not figure out the reason. IN one doc: https://cloud.google.com/compute/docs/instances/managing-instance-access#login_messages

At the Expected login behaviors section, it reads "If a username is not set by a G Suite administrator, OS Login generates a default Linux username by combining the username and domain from the email associated with the user's Google profile. This naming convention ensures uniqueness. For example, if the user email associated with the Google profile is user@example.com, then their generated username is user_example_com."

This looks like what I am getting, but I had set OS login role to my account.

I was expecting with the OS login role setup, I could login to the instance as my original account: user

Did I miss anything here or this is indeed the expected behavior? Is is possible to get my account "user" to use OS Login w/o getting user_mydomainname?

Thanks,
Philip

Body:
At first, I've tried to check it OS Login feature on my test VM by following documentation:

create VM instance:

$ gcloud compute instances create os-login-instance-1 --machine-type=n1-standard-1 --zone=europe-west3-a
Created [https://www.googleapis.com/compute/v1/projects/test-prj/zones/europe-west3-a/instances/os-login-instance-1].
NAME                 ZONE            MACHINE_TYPE   PREEMPTIBLE  INTERNAL_IP    EXTERNAL_IP     STATUS
os-login-instance-1  europe-west3-a  n1-standard-1               10.156.15.226  35.XXX.236.XXX  RUNNING

enable OS Login feature for VM:

$ cloud compute instances add-metadata os-login-instance-1 --metadata enable-oslogin=TRUE --zone=europe-west3-a
Updated [https://www.googleapis.com/compute/v1/projects/test-prj/zones/europe-west3-a/instances/os-login-instance-1].

add role roles/compute.osAdminLogin for username@domain.com to make it able to use sudo command:

$ gcloud projects add-iam-policy-binding test-prj \
 --member='user:username@domain.com' \
 --role='roles/compute.osAdminLogin'
Updated IAM policy for project [test-prj].

you can use roles/compute.osLogin for non-root access.

create SSH keys to connect:

$ ssh-keygen
Generating public/private rsa key pair.

upload SSH key to the project:

gcloud compute os-login ssh-keys add --key-file .ssh/id_rsa.pub

connect to your instance:

$ ssh username_domain_com@35.242.236.114

Linux os-login-instance-1 4.9.0-12-amd64 #1 SMP Debian 4.9.210-1 (2020-01-20) x86_64

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Creating directory '/home/username_domain_com'.
username_domain_com@os-login-instance-1:~$

$ gcloud compute ssh os-login-instance-1
Linux os-login-instance-1 4.9.0-12-amd64 #1 SMP Debian 4.9.210-1 (2020-01-20) x86_64

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Mon Feb 17 12:32:56 2020 from 104.132.189.65
username_domain_com@os-login-instance-1:~$ whoami
username_domain_com

or you can use FQDN name (should be resolved) instead of IP.

As we expected full e-mail address was transformed and all dots and special characters was replaced by an underscore accordingly to the documentation:

If a username is not set by a G Suite administrator, OS Login
  generates a default Linux username by combining the username and
  domain from the email associated with the user's Google profile. This
  naming convention ensures uniqueness. For example, if the user email
  associated with the Google profile is user@example.com, then their
  generated username is user_example_com.

username@domain.com becomes -> username_domain_com

and I was able to connect to VM, but with username_domain_com name.

Let's have a look at the documentation how to change username_domain_com into username in the same document:

G Suite organizations can optionally change their default to remove
  the domain suffix for newly generated usernames. For example, if the
  user email associated with the Google profile is user@example.com,
  then their generated username is user. For more information, see
  Managing the OS Login API.

and here you can find more details why it works in that way:

OS Login ties your Linux user account to your Google identity so that
  you have a consistent username, UID, and other posix information, in
  every VM you log into. This allows the VM to authorize your login
  using IAM permissions so that you can easily revoke access. The
  posix information is immutable for consumer identities (non-G Suite
  users). This prevents a bad actor from setting information in a
  malicious way that a project owner cannot manage. In order to prevent
  uniqueness conflicts across different organizations (user@gmail.com
  and user@example.com) the domain name is included by default.

So, you can use username instead of username_domain.com for your G Suite organization, and you can't if you're an individual customer.


问:
Dynamically change background of body in html
In our application, I've to write JSP which I upload to an application and as per JSP UI is reflected.

In this I make API call and get value of Rating which is A, B, C, D or E. I've some code to achieve that and store in variable -

```<code>String reliabilityRating = getRating();
</code>```

Based on rating, I want to change background of the page. CSS are like follows -

```<code>.rating-A {
    line-height: 23px;
    background-color: #00aa00;
}
.rating-B {
    background-color: #b0d513;
}

.rating-C {
    background-color: #eabe06;
}
</code>```

To change background based on rating, I can have html like -

```<code><body class="rating-A">
</code>```

But this is fixed. I want to make it dynamic like rating-X where X can be A, B, C, D or E. Hence I tried calling method which returns rating like

```<code><body class="rating-" + getRating()>
</code>```

But this is not helping to achieve what I want. Could you please suggest how I can change background of page based on value of specific variable?

答:
I think the best approach you can use in this scenario is using a custom data attribute in the body tag that works as metadata and change it from the js file.

Here is a demo:

const body = document.body;

const changeRating = rating => body.setAttribute('data-rating', rating);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {
  height: 100%;
}
[data-rating="A"] {
    line-height: 23px;
    background-color: #00aa00;
}
[data-rating="B"] {
    background-color: #b0d513;
}

[data-rating="C"] {
    background-color: #eabe06;
}</code>```

<button onclick="changeRating('A')">Rating A</button>
<button onclick="changeRating('B')">Rating B</button>
<button onclick="changeRating('C')">Rating C</button>```

Body:
In our application, I've to write JSP which I upload to an application and as per JSP UI is reflected.

In this I make API call and get value of Rating which is A, B, C, D or E. I've some code to achieve that and store in variable -

String reliabilityRating = getRating();

Based on rating, I want to change background of the page. CSS are like follows -

.rating-A {
    line-height: 23px;
    background-color: #00aa00;
}
.rating-B {
    background-color: #b0d513;
}

.rating-C {
    background-color: #eabe06;
}

To change background based on rating, I can have html like -

But this is fixed. I want to make it dynamic like rating-X where X can be A, B, C, D or E. Hence I tried calling method which returns rating like

But this is not helping to achieve what I want. Could you please suggest how I can change background of page based on value of specific variable?

Body:
I think the best approach you can use in this scenario is using a custom data attribute in the body tag that works as metadata and change it from the js file.

Here is a demo:

const body = document.body;

const changeRating = rating => body.setAttribute('data-rating', rating);

html, body {
  height: 100%;
}
[data-rating="A"] {
    line-height: 23px;
    background-color: #00aa00;
}
[data-rating="B"] {
    background-color: #b0d513;
}

[data-rating="C"] {
    background-color: #eabe06;
}

<body data-rating="A">
</body>

<button onclick="changeRating('A')">Rating A</button>
<button onclick="changeRating('B')">Rating B</button>
<button onclick="changeRating('C')">Rating C</button>


问:
In C++, how do i use like strncmp function in C?
In C++, Isn`t there string function like strncmp() in C ???

for example

```<code>string str1 = "abc";
string str2 = "ab";

str2.compare(0,1,str1) == 0
</code>```

is it possible??

答:
You can compare std::string directly:

```<code>if (str1 == str2)
</code>```

To compare up to length 2, use compare:

```<code>if (str2.compare(0, 2, str1) == 0)
</code>```

You can also use C functions in C++ if you include the corresponding C header, for example to use string.h, include <cstring>.

Body:
In C++, Isn`t there string function like strncmp() in C ???

for example

string str1 = "abc";
string str2 = "ab";

str2.compare(0,1,str1) == 0

is it possible??

Body:
You can compare std::string directly:

if (str1 == str2)

To compare up to length 2, use compare:

if (str2.compare(0, 2, str1) == 0)

You can also use C functions in C++ if you include the corresponding C header, for example to use string.h, include <cstring>.


问:
How to compute distance between my original and supplied point in Java
```<code>public class Point {

private double X, Y;

  public Point() {
    setPoint(0.0,0.0);
  }

   public Point (double X, double Y) {
      setPoint(X,Y);
   }

  public void setPoint(double X, double Y) {
    this.X = X;
    this.Y = Y;
  }
  public double getX() {

    return this.X;
  }
  public double getY() {

    return this.Y;
  }

 /**
     * Compute the distance of this Point to the supplied Point x.
     *
     * @param x  Point from which the distance should be measured.
     * @return   The distance between x and this instance
     */
    public double distance(Point x) {

    double d= Math.pow(this.X-X,2)+Math.pow(this.Y-Y,2);
    return Math.sqrt(d);
}
</code>```

I'm trying to compute the distance of my "original point" and my supplied point x. I'm not exactly sure if i'm doing this right. My main concern is:

How do I refer to the coordinates of my original point and the supplied point? The maths here is basic, so I'm confident with that.

Any help is appreciated. PS I'm new to Java.

So also I was thinking of assigning my point the value within the function:

public double distance(Point x) {

    Point x = new Point(X,Y);
    double d= Math.pow(this.X-x.X,2)+Math.pow(this.Y-x.Y,2);
    return Math.sqrt(d);
}
```

Would this be fine?

答:
If you have a class like below:

```<code>public class Point {
    private double x;
    private double y;

    ...constructors and methods omitted
}
</code>```

To calculate distance between your point and another one you can use the java standard method Math.hypot like below:

```<code>public double distance(Point other) {
   return Math.hypot(this.x - other.x, this.y - other.y);
}
</code>```

Body:
public class Point {

private double X, Y;

  public Point() {
    setPoint(0.0,0.0);
  }

   public Point (double X, double Y) {
      setPoint(X,Y);
   }

  public void setPoint(double X, double Y) {
    this.X = X;
    this.Y = Y;
  }
  public double getX() {

    return this.X;
  }
  public double getY() {

    return this.Y;
  }

 /**
     * Compute the distance of this Point to the supplied Point x.
     *
     * @param x  Point from which the distance should be measured.
     * @return   The distance between x and this instance
     */
    public double distance(Point x) {

    double d= Math.pow(this.X-X,2)+Math.pow(this.Y-Y,2);
    return Math.sqrt(d);
}

I'm trying to compute the distance of my "original point" and my supplied point x. I'm not exactly sure if i'm doing this right. My main concern is:

How do I refer to the coordinates of my original point and the supplied point? The maths here is basic, so I'm confident with that.

Any help is appreciated. PS I'm new to Java.

So also I was thinking of assigning my point the value within the function:

public double distance(Point x) {

    Point x = new Point(X,Y);
    double d= Math.pow(this.X-x.X,2)+Math.pow(this.Y-x.Y,2);
    return Math.sqrt(d);
}

Would this be fine?

Body:
If you have a class like below:

public class Point {
    private double x;
    private double y;

    ...constructors and methods omitted
}

To calculate distance between your point and another one you can use the java standard method Math.hypot like below:

public double distance(Point other) {
   return Math.hypot(this.x - other.x, this.y - other.y);
}


问:
compare list values withina python dictionary
I think it is very basic, but I struggle to find a way to solve this.
In a python dictionary like below (where values are lists), how can I conveniently compare values of each key-value pair?
For example, how can I retrieve the key-value pairs where:

Elements of values are not repeated in values of other key-value pairs,

If the first element of the value present in other values, select the pair where the second element of the value in larger.

In other words, I need to get

```<code>"a": ["bc", "5", "0"]
"b": ["nc", "8", "5"]
</code>```

```<code>test_dict = {"a": ["bc", "5", "0"], "b": ["nc", "8", "5"], "c": ["bc", "3", "0"]}
</code>```

Any hint is appreciated.

答:
I would use a comprehension, unpacking all the elements to keep things clean.  Try</p>

```<code>In [1]: out = {k:(v1, v2, v3) for k, (v1, v2, v3) in test_dict.items() if k not in v1 and int(v2) > int(v3)}

In [2]: out
Out[2]: {'a': ('bc', '5', '0'), 'b': ('nc', '8', '5')}
</code>```

Body:
I think it is very basic, but I struggle to find a way to solve this.
In a python dictionary like below (where values are lists), how can I conveniently compare values of each key-value pair?
For example, how can I retrieve the key-value pairs where:

Elements of values are not repeated in values of other key-value pairs,

If the first element of the value present in other values, select the pair where the second element of the value in larger.

In other words, I need to get

"a": ["bc", "5", "0"]
"b": ["nc", "8", "5"]

test_dict = {"a": ["bc", "5", "0"], "b": ["nc", "8", "5"], "c": ["bc", "3", "0"]}

Any hint is appreciated.

Body:
I would use a comprehension, unpacking all the elements to keep things clean.  Try

In [1]: out = {k:(v1, v2, v3) for k, (v1, v2, v3) in test_dict.items() if k not in v1 and int(v2) > int(v3)}

In [2]: out
Out[2]: {'a': ('bc', '5', '0'), 'b': ('nc', '8', '5')}


问:
How to enable Basic Authorization in Iron?
I would like enable Basic Authorization in Iron http server.
I wrote code but is not working correctly. How enable Basic Authorization in Iron Http server? I am asking for an example. </p>

```<code>let mut router = Router::new();
router.get("/json", get_json, "json");

fn get_json(_: &mut Request) -> IronResult<Response> {
    let mut headers = Headers::new();
    headers.set(
       Authorization(
           Basic {
               username: "root".to_owned(),
               password: Some("test".to_owned())
           }
       )
    );
    let payload = "{ \"json\" : \"test\" }".to_string();
    let mut resp = Response::with((status::Ok, payload));
    resp.headers = headers;
    Ok(resp)
}

match Iron::new(router).http(SocketAddrV4::new(Ipv4Addr::new(0, 0, 0, 0), 3000)) {
     Ok(_) => println!("Listening on {}", 3000),
     Err(e) => println!("Error: {}", e),
};
</code>```

答:
I'm solved this problem.

```<code>extern crate iron;

use std::error::Error;
use std::fmt;

use iron::prelude::*;
use iron::{headers, middleware, status, AfterMiddleware, BeforeMiddleware};
use iron::typemap::TypeMap;

#[derive(Debug)]
struct AuthError;

impl fmt::Display for AuthError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt("authentication error", f)
    }
}

impl Error for AuthError {
    fn description(&self) -> &str {
        "authentication error"
    }
}

pub trait CheckAuth {
    fn authorize(&self, user: &str, pass: &str) -> bool;

    #[allow(unused_variables)]
    fn wrong_credentials_error(&self, user: &str, pass: &str) -> &'static str {
        "Wrong username or password."
    }

    fn no_password_error(&self) -> &'static str {
        "No password found."
    }
}

pub struct Authentication {
    username: String,
    password: String
}

impl CheckAuth for Authentication {
    fn authorize(&self, user: &str, pass: &str) -> bool {
        user == self.username && pass == self.password
    }
}

impl CheckAuth for Fn(&str, &str) -> bool {
    fn authorize(&self, user: &str, pass: &str) -> bool {
        self(user, pass)
    }
}

impl BeforeMiddleware for Authentication {
       fn before(&self, req: &mut Request) -> IronResult<()> {
        match req.headers.get::<headers::Authorization<headers::Basic>>() {
            Some(&headers::Authorization(headers::Basic { ref username, password: Some(ref password) })) => {
                if self.authorize(username, password) {
                    Ok(())
                } else {
                    Err(IronError {
                        error: Box::new(AuthError),
                        response: Response::with((status::Unauthorized, self.wrong_credentials_error(username, password)))
                    })
                }
            }
            Some(&headers::Authorization(headers::Basic { username: _, password: None })) => {
                Err(IronError {
                    error: Box::new(AuthError),
                    response: Response::with((status::Unauthorized, self.no_password_error()))
                })
            }
            None => {
                let mut hs = headers::Headers::new();
                hs.set_raw("WWW-Authenticate", vec![b"Basic realm=\"main\"".to_vec()]);
                Err(IronError {
                    error: Box::new(AuthError),
                    response: Response {
                        status: Some(status::Unauthorized),
                        headers: hs,
                        extensions: TypeMap::new(),
                        body: None
                    }
                })
            }
        }
    }
}

fn get_json(_: &mut Request) -> IronResult<Response> {
    let payload = "{ \"json\" : \"test\" }".to_string();
    let mut resp = Response::with((status::Ok, payload));
    Ok(resp)
}

fn main()
{
    let mut chain = Chain::new(get_json);
    chain.link_before(Authentication{username : "test".to_string(), password : "test".to_string()});
    Iron::new(chain).http("localhost:3000");
}
</code>```

Link : Github repo

Body:
I would like enable Basic Authorization in Iron http server.
I wrote code but is not working correctly. How enable Basic Authorization in Iron Http server? I am asking for an example.

let mut router = Router::new();
router.get("/json", get_json, "json");

fn get_json(_: &mut Request) -> IronResult<Response> {
    let mut headers = Headers::new();
    headers.set(
       Authorization(
           Basic {
               username: "root".to_owned(),
               password: Some("test".to_owned())
           }
       )
    );
    let payload = "{ \"json\" : \"test\" }".to_string();
    let mut resp = Response::with((status::Ok, payload));
    resp.headers = headers;
    Ok(resp)
}

match Iron::new(router).http(SocketAddrV4::new(Ipv4Addr::new(0, 0, 0, 0), 3000)) {
     Ok(_) => println!("Listening on {}", 3000),
     Err(e) => println!("Error: {}", e),
};

Body:
I'm solved this problem.

extern crate iron;

use std::error::Error;
use std::fmt;

use iron::prelude::*;
use iron::{headers, middleware, status, AfterMiddleware, BeforeMiddleware};
use iron::typemap::TypeMap;

#[derive(Debug)]
struct AuthError;

impl fmt::Display for AuthError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt("authentication error", f)
    }
}

impl Error for AuthError {
    fn description(&self) -> &str {
        "authentication error"
    }
}

pub trait CheckAuth {
    fn authorize(&self, user: &str, pass: &str) -> bool;

    #[allow(unused_variables)]
    fn wrong_credentials_error(&self, user: &str, pass: &str) -> &'static str {
        "Wrong username or password."
    }

    fn no_password_error(&self) -> &'static str {
        "No password found."
    }
}

pub struct Authentication {
    username: String,
    password: String
}

impl CheckAuth for Authentication {
    fn authorize(&self, user: &str, pass: &str) -> bool {
        user == self.username && pass == self.password
    }
}

impl CheckAuth for Fn(&str, &str) -> bool {
    fn authorize(&self, user: &str, pass: &str) -> bool {
        self(user, pass)
    }
}

impl BeforeMiddleware for Authentication {
       fn before(&self, req: &mut Request) -> IronResult<()> {
        match req.headers.get::<headers::Authorization<headers::Basic>>() {
            Some(&headers::Authorization(headers::Basic { ref username, password: Some(ref password) })) => {
                if self.authorize(username, password) {
                    Ok(())
                } else {
                    Err(IronError {
                        error: Box::new(AuthError),
                        response: Response::with((status::Unauthorized, self.wrong_credentials_error(username, password)))
                    })
                }
            }
            Some(&headers::Authorization(headers::Basic { username: _, password: None })) => {
                Err(IronError {
                    error: Box::new(AuthError),
                    response: Response::with((status::Unauthorized, self.no_password_error()))
                })
            }
            None => {
                let mut hs = headers::Headers::new();
                hs.set_raw("WWW-Authenticate", vec![b"Basic realm=\"main\"".to_vec()]);
                Err(IronError {
                    error: Box::new(AuthError),
                    response: Response {
                        status: Some(status::Unauthorized),
                        headers: hs,
                        extensions: TypeMap::new(),
                        body: None
                    }
                })
            }
        }
    }
}

fn get_json(_: &mut Request) -> IronResult<Response> {
    let payload = "{ \"json\" : \"test\" }".to_string();
    let mut resp = Response::with((status::Ok, payload));
    Ok(resp)
}

fn main()
{
    let mut chain = Chain::new(get_json);
    chain.link_before(Authentication{username : "test".to_string(), password : "test".to_string()});
    Iron::new(chain).http("localhost:3000");
}

Link : Github repo


问:
Connect to ELM327 // Select protocol
I am trying to connect to a ELM327 device via bluetooth.
The library I am using:

https://github.com/eltonvs/java-obd-api

Establishing a bluetooth connection works fine and I can reset the device:

```<code>BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
final BluetoothSocket socket;
try {
     socket = device.createInsecureRfcommSocketToServiceRecord(uuid);
     socket.connect();

     Log.d("xx", "1. Reset");
     ObdResetCommand obdResetCommand = new ObdResetCommand();
     obdResetCommand.run(socket.getInputStream(), socket.getOutputStream());
     System.out.println(obdResetCommand.getFormattedResult());

     Log.d("xx", "2. Echo Off");
     EchoOffCommand echoOffCommand = new EchoOffCommand();
     echoOffCommand.run(socket.getInputStream(), socket.getOutputStream());
     System.out.println(echoOffCommand.getFormattedResult());

     Log.d("xx", "3. LineFeed Off");
     LineFeedOffCommand lineFeedOffCommand = new LineFeedOffCommand();
     lineFeedOffCommand.run(socket.getInputStream(), socket.getOutputStream());
     System.out.println(lineFeedOffCommand.getFormattedResult());
}
</code>```

Output:

D/xx: 1. Reset

  I/System.out: ELM327v1.5

  D/xx: 2. Echo Off

  I/System.out: OK

  D/xx: 3. LineFeed Off
  I/System.out: OK

The part that is not working is to select the protocol and read a voltage value:

```<code>SelectProtocolCommand selectProtocolCommand = new SelectProtocolCommand(ObdProtocols.AUTO);
try {
   selectProtocolCommand.run(socket.getInputStream(), socket.getOutputStream());
} catch (IOException | InterruptedException e) {
    e.printStackTrace();
}

    ModuleVoltageCommand moduleVoltageCommand = new ModuleVoltageCommand();
    try {
        moduleVoltageCommand.run(socket.getInputStream(), socket.getOutputStream());
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
</code>```

What I observe is that the protocol selection is finished very quickly without any output. When I compare the protocol selection part to other apps like "torque lite", this takes much longer and I see flashing lights on my ELM327 device, which is not the case when running my code.

The ModuleVoltageCommand crashes then with:

br.ufrn.imd.obd.exceptions.UnableToConnectException: Error running
  Control Module Power Supply [01 42], response: ...UNABLETOCONNECT

I verified the dongle is working with other apps, so this must be an issue with my code.

What am I doing wrong?

答:
I'm the creator of this library, thanks for using my project!

This is an issue with the ECU, when you change the protocol, the next command will usually fail. What I usually do is sending a dump command that's expected to fail (so you just ignore any raised exception for this command) and then I send the commands I really want to run.

Hope it solves your issue!

Title: Connect to ELM327 // Select protocol

Body:
I am trying to connect to a ELM327 device via bluetooth.
The library I am using:

https://github.com/eltonvs/java-obd-api

Establishing a bluetooth connection works fine and I can reset the device:

BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
final BluetoothSocket socket;
try {
     socket = device.createInsecureRfcommSocketToServiceRecord(uuid);
     socket.connect();

     Log.d("xx", "1. Reset");
     ObdResetCommand obdResetCommand = new ObdResetCommand();
     obdResetCommand.run(socket.getInputStream(), socket.getOutputStream());
     System.out.println(obdResetCommand.getFormattedResult());

     Log.d("xx", "2. Echo Off");
     EchoOffCommand echoOffCommand = new EchoOffCommand();
     echoOffCommand.run(socket.getInputStream(), socket.getOutputStream());
     System.out.println(echoOffCommand.getFormattedResult());

     Log.d("xx", "3. LineFeed Off");
     LineFeedOffCommand lineFeedOffCommand = new LineFeedOffCommand();
     lineFeedOffCommand.run(socket.getInputStream(), socket.getOutputStream());
     System.out.println(lineFeedOffCommand.getFormattedResult());
}

Output:

D/xx: 1. Reset

  I/System.out: ELM327v1.5

  D/xx: 2. Echo Off

  I/System.out: OK

  D/xx: 3. LineFeed Off
  I/System.out: OK

The part that is not working is to select the protocol and read a voltage value:

SelectProtocolCommand selectProtocolCommand = new SelectProtocolCommand(ObdProtocols.AUTO);
try {
   selectProtocolCommand.run(socket.getInputStream(), socket.getOutputStream());
} catch (IOException | InterruptedException e) {
    e.printStackTrace();
}

    ModuleVoltageCommand moduleVoltageCommand = new ModuleVoltageCommand();
    try {
        moduleVoltageCommand.run(socket.getInputStream(), socket.getOutputStream());
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }

What I observe is that the protocol selection is finished very quickly without any output. When I compare the protocol selection part to other apps like "torque lite", this takes much longer and I see flashing lights on my ELM327 device, which is not the case when running my code.

The ModuleVoltageCommand crashes then with:

br.ufrn.imd.obd.exceptions.UnableToConnectException: Error running
  Control Module Power Supply [01 42], response: ...UNABLETOCONNECT

I verified the dongle is working with other apps, so this must be an issue with my code.

What am I doing wrong?


问:
How to identify and convert partial date
I have diversity partial date formats, for instance mm/yy, MMM yyyy and ect.
How to identify and  convert partial date to format yyyy-mm???</p>

答:
As mentioned, you can't do this type of coercion without a day as part of the date, so I think the best option is to add a dummy day value and then coerce to whatever format you need. Just remember to default for nulls as trying to concatenate to a null will error out your script. For example: </p>

```<code>%dw 2.0
output application/json

fun formatDate(date: String): String =
    (date ++ "/01") as Date {format: "MM/yy/dd"} as String {format: "yyyy-MM"}
---
formatDate(payload)
</code>```

Body:
As mentioned, you can't do this type of coercion without a day as part of the date, so I think the best option is to add a dummy day value and then coerce to whatever format you need. Just remember to default for nulls as trying to concatenate to a null will error out your script. For example:

%dw 2.0
output application/json

fun formatDate(date: String): String =
    (date ++ "/01") as Date {format: "MM/yy/dd"} as String {format: "yyyy-MM"}
---
formatDate(payload)


问:
Google script trigger stopped working with permission errors (Code:11:28)
My calendar booking script stopped working in the past week. Checking the error logs, it seems that the trigger is still being fired but I am getting this error:

Exception: The script doesn't have permission to perform that action. Required permission: (https://www.googleapis.com/auth/calendar || https://www.googleapis.com/auth/calendar.readonly || https://www.google.com/calendar/feeds) at unknown function

I have modified my appsscript.json to include the oauth for these three permissions but the script still doesn't work. Can anyone please advise? Thanks.

Contents of appsscript.json:

```<code>{
  "oauthScopes": [
    "https://www.googleapis.com/auth/calendar",
    "https://www.googleapis.com/auth/calendar.readonly",
    "https://www.google.com/calendar/feeds"
  ],
  "timeZone": "Europe/London",
  "dependencies": {
  },
  "webapp": {
    "access": "ANYONE",
    "executeAs": "USER_DEPLOYING"
  },
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8"

}
</code>```

答: You need to open the script inside the Google Script editor, go to the Run menu and choose any function from the dropdown. This will prompt you to authorize the script again and the triggers will function again with the correct permissions.</p>

Body:
My calendar booking script stopped working in the past week. Checking the error logs, it seems that the trigger is still being fired but I am getting this error:

Exception: The script doesn't have permission to perform that action. Required permission: (https://www.googleapis.com/auth/calendar || https://www.googleapis.com/auth/calendar.readonly || https://www.google.com/calendar/feeds) at unknown function

I have modified my appsscript.json to include the oauth for these three permissions but the script still doesn't work. Can anyone please advise? Thanks.

Contents of appsscript.json:

{
  "oauthScopes": [
    "https://www.googleapis.com/auth/calendar",
    "https://www.googleapis.com/auth/calendar.readonly",
    "https://www.google.com/calendar/feeds"
  ],
  "timeZone": "Europe/London",
  "dependencies": {
  },
  "webapp": {
    "access": "ANYONE",
    "executeAs": "USER_DEPLOYING"
  },
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8"

}


问:
Rails ActiveAdmin - change the after update redirect_to
I have a Feature page that belongs to the Car page. That is working exactly how I want to, except for one thing.

After creating, updating or destroying, I want the page to be redirected to the admin_car_path(car) instead of the defaults admin_car_feature_path(car,feature) for create and update and admin_car_features_path(car).

I unsuccessfully searched for that.

```<code>ActiveAdmin.register Car do
end

ActiveAdmin.register Feature do
  belongs_to :car
end
</code>```

TIA

答:
Here is a solution that also works with create_another, using parent and child for model names.

This solution assumes that you show children as part of parent (e.g. via table_for) so you do not need child's index method.

In resource override controller's smart_resource_url and index methods:

```<code>  controller do
    def smart_resource_url
      if create_another?
        new_resource_url(create_another: params[:create_another])
      else
        parent_path(params[:parent_id])
      end
    end

    def index
      redirect_to parent_path(params[:parent_id])
    end
  end
</code>```

Body:
I have a Feature page that belongs to the Car page. That is working exactly how I want to, except for one thing.

After creating, updating or destroying, I want the page to be redirected to the admin_car_path(car) instead of the defaults admin_car_feature_path(car,feature) for create and update and admin_car_features_path(car).

I unsuccessfully searched for that.

ActiveAdmin.register Car do
end

ActiveAdmin.register Feature do
  belongs_to :car
end

TIA

Body:
Here is a solution that also works with create_another, using parent and child for model names.

This solution assumes that you show children as part of parent (e.g. via table_for) so you do not need child's index method.

In resource override controller's smart_resource_url and index methods:

  controller do
    def smart_resource_url
      if create_another?
        new_resource_url(create_another: params[:create_another])
      else
        parent_path(params[:parent_id])
      end
    end

    def index
      redirect_to parent_path(params[:parent_id])
    end
  end