问:
Adding ld+json script tags in Angular2 component template
I have tried too many tricky ways,
such as Renderer2 or ɵDomAdapter,
the script tag is integrated well in the html,
but when loading the url with the structured-data tool of google,
the ld+json script is not rendered !

Is there a way to make google render the page after loading the component ?

答:
There are a couple of ways to achieve this. The code below is the best solution I have come up with. This example will also work with Angular Universal.

import { Component, OnInit } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Component({
  selector: 'app-root',
  template: '

'
})
export class JsonLdComponent implements OnChanges {
  jsonLD: SafeHtml;
  constructor(private sanitizer: DomSanitizer) { }

  ngOnInit(changes: SimpleChanges) {
    const json = {
      "@context": "http://schema.org",
      "@type": "Organization",
      "url": "https://google.com",
      "name": "Google",
      "contactPoint": {
        "@type": "ContactPoint",
        "telephone": "+1-000-000-0000",
        "contactType": "Customer service"
      }
    };

    // Basically telling Angular this content is safe to directly inject into the dom with no sanitization
    this.jsonLD = this.getSafeHTML(json);
  }

  getSafeHTML(value: {}) {
    const json = JSON.stringify(value, null, 2);
    const html = `${json}`;
    // Inject to inner html without Angular stripping out content
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }
}
```

I go into more detail in this blog post here https://coryrylan.com/blog/angular-seo-with-schema-and-json-ld

I also took this technique and wrapped it up into a npm package to make
it more reusable. https://github.com/coryrylan/ngx-json-ld

Body:
There are a couple of ways to achieve this. The code below is the best solution I have come up with. This example will also work with Angular Universal.

import { Component, OnInit } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Component({
  selector: 'app-root',
  template: '<div [innerHTML]="jsonLD"></div>'
})
export class JsonLdComponent implements OnChanges {
  jsonLD: SafeHtml;
  constructor(private sanitizer: DomSanitizer) { }

  ngOnInit(changes: SimpleChanges) {
    const json = {
      "@context": "http://schema.org",
      "@type": "Organization",
      "url": "https://google.com",
      "name": "Google",
      "contactPoint": {
        "@type": "ContactPoint",
        "telephone": "+1-000-000-0000",
        "contactType": "Customer service"
      }
    };

    // Basically telling Angular this content is safe to directly inject into the dom with no sanitization
    this.jsonLD = this.getSafeHTML(json);
  }

  getSafeHTML(value: {}) {
    const json = JSON.stringify(value, null, 2);
    const html = `${json}`;
    // Inject to inner html without Angular stripping out content
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }
}

I go into more detail in this blog post here https://coryrylan.com/blog/angular-seo-with-schema-and-json-ld

I also took this technique and wrapped it up into a npm package to make
it more reusable. https://github.com/coryrylan/ngx-json-ld


来源: stackexchange

问:
Print Byte Array Vertically in C
I have 4 byte arrays containing 4 bytes each, and when I print them they print horizontally, but I need them to print vertically. Is this possible in C? I know when I use printf() and pass it the array, it prints all four bytes automatically. Can I sub-divide the array into four separate bytes like a normal array and print each byte on a separate line? There has to be a way.

To illustrate what I am doing, here is the segment that I am having trouble with:

```<code>    byte a0 = state[0];
    byte a1 = state[1];
    byte a2 = state[2];
    byte a3 = state[3];
    state[0] = lookup_g2[a0] ^ lookup_g3[a1] ^ a2 ^ a3;
    state[1] = lookup_g2[a1] ^ lookup_g3[a2] ^ a3 ^ a0;
    state[2] = lookup_g2[a2] ^ lookup_g3[a3] ^ a0 ^ a1;
    state[3] = lookup_g2[a3] ^ lookup_g3[a0] ^ a1 ^ a2;
    for (int i = 0; i < 4; i++)
    {
        printf("%02x", state[i]);
    }
    printf("%s", "\n");
</code>```

This prints each byte array in its entirety on each line until main()ends. Preferably, I would like to print each array in groups of four vertically.

Also, I know there is sprintf() which I was recommended to use but for now I'm using printf() until I can figure out how to print vertically.

Example:

```<code>printf("%02x", state[0]);
</code>```

yields:

```<code>b9 e4 47 c5
</code>```

The output I am looking for is:

```<code>b9
e4
47
c5
</code>```

and then the following iterations will print their values next to the first column as shown above. Is this possible?

答:
Then how do you print the next line of bytes in a column next to the
  first up to four columns then move to a new line?

If I follow what you are attempting to do, you have 4 state arrays (or 4 rows and columns of something) and you want to output the first line with the first element of each (one in each column), the next line (one element in each column), and so on. If you want to output each value individually, then you will need nested loops, outputting one value at a time in the inner loop (printing each element in a column), then output the '\n' once the inner loop completes.

Something like the following:

```<code>#include <stdio.h>

typedef unsigned char byte;

int main (void) {

    byte state[] = { 0xb9, 0xe4, 0x47, 0xc5 },
        n = sizeof state / sizeof *state;

    for (byte i = 0; i < n; i++) {              /* outer loop */
        for (byte j = 0; j < n; j++)            /* inner loop */
            printf (" %02x", state[(j+i)%n]);   /* stuff      */
        putchar ('\n'); /* newline after inner loop completes */
    }

    return 0;
}
</code>```

Example Use/Output

```<code>$ ./bin/byteperline
 b9 e4 47 c5
 e4 47 c5 b9
 47 c5 b9 e4
 c5 b9 e4 47
</code>```

note: I just used the values from the first array 4-times to construct the four columns. You will adjust your indexing scheme to whatever is called for by your data (e.g. to print rows as columns or columns as rows) Regardless how you do it, you must output the values in a row-wise manner. You can't print a column and then back up 4-lines and offset by 5 chars and print the next column. (I mean you can, but that is well-beyond your question and would require a separate curses library to do in a portable fashion)

Look things over and let me know if this is what you intended.

ContentLicense: CC BY-SA 3.0

Title: Print Byte Array Vertically in C

Body:
I have 4 byte arrays containing 4 bytes each, and when I print them they print horizontally, but I need them to print vertically. Is this possible in C? I know when I use printf() and pass it the array, it prints all four bytes automatically. Can I sub-divide the array into four separate bytes like a normal array and print each byte on a separate line? There has to be a way.

To illustrate what I am doing, here is the segment that I am having trouble with:

    byte a0 = state[0];
    byte a1 = state[1];
    byte a2 = state[2];
    byte a3 = state[3];
    state[0] = lookup_g2[a0] ^ lookup_g3[a1] ^ a2 ^ a3;
    state[1] = lookup_g2[a1] ^ lookup_g3[a2] ^ a3 ^ a0;
    state[2] = lookup_g2[a2] ^ lookup_g3[a3] ^ a0 ^ a1;
    state[3] = lookup_g2[a3] ^ lookup_g3[a0] ^ a1 ^ a2;
    for (int i = 0; i < 4; i++)
    {
        printf("%02x", state[i]);
    }
    printf("%s", "\n");

This prints each byte array in its entirety on each line until main()ends. Preferably, I would like to print each array in groups of four vertically.

Also, I know there is sprintf() which I was recommended to use but for now I'm using printf() until I can figure out how to print vertically.

Example:

printf("%02x", state[0]);

yields:

b9 e4 47 c5

The output I am looking for is:

b9
e4
47
c5

and then the following iterations will print their values next to the first column as shown above. Is this possible?

Body:
Then how do you print the next line of bytes in a column next to the
  first up to four columns then move to a new line?

If I follow what you are attempting to do, you have 4 state arrays (or 4 rows and columns of something) and you want to output the first line with the first element of each (one in each column), the next line (one element in each column), and so on. If you want to output each value individually, then you will need nested loops, outputting one value at a time in the inner loop (printing each element in a column), then output the '\n' once the inner loop completes.

Something like the following:

#include <stdio.h>

typedef unsigned char byte;

int main (void) {

    byte state[] = { 0xb9, 0xe4, 0x47, 0xc5 },
        n = sizeof state / sizeof *state;

    for (byte i = 0; i < n; i++) {              /* outer loop */
        for (byte j = 0; j < n; j++)            /* inner loop */
            printf (" %02x", state[(j+i)%n]);   /* stuff      */
        putchar ('\n'); /* newline after inner loop completes */
    }

    return 0;
}

Example Use/Output

$ ./bin/byteperline
 b9 e4 47 c5
 e4 47 c5 b9
 47 c5 b9 e4
 c5 b9 e4 47

note: I just used the values from the first array 4-times to construct the four columns. You will adjust your indexing scheme to whatever is called for by your data (e.g. to print rows as columns or columns as rows) Regardless how you do it, you must output the values in a row-wise manner. You can't print a column and then back up 4-lines and offset by 5 chars and print the next column. (I mean you can, but that is well-beyond your question and would require a separate curses library to do in a portable fashion)

Look things over and let me know if this is what you intended.


问:
wso2esb- accessing variable outside iterator mediator
Basically, inside iterator, I am setting some variable using Script (name: setValue) mediator.  I am trying to access them in the Ruby script outside the iterator.

According to the documentation: How to access property mediator outside iterator which is defined inside iterator?

Different options I tried:

1)  In Ruby script,  I tried using

```<code>$mc.get-property('Operation','githubhosturl1');  I am getting syntax error at operation.
</code>```

2)  Outside Iterator  I tried accessing them using Property

```<code><property   expression="get-property('operation','githubhosturl')  name="githubhosturl1)
</code>```

getting an error at expression.

3)  In Ruby script I tried:

$mc.get-property('githubhosturl1') - Empty value returning

How can I solve this issue?

My code  - proxy service -  I am pasting only small portion, where there is an issue.  In setValue script I am able to print the value in the console log.

```<code><Iterator>
-------
--------
-------
<script description="setValue" language="js"><![CDATA[var log = mc.getServiceLog();
            var tool =  mc.getProperty('toolList');

           if( tool == "github")
           {
                var vhosturl = mc.getProperty('catName');
                mc.setProperty('githubhosturl',vhosturl.toString());
                var vassetid = mc.getProperty('assetidval');
                mc.setProperty('gitassetid',vassetid.toString());
                var vbranch="qa";
                mc.setProperty('gitbranch',vbranch.toString());
           }
           if( tool == "dockercloud")
           {
                var vhosturl = mc.getProperty('catName');
                mc.setProperty('dockerhosturl',vhosturl.toString());
                var vassetid = mc.getProperty('assetidval');
                mc.setProperty('dockerid',vassetid.toString());
                var creid = mc.getProperty('jsondata');
                mc.setProperty('doccredid',creid.toString());
                var vprojName = mc.getProperty('projName');
                mc.setProperty('docproj',vprojName.toString());
           }]]></script>
        <property expression="get-property('githubhosturl')" name="githubhosturl1" scope="operation" type="STRING"/>
        <property expression="get-property('gitbranch')" name="gitbranch1" scope="operation" type="STRING"/>
        <property expression="get-property('gitassetid')" name="gitassetid1" scope="operation" type="STRING"/>
        <property expression="get-property('dockerhosturl')" name="dockerhosturl1" scope="operation" type="STRING"/>
        <property expression="get-property('doccredid')" name="doccredid1" scope="operation" type="STRING"/>
        <property expression="get-property('docproj')" name="docproj1" scope="operation" type="STRING"/>
    </sequence>
</target>
</iterate>
<script description="re" language="rb"><![CDATA[require 'erb'
     require 'erb'

     @giturl = $mc.getProperty('githubhosturl1');
      @gitbranch = $mc.getProperty('gitbranch1');
      @gitcredential = $mc.getProperty('gitassetid1');

      @dockerurl = $mc.getProperty('dockerhosturl1');
      @dockerCred = $mc.getProperty('doccredid1');
      @dockerprojectname = $mc.getProperty('docproj1');

      @template = File.read('C:\WS02\workspace\index.txt.erb')
      OutTemplate = ERB.new(@template).result( binding )

      File.open('C:\WS02\workspace\Jenkin.groovy',"w") do |f|
         f.puts OutTemplate
      end]]></script>
</code>```

答: By changing all the scope inside the Iteration from "default" to "Operation"  and access them outside using  get-property('operation', variable) and then change the scope to "Default"</p>

Body:
Basically, inside iterator, I am setting some variable using Script (name: setValue) mediator.  I am trying to access them in the Ruby script outside the iterator.

According to the documentation: How to access property mediator outside iterator which is defined inside iterator?

Different options I tried:

1)  In Ruby script,  I tried using

$mc.get-property('Operation','githubhosturl1');  I am getting syntax error at operation.

2)  Outside Iterator  I tried accessing them using Property

<property   expression="get-property('operation','githubhosturl')  name="githubhosturl1)

getting an error at expression.

3)  In Ruby script I tried:

$mc.get-property('githubhosturl1') - Empty value returning

How can I solve this issue?

My code  - proxy service -  I am pasting only small portion, where there is an issue.  In setValue script I am able to print the value in the console log.

<Iterator>
-------
--------
-------

        <property expression="get-property('githubhosturl')" name="githubhosturl1" scope="operation" type="STRING"/>
        <property expression="get-property('gitbranch')" name="gitbranch1" scope="operation" type="STRING"/>
        <property expression="get-property('gitassetid')" name="gitassetid1" scope="operation" type="STRING"/>
        <property expression="get-property('dockerhosturl')" name="dockerhosturl1" scope="operation" type="STRING"/>
        <property expression="get-property('doccredid')" name="doccredid1" scope="operation" type="STRING"/>
        <property expression="get-property('docproj')" name="docproj1" scope="operation" type="STRING"/>
    </sequence>
</target>
</iterate>


问:
Unity - Raycast distance doesn't change
I'm trying to detect the ground ahead of a cube that doens't have boxcollider or rigid body. I can detect it ok but the distance never changes. I can use very big number or very small ones that it still detects the ground at the same distance.

The debug lines are working fine and nothing is detected before the ground. Even trying raycast without distance keeps the detection at the same distance.
I tried some other variations of the method Raycast with the same results.

Here is my script:

```<code>Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hitInfo;
Debug.DrawRay(pos, transform.forward * detectDistance, Color.green);
if (Physics.Raycast(ray,out hitInfo, detectDistance)) {
       Debug.Log(hitInfo.transform.name);
       Debug.DrawRay(pos, transform.forward * detectDistance, Color.red);
}
</code>```

答:
If your main goal is to calculate the distance between two GameObjects (cube and ground), the use of Raycast is not a must. You can follow this other approach:

```<code>Vector3 dist = Vector.distance(cube.transform.position, ground.transform.position);
Debug.Log(string.Format("Distance between {0} and {1} is: {2}", cube, ground, dist));
</code>```

However if you want to keep with the Raycast, without having all the information about how is your scene and how are the gameObjects located, I can only recommend you to try the following things:

1- Calculate the direction of the Ray like this:

```<code>Vector3 direction = ( cube.transform.position - ground.transform.position ).normalized;
Ray ray = new Ray( cube.transform.position, direction );
</code>```

2- Calculate the distance from hit:

```<code>if (Physics.Raycast(downRay, out hit)) {
   float distance = hit.distance;
}
</code>```

3- And just in case calculate the distance from void FixedUpdate()

Title: Unity - Raycast distance doesn't change

Body:
I'm trying to detect the ground ahead of a cube that doens't have boxcollider or rigid body. I can detect it ok but the distance never changes. I can use very big number or very small ones that it still detects the ground at the same distance.

The debug lines are working fine and nothing is detected before the ground. Even trying raycast without distance keeps the detection at the same distance.
I tried some other variations of the method Raycast with the same results.

Here is my script:

Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hitInfo;
Debug.DrawRay(pos, transform.forward * detectDistance, Color.green);
if (Physics.Raycast(ray,out hitInfo, detectDistance)) {
       Debug.Log(hitInfo.transform.name);
       Debug.DrawRay(pos, transform.forward * detectDistance, Color.red);
}

Body:
If your main goal is to calculate the distance between two GameObjects (cube and ground), the use of Raycast is not a must. You can follow this other approach:

Vector3 dist = Vector.distance(cube.transform.position, ground.transform.position);
Debug.Log(string.Format("Distance between {0} and {1} is: {2}", cube, ground, dist));

However if you want to keep with the Raycast, without having all the information about how is your scene and how are the gameObjects located, I can only recommend you to try the following things:

1- Calculate the direction of the Ray like this:

Vector3 direction = ( cube.transform.position - ground.transform.position ).normalized;
Ray ray = new Ray( cube.transform.position, direction );

2- Calculate the distance from hit:

if (Physics.Raycast(downRay, out hit)) {
   float distance = hit.distance;
}

3- And just in case calculate the distance from void FixedUpdate()


答: IIRC, one of the goals of the text output from the SVN command line tools was that they be regular and machine parsable in addition to being human readable.  I just took a quick peek at the latest docs, and the format looks identical to what I remember reading about several years ago</p>

ContentLicense: CC BY-SA 2.5

Title: Output of svn log -v

Body:
I just wonna know if the output of the command svn log -v is always the same. For me it looks like:

------------------------------------------------------------------------
r2 | username | 2011-01-16 16:52:23 +0100 (Sun, 16 Jan 2011) | 1 line
Changed paths:
   D /foo
Removed foo
------------------------------------------------------------------------
r1 | balzarot | 2011-01-16 16:51:03 +0100 (Sun, 16 Jan 2011) | 1 line
Changed paths:
   A /foo
created foo
------------------------------------------------------------------------

but I don't know if it is always like that, especially the format of the date!
Can you help me please
thnx


问:
Overlay Image(s) & Text on PixiJS Particle Container?
I'm a beginner web developer creating my first personal portfolio page. I'm trying to use this particle container as a sort of background hero "video."

Codepen.io - https://codepen.io/erikterwan/pen/VpjVvZ

HTML:

```<code><div id="fps"></div>
</code>```

CSS:

```<code>html, body {
    margin: 0;
    padding: 0;
}

#fps {
    position: absolute;
    bottom: 5px;
    right: 5px;

    font-family: sans-serif;
    font-size: 12px;
    text-transform: uppercase;
    color: #fff;
    color: rgba(255,255,255,0.5);

    z-index: 2;
}
</code>```

I'll omit the JS for now since it's pretty long, but it's there in the Codepen if you want to take a look (and see what the particle container actually looks like).

I've been trying to overlay an image and text over the container (like my picture with my name under it), but they either just go above or under it, or disappear entirely (I assumed behind it).

My HTML:

```<code><div class="container-fluid">
    <div id="fps"></div>
    <div class="row">
        <div class="col-lg-3 col-lg-offset-4">
            <img id="profile-image" src="http://alloutput.com/wp-content/uploads/2013/11/black-circle-mask-to-fill-compass-outline.png">
    </div>
</div>
</code>```

My CSS:

```<code>html {
    font-family: 'Raleway', sans-serif;
}
/* Navbar Stuff Here */
#fps {
    color: #fff;
    color: rgba(255,255,255,0.5);
    z-index: 2;
}
#profile-image {
    border-radius: 100%;
    height: 150px;
    background-color: yellow;
}
</code>```

I haven't modified any of the JS.

Would really appreciate if anyone could give some insight or point me in the right direction to figure out this problem!

答:
You just have to absolutely position your
:

```<code>.container-fluid{
    z-index:1;
    position: absolute;

}
</code>```

Body:
I'm a beginner web developer creating my first personal portfolio page. I'm trying to use this particle container as a sort of background hero "video."

Codepen.io - https://codepen.io/erikterwan/pen/VpjVvZ

HTML:

CSS:

html, body {
    margin: 0;
    padding: 0;
}

#fps {
    position: absolute;
    bottom: 5px;
    right: 5px;

    font-family: sans-serif;
    font-size: 12px;
    text-transform: uppercase;
    color: #fff;
    color: rgba(255,255,255,0.5);

    z-index: 2;
}

I'll omit the JS for now since it's pretty long, but it's there in the Codepen if you want to take a look (and see what the particle container actually looks like).

I've been trying to overlay an image and text over the container (like my picture with my name under it), but they either just go above or under it, or disappear entirely (I assumed behind it).

My HTML:

My CSS:

html {
    font-family: 'Raleway', sans-serif;
}
/* Navbar Stuff Here */
#fps {
    color: #fff;
    color: rgba(255,255,255,0.5);
    z-index: 2;
}
#profile-image {
    border-radius: 100%;
    height: 150px;
    background-color: yellow;
}

I haven't modified any of the JS.

Would really appreciate if anyone could give some insight or point me in the right direction to figure out this problem!

Body:
You just have to absolutely position your <div>:

.container-fluid{
    z-index:1;
    position: absolute;

}


问:
Uploading image by using Retrofit
I've been trying to upload an image from my application through API. But I keep getting this as response:

```<code>{"error":"<p>You did not select a file to upload.<\/p>"}
</code>```

This is my code:

APIService.java

```<code>@Multipart
@POST("/media/upload.html")
Call<UploadImg> uploadimage (@Part MultipartBody.Part file);
</code>```

UploadImageActivity.java

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null){
        Uri uri = data.getData();
        Picasso.with(this).load(uri).fit().into(btn_img_picker);

        String imagePath;

        if (data.toString().contains("content:")) {
            imagePath = getRealPathFromURI(uri);
        } else if (data.toString().contains("file:")) {
            imagePath = uri.getPath();
        } else {
            imagePath = null;
        }

        File file = new File(imagePath);

        System.out.println(imagePath);

        RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);

        MultipartBody.Part body = MultipartBody.Part.createFormData("userfile", file.getName(), requestFile);

        System.out.println(file.getName());

        Call<UploadImg> call = mAPIService.uploadimage(body);
        call.enqueue(new Callback<UploadImg>() {
            @Override
            public void onResponse(Call<UploadImg> call, Response<UploadImg> response) {
                System.out.println(response.raw());
            }

            @Override
            public void onFailure(Call<UploadImg> call, Throwable t) {
                System.out.println(t);
            }
        });
    }
}

public String getRealPathFromURI(Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = {MediaStore.Images.Media.DATA};
        cursor = getContentResolver().query(contentUri, proj, null, null,
                null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}
</code>```

I have tested sending image in Postman's form-data. I can send a picture from my desktop and received intended response. But I can't do the same with my code in android.

Am I sending the incorrect path format of the image? Currently, variable imagePath has an output like this:

```<code>/storage/emulated/0/Download/download.jpg
</code>```

If this is the incorrect path to send, please tell the correct one. Thanks in advance.

答:
try this

```<code> @Multipart @POST("user/updateprofile") Observable<ResponseBody>
 updateProfile(@Part("user_id") RequestBody id, @Part("full_name")
 RequestBody fullName, @Part MultipartBody.Part image, @Part("other")
 RequestBody other);
</code>```

pass it like this

```<code>File file = new File("/storage/emulated/0/Download/Corrections 6.jpg"); RequestBody
requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
</code>```

add another part within the multipart request

```<code> RequestBody fullName =  RequestBody.create(  MediaType.parse("multipart/form-data"), "Your Name");
 service.updateProfile(id, fullName, body, other)
</code>```

Title: Uploading image by using Retrofit

Body:
I've been trying to upload an image from my application through API. But I keep getting this as response:

{"error":"
You did not select a file to upload.<\/p>"}

This is my code:

APIService.java

@Multipart
@POST("/media/upload.html")
Call<UploadImg> uploadimage (@Part MultipartBody.Part file);

UploadImageActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null){
        Uri uri = data.getData();
        Picasso.with(this).load(uri).fit().into(btn_img_picker);

        String imagePath;

        if (data.toString().contains("content:")) {
            imagePath = getRealPathFromURI(uri);
        } else if (data.toString().contains("file:")) {
            imagePath = uri.getPath();
        } else {
            imagePath = null;
        }

        File file = new File(imagePath);

        System.out.println(imagePath);

        RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);

        MultipartBody.Part body = MultipartBody.Part.createFormData("userfile", file.getName(), requestFile);

        System.out.println(file.getName());

        Call<UploadImg> call = mAPIService.uploadimage(body);
        call.enqueue(new Callback<UploadImg>() {
            @Override
            public void onResponse(Call<UploadImg> call, Response<UploadImg> response) {
                System.out.println(response.raw());
            }

            @Override
            public void onFailure(Call<UploadImg> call, Throwable t) {
                System.out.println(t);
            }
        });
    }
}

public String getRealPathFromURI(Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = {MediaStore.Images.Media.DATA};
        cursor = getContentResolver().query(contentUri, proj, null, null,
                null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

I have tested sending image in Postman's form-data. I can send a picture from my desktop and received intended response. But I can't do the same with my code in android.

Am I sending the incorrect path format of the image? Currently, variable imagePath has an output like this:

/storage/emulated/0/Download/download.jpg

If this is the incorrect path to send, please tell the correct one. Thanks in advance.

Body:
try this

 @Multipart @POST("user/updateprofile") Observable<ResponseBody>
 updateProfile(@Part("user_id") RequestBody id, @Part("full_name")
 RequestBody fullName, @Part MultipartBody.Part image, @Part("other")
 RequestBody other);

pass it like this

File file = new File("/storage/emulated/0/Download/Corrections 6.jpg"); RequestBody
requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);

add another part within the multipart request

 RequestBody fullName =  RequestBody.create(  MediaType.parse("multipart/form-data"), "Your Name");
 service.updateProfile(id, fullName, body, other)


问:
sum up a list using stream
For the following data -

```<code>int[] array = {56,67,78,89,90,12,23};
List<Integer> list= new ArrayList<Integer>(Arrays.asList(array));
</code>```

Why is there a difference in the below:

```<code>int sum1 = Arrays.stream(array).sum();

int sum2 = list.stream().mapToInt(Integer::intValue).sum();
</code>```

Why cant the second option be list.stream().sum() without the extra conversion?

答:
the confusing part is here, because

Arrays.stream(array) and list.stream() are not producing the same result.. those return actually completely different streams.

the long answer is:

when you do this:

Arrays.stream(array) you get back a IntStream that is basically a stream of integers, so that objects has a method sum() that let you do the addition acumulative of all its elements..

but not every stream of T allows to concate Ts so that method is not avaliable in a normal stream, one option is to pass the stream over a function that convert those into a new stream... that is what mapToInt does.

Title: sum up a list using stream

Body:
For the following data -

int[] array = {56,67,78,89,90,12,23};
List<Integer> list= new ArrayList<Integer>(Arrays.asList(array));

Why is there a difference in the below:

int sum1 = Arrays.stream(array).sum();

int sum2 = list.stream().mapToInt(Integer::intValue).sum();

Why cant the second option be list.stream().sum() without the extra conversion?


问:
How to access variables from base workspace within function?
I am a nested function inside a function and I am calling variables from base workspace. Note that guiel is in base workspace.

```<code>function callback(~,~)
    vars.dropheight = str2num(get(edit(2),'String'));
    vars.armradius = str2num(get(edit(1),'String'));
    kiddies = get(guiel.hAX(3),'Children');
    delete(kiddies);
    clear kiddies;
    set(guiel.tfPanel,'Visible','off','Position',cnst.tfPanelpos);
    set(guiel.hAX(1),'Position',cnst.axpos1);
    if ishandle(guiel.hAX(2))
    set(guiel.hAX(2),'Position',cnst.axpos2);
    end
    eval(get(guiel.hPB(4),'Callback'));
end
</code>```

答:
Best practices for GUI design are that you encapsulate your GUI and its operations in such a way that it never has to depend on the base workspace to function correctly. The reason? The user and other programs can modify anything in the base workspace, and can thus easily break your GUI.

I give an example of a basic GUI setup using nested functions in this post. Here's a general skeleton for designing a GUI:

```<code>function create_GUI()

  % Initialize data:
  data1 = ...;
  data2 = ...;

  % Create GUI:
  hFigure = figure;
  hObject1 = uicontrol(..., 'Callback', @callback1);
  hObject2 = uicontrol(..., 'Callback', @callback2);
  ....

  function callback1(~, ~)
    % Access any data or handles from above
    ...
  end

  function callback1(~, ~)
    % Access any data or handles from above
    ...
  end

end
</code>```

The idea is that the main function creates all the GUI components, initializing all the needed data and object handles. The callbacks nested within the main function will have access to the data and handles as needed. I suggest designing your GUI like this, or using one of the other options listed here. This should alleviate some of your data access issues and make your GUI more robust.

Body:
I am a nested function inside a function and I am calling variables from base workspace. Note that guiel is in base workspace.

function callback(~,~)
    vars.dropheight = str2num(get(edit(2),'String'));
    vars.armradius = str2num(get(edit(1),'String'));
    kiddies = get(guiel.hAX(3),'Children');
    delete(kiddies);
    clear kiddies;
    set(guiel.tfPanel,'Visible','off','Position',cnst.tfPanelpos);
    set(guiel.hAX(1),'Position',cnst.axpos1);
    if ishandle(guiel.hAX(2))
    set(guiel.hAX(2),'Position',cnst.axpos2);
    end
    eval(get(guiel.hPB(4),'Callback'));
end

Body:
Best practices for GUI design are that you encapsulate your GUI and its operations in such a way that it never has to depend on the base workspace to function correctly. The reason? The user and other programs can modify anything in the base workspace, and can thus easily break your GUI.

I give an example of a basic GUI setup using nested functions in this post. Here's a general skeleton for designing a GUI:

function create_GUI()

  % Initialize data:
  data1 = ...;
  data2 = ...;

  % Create GUI:
  hFigure = figure;
  hObject1 = uicontrol(..., 'Callback', @callback1);
  hObject2 = uicontrol(..., 'Callback', @callback2);
  ....

  function callback1(~, ~)
    % Access any data or handles from above
    ...
  end

  function callback1(~, ~)
    % Access any data or handles from above
    ...
  end

end

The idea is that the main function creates all the GUI components, initializing all the needed data and object handles. The callbacks nested within the main function will have access to the data and handles as needed. I suggest designing your GUI like this, or using one of the other options listed here. This should alleviate some of your data access issues and make your GUI more robust.


问:
Strange SQL Performance: Parameter slower than Function call
I've had a project dumped in my lap, and I'm pretty far outside of my element.  There is a table with roughly 10,000,000 rows that is being queried.  There is one query in particular that is taking too long to run, and is timing out.  The query generated by Linq is

```<code>-- Region Parameters
DECLARE @p0 Int = 335
DECLARE @p1 DateTime = DATEADD(day,-7,GETDATE())
-- EndRegion
SELECT *
FROM [Events] AS [t0],
    [Devices] AS [t1],
    [EventTypes] AS [t2],
    [DeviceTypes] AS [t3]
WHERE ([t1].[DeviceID] = [t0].[DeviceID])
    AND ([t2].[EventTypeID] = [t0].[EventTypeID])
    AND ([t3].[DeviceTypeID] = [t1].[DeviceTypeID])
    AND ([t1].[RoomID] = @p0)
    AND ([t0].[EventTime] >= @p1)
</code>```

If I change the last line to be [t0].[EventTime] >= DATEADD(day,-7,GETDATE()) instead of using the variable @p1, the query goes from taking 45 seconds to run, to taking 3 seconds to run.

My two questions are 1) Why does this simple change increase performance so drastically and 2) is there a way to force Linq to not use the variable and inline the datetime object?

The Linq code is C# .NET 3.5 and the server is MSSQL 2005

Edit: I added the SELECT * for brevity, the actual query does not do that.

答:
10.0.1600 is SQL Server 2008 RTM.  Try upgrading to SP2 (which is a good idea anyways!).

Often when I run into weird optimization issues I've found that the SQL Server is out of date and a newer SP resolves the issues.  Not always, but often.

Body:
I've had a project dumped in my lap, and I'm pretty far outside of my element.  There is a table with roughly 10,000,000 rows that is being queried.  There is one query in particular that is taking too long to run, and is timing out.  The query generated by Linq is

-- Region Parameters
DECLARE @p0 Int = 335
DECLARE @p1 DateTime = DATEADD(day,-7,GETDATE())
-- EndRegion
SELECT *
FROM [Events] AS [t0],
    [Devices] AS [t1],
    [EventTypes] AS [t2],
    [DeviceTypes] AS [t3]
WHERE ([t1].[DeviceID] = [t0].[DeviceID])
    AND ([t2].[EventTypeID] = [t0].[EventTypeID])
    AND ([t3].[DeviceTypeID] = [t1].[DeviceTypeID])
    AND ([t1].[RoomID] = @p0)
    AND ([t0].[EventTime] >= @p1)

If I change the last line to be [t0].[EventTime] >= DATEADD(day,-7,GETDATE()) instead of using the variable @p1, the query goes from taking 45 seconds to run, to taking 3 seconds to run.

My two questions are 1) Why does this simple change increase performance so drastically and 2) is there a way to force Linq to not use the variable and inline the datetime object?

The Linq code is C# .NET 3.5 and the server is MSSQL 2005

Edit: I added the SELECT * for brevity, the actual query does not do that.


问:
How to debug Android's native browser (not Chrome) on a desktop machine?
I can successfully debug the front end of a web application running on a mobile device using Google's Chrome DevTools (chrome://inspect) when my mobile device is using the Chrome's browser (using port forwarding). I was wondering whether it is possible to do the same using the Android's native browser, I mean the one browser pre-installed in Android which application launcher looks like this, just to be more clear, :-) :

Is there a way to do that? Cause when I open a tab with this browser inside chrome://inspect of course I don't get the opened tab and I can't inspect the content my device is viewing from the native browser.

I need in a way to do that because I have found some UI related problems (CSS, JS) specifically bound to the native browser, actually in chrome all works beautifully, but on the native browser no.

I have also tried to use weinre and found it very useful, but I can use it only in the context of a LAN, meaning that I have to bind the device with a LAN IP address and actually I need to access to the web application from http://localhost (like it is done in Chrome DevTools with port forwarding) because I use server-side software which strictly relies only on localhost (it is not mine, I wouldn't do that if I could).

So, is there a way to accomplish this on the Android default native browser? Using weinre and/or Chrome DevTools?

Thanks for the attention!

P.S.: I know Android browser is not native anymore from Android 4.4, anyway, I would need that for compatibility, if of course, it is possible (it should be, I guess).

答:
You can use the Chrome developer tools to debug a mobile website running in the stock Android browser, in a similar way that you can do debugging when the website's running on Chrome for Android:

If you haven't already done this, follow all steps in the accepted answer here, to enable debugging using the Chrome dev tools (on your desktop computer):

Chrome DevTools Devices does not detect device when plugged in

Now, with your device connected to your computer, open your web page in the stock Android browser. Go to the Chrome dev tools, where you should see your device connected, and you should see something like this (with the usual 'inspect' button off to the right hand side). Click the 'inspect' button and you're in - you can debug the stock Android browser using the Chrome dev tools!


问:
WordPress User Table Migration Corrupt?
I am having trouble with a WordPress users migration. When I migrate the users table to another database, it seems to go smoothly. However, when I login to WordPress and navigate to the users area, it lists all of the users but still only acknowledges that there is only 1 users.

So it shows the list of 10,000 users, but only says "1 user".

Do I need to migrate the user-meta table?

答: you have to migrate the usermeta table also because user roles are defined there.</p>

Title: WordPress User Table Migration Corrupt?


问:
Python/mySQL on an Embedded ARM9 Device?
I have an application where a small embedded ARM9 device (running Linux) must gather information from sensors and then connect to a remote mySQL database and INSERT the data. I have Python 2.5 running on the ARM9 device fine. I have developed a prototype application in Python 2.5 running on x86 Windows and it connects with mySQL and INSERTS just fine. My confusion in this issue come from working with "mySQL Connect/C" which would have to be cross compiled for the ARM processor before being used.

What is the best way to port or move this DB app onto the ARM device?

Are there underlying x86 binaries in supporting libraries that must be cross compiled?

Or, is MySQLdb simply portable across platforms?

答: I suggest using SQLite. I have an application running Python+SQLite for telemetry purposes and it works like a charm. It's much easier than MySQL.</p>

OwnerDisplayName: Doug


问:
PHP Regex to allow only one decimal and one percentage sign
Hello I'm trying to create a regex to validate a percentage value but I only want to allow one decimal after at least one digit and and one percentage sign as the last character. For example the following values below should be valid:

```<code>8%

10%

12.60%

7.750%
</code>```

So far this is my regex code for my php function.

```<code>if(!preg_match('/[^0-9.%]/', $string)){
    return true;
} else {
    return false;
}
</code>```

答:
Pattern: /^\d+(?:\.\d+)?%$/

Demo: https://regex101.com/r/7mqiIJ/1

Explanation:

```<code>^            #start of the string
\d+          #match one or more digits
(?:          #start a non-capturing group
    \.\d+    #match one decimal point (dot) followed by one or more digits
)?           #make the group optional
%            #match one percent sign
$            #end of the string
</code>```

You may want to fully consider any fringe cases that you want to validate as false.

Fringe Cases:

01% (leading omittable zero)

.10% (trailing omittable zero)

These cases may not be grounds for deeming a value as invalid, but probably could/should be trimmed of omittable zeros.  (This can be done as part of the preg_match call if you want to be clever about it.)

To omit leading zeros, you can use: /^0*\K\d+(?:\.\d+)?%$/ to match all leading 0's and then restart the fullstring match with \K.  The trailing zeros (just before %) will require a different approach -- but perhaps they don't bother you.

Here is how you can execute it: (Demo)

```<code>$string='10.99%';
if(preg_match('/^\d+(?:\.\d+)?%$/',$string)){
    echo 'valid';
} else {
    echo 'invalid';
}

echo "\n\n";

$string='10.%';
if(preg_match('/^\d+(?:\.\d+)?%$/',$string)){
    echo 'valid';
} else {
    echo 'invalid';
}
</code>```

Output:

```<code>valid

invalid
</code>```

Body:
Hello I'm trying to create a regex to validate a percentage value but I only want to allow one decimal after at least one digit and and one percentage sign as the last character. For example the following values below should be valid:

8%

10%

12.60%

7.750%

So far this is my regex code for my php function.

if(!preg_match('/[^0-9.%]/', $string)){
    return true;
} else {
    return false;
}

Body:
Pattern: /^\d+(?:\.\d+)?%$/

Demo: https://regex101.com/r/7mqiIJ/1

Explanation:

^            #start of the string
\d+          #match one or more digits
(?:          #start a non-capturing group
    \.\d+    #match one decimal point (dot) followed by one or more digits
)?           #make the group optional
%            #match one percent sign
$            #end of the string

You may want to fully consider any fringe cases that you want to validate as false.

Fringe Cases:

01% (leading omittable zero)

.10% (trailing omittable zero)

These cases may not be grounds for deeming a value as invalid, but probably could/should be trimmed of omittable zeros.  (This can be done as part of the preg_match call if you want to be clever about it.)

To omit leading zeros, you can use: /^0*\K\d+(?:\.\d+)?%$/ to match all leading 0's and then restart the fullstring match with \K.  The trailing zeros (just before %) will require a different approach -- but perhaps they don't bother you.

Here is how you can execute it: (Demo)

$string='10.99%';
if(preg_match('/^\d+(?:\.\d+)?%$/',$string)){
    echo 'valid';
} else {
    echo 'invalid';
}

echo "\n\n";

$string='10.%';
if(preg_match('/^\d+(?:\.\d+)?%$/',$string)){
    echo 'valid';
} else {
    echo 'invalid';
}

Output:

valid

invalid


问:
Is there a good way to identify a word, even if it's misspelled in javascript?
I have a bunch of words (mostly locations, like Stockholm and London) and a bunch of strings. like "I want to go from stockholm to london". I want to find out what words are in what strings.

I currently use .indexOf to perform this task.

Is there a library, method, function etc, in javascript that identifies misspelled versions of words?

答:
In the past, I have used MissPlete library, which uses Jaro–Winkler distance algoritm by default.

It has no dependencies (not even jQuery), which I highly value.


问:
Get image from script attached to gameobject using getComponent in Unity
I'm trying to introduce a radar scan feature so that when a button is clicked the image on the radar is updated based on the tag of the object with a new image. I'm getting a "NullReferenceException: Object reference not set to an instance of an object" on Enemy.GetComponent line in my Radar Scan Script.
but I have a image set?
dot 1 which I will now show below

Am I accessing it wrong? Here's my RadarScan script

```<code>public class RadarScan : MonoBehaviour
{
GameObject Enemy;
Image RadarImageToChange;

void Start()
{
    Enemy = GameObject.Find("Enemy");
}

public void ChangeImage(Image UpdateImage)
{
    if (Enemy.tag == "Enemy")
    {
        RadarImageToChange = Enemy.GetComponent<MakeRadarObject>().image;
        UpdateImage = RadarImageToChange;
    }

}
}
</code>```

Here's my radar Script

```<code>public class RadarObject
{
    public Image icon { get; set; }
    public GameObject owner { get; set; }
}

public class Radar : MonoBehaviour {

public Transform playerPos; //position of player
float mapScale = 0.1f; //scale radar size

public static List<RadarObject> radObjects = new List<RadarObject>();

//Registers Object to the radar
public static void RegisterRadarObject(GameObject o, Image i)
{
    Image image = Instantiate(i);
    radObjects.Add(new RadarObject() { owner = o, icon = image }); //adds to List
}

//It loops through the list looking for the owner existing in the list, when it finds the owner is detroys the icon
public static void RemoveRadarObject(GameObject o)
{
    //New list for destroyed objects
    List<RadarObject> newList = new List<RadarObject>();
    for (int i = 0; i < radObjects.Count; i++)
    {
        if (radObjects[i].owner == o)
        {
            Destroy(radObjects[i].icon);
            continue;
        }
         else
            newList.Add(radObjects[i]);
        }
    radObjects.RemoveRange(0, radObjects.Count);
    radObjects.AddRange(newList);
}

void DrawRadarDots()
{
    //loops through the list and for each Object it gets the owners transform position and determins the difference between it's
    //position and the players position, does calculations on the angle and distance and position on a circle using polar equations.
    foreach (RadarObject ro in radObjects)
    {
        Vector3 radarPos = (ro.owner.transform.position - playerPos.position);
        float distToObject = Vector3.Distance(playerPos.position, ro.owner.transform.position) * mapScale;
        float deltay = Mathf.Atan2(radarPos.x, radarPos.z) * Mathf.Rad2Deg - 270 - playerPos.eulerAngles.y;
        radarPos.x = distToObject * Mathf.Cos(deltay * Mathf.Deg2Rad) * -1;
        radarPos.z = distToObject * Mathf.Sin(deltay * Mathf.Deg2Rad);

        //grabs icon of players objects and make it a child of panel and set it's postion based on radarPos.x and radarPos.z
        ro.icon.transform.SetParent(this.transform);
        ro.icon.transform.position = new Vector3(radarPos.x, radarPos.z, 0) + this.transform.position;
    }
}

    //Update is called once per frame
    void Update ()
    {
        DrawRadarDots();
    }
 }
</code>```

Here is my stack trace

答:
but I have a image set

Not really. You have a misconception about variable membership and/or how GetComponent() works.

The GetComponent() method (and it's variants) is used to get a Component attached to a GameObject directly. It won't recognize/find members (including variables) of the components; only the components themselves;
 even if those members are of Type of Component.

This means that the null you're getting at Enemy.GetComponent<Image>(); is not being thrown on the Image reference. As you've said, that one is set.

The problem arises from GetComponent itself:

The image component is not attached to the GameObject; instead, a reference of it is set as a member in the MakeRadarObject component.

As such, GetComponent doesn't find any Image component attached to the GameObject, so it returns null; as it should.

Body:
I'm trying to introduce a radar scan feature so that when a button is clicked the image on the radar is updated based on the tag of the object with a new image. I'm getting a "NullReferenceException: Object reference not set to an instance of an object" on Enemy.GetComponent line in my Radar Scan Script.
but I have a image set?
dot 1 which I will now show below

Am I accessing it wrong? Here's my RadarScan script

public class RadarScan : MonoBehaviour
{
GameObject Enemy;
Image RadarImageToChange;

void Start()
{
    Enemy = GameObject.Find("Enemy");
}

public void ChangeImage(Image UpdateImage)
{
    if (Enemy.tag == "Enemy")
    {
        RadarImageToChange = Enemy.GetComponent<MakeRadarObject>().image;
        UpdateImage = RadarImageToChange;
    }

}
}

Here's my radar Script

public class RadarObject
{
    public Image icon { get; set; }
    public GameObject owner { get; set; }
}

public class Radar : MonoBehaviour {

public Transform playerPos; //position of player
float mapScale = 0.1f; //scale radar size

public static List<RadarObject> radObjects = new List<RadarObject>();

//Registers Object to the radar
public static void RegisterRadarObject(GameObject o, Image i)
{
    Image image = Instantiate(i);
    radObjects.Add(new RadarObject() { owner = o, icon = image }); //adds to List
}

//It loops through the list looking for the owner existing in the list, when it finds the owner is detroys the icon
public static void RemoveRadarObject(GameObject o)
{
    //New list for destroyed objects
    List<RadarObject> newList = new List<RadarObject>();
    for (int i = 0; i < radObjects.Count; i++)
    {
        if (radObjects[i].owner == o)
        {
            Destroy(radObjects[i].icon);
            continue;
        }
         else
            newList.Add(radObjects[i]);
        }
    radObjects.RemoveRange(0, radObjects.Count);
    radObjects.AddRange(newList);
}

void DrawRadarDots()
{
    //loops through the list and for each Object it gets the owners transform position and determins the difference between it's
    //position and the players position, does calculations on the angle and distance and position on a circle using polar equations.
    foreach (RadarObject ro in radObjects)
    {
        Vector3 radarPos = (ro.owner.transform.position - playerPos.position);
        float distToObject = Vector3.Distance(playerPos.position, ro.owner.transform.position) * mapScale;
        float deltay = Mathf.Atan2(radarPos.x, radarPos.z) * Mathf.Rad2Deg - 270 - playerPos.eulerAngles.y;
        radarPos.x = distToObject * Mathf.Cos(deltay * Mathf.Deg2Rad) * -1;
        radarPos.z = distToObject * Mathf.Sin(deltay * Mathf.Deg2Rad);

        //grabs icon of players objects and make it a child of panel and set it's postion based on radarPos.x and radarPos.z
        ro.icon.transform.SetParent(this.transform);
        ro.icon.transform.position = new Vector3(radarPos.x, radarPos.z, 0) + this.transform.position;
    }
}

    //Update is called once per frame
    void Update ()
    {
        DrawRadarDots();
    }
 }

Here is my stack trace


问:
How to prevent a UIViewController from being popped out?
I have a childViewController which is pushed from parentViewController. In childViewController I want to block pop action in a particular condition.

I wrote this code in viewWillDisappear: But I guess need to do this somewhere else.

```<code>override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    if changesMade {
        let alertController = UIAlertController(title: "Alert", message: "Changes made are not saved. Do you wish to save changes made?", preferredStyle: .alert)

        let cancelOption = UIAlertAction(title: "Cancel", style: .cancel)
        let saveOption = UIAlertAction(title: "Save", style: .default, handler: { (action) in
            self.saveSession()
        })

        alertController.addAction(saveOption)
        alertController.addAction(cancelOption)
        present(alertController, animated: true)
    }
}
</code>```

答:
block pop action till your changes are not saved like this

```<code>if changesMade {
        let alertController = UIAlertController(title: "Alert", message: "Changes made are not saved. Do you wish to save changes made?", preferredStyle: .alert)

        let cancelOption = UIAlertAction(title: "Cancel", style: .cancel)
        let saveOption = UIAlertAction(title: "Save", style: .default, handler: { (action) in
            self.saveSession()
            self.navigationController?.popViewController(animated: true)
        })

        alertController.addAction(saveOption)
        alertController.addAction(cancelOption)
        present(alertController, animated: true)
    }
</code>```

Update - Add this below custom button and its action in child View controller which is being pushed from parent View Controller
so, without satisfying your condition user can not move from child to parent again

For customising action of navigation backButton you need to manually add a back Button using below line , you can Customise barButton being added here in DidLoad

```<code> self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.backToInitial(sender:)))
</code>```

It will perform required Action

```<code> @objc func backToInitial(sender: AnyObject) {
        if changesMade {
            let alertController = UIAlertController(title: "Alert", message: "Changes made are not saved. Do you wish to save changes made?", preferredStyle: .alert)

            let cancelOption = UIAlertAction(title: "Cancel", style: .cancel)
            let saveOption = UIAlertAction(title: "Save", style: .default, handler: { (action) in
                self.saveSession()
                self.navigationController?.popViewController(animated: true)
            })

            alertController.addAction(saveOption)
            alertController.addAction(cancelOption)
            present(alertController, animated: true)
        }
    }
</code>```

and I do not think you can stop default back button action task of navigation Controller as it is designed the way to perform it

But yes you can manage it in ViewWillDisappear as :

```<code>override func viewWillDisappear(_ animated: Bool) {
        if self.isMovingFromParentViewController || self.isBeingDismissed {
            self.navigationController?.popViewController(animated: false) //here task but will not result as Expected output
        }
    }
</code>```

-----------------Re-Update ---------------

in swift I used a objective-C class to get output as expected now, childViewController pop action is being controller from a alert using default back button that we get from navigation controller

You can customise you pop action to perform or not until your condition is not satisfied
Github Link - https://github.com/RockinGarg/NavigationBackButton.git

Body:
I have a childViewController which is pushed from parentViewController. In childViewController I want to block pop action in a particular condition.

I wrote this code in viewWillDisappear: But I guess need to do this somewhere else.

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    if changesMade {
        let alertController = UIAlertController(title: "Alert", message: "Changes made are not saved. Do you wish to save changes made?", preferredStyle: .alert)

        let cancelOption = UIAlertAction(title: "Cancel", style: .cancel)
        let saveOption = UIAlertAction(title: "Save", style: .default, handler: { (action) in
            self.saveSession()
        })

        alertController.addAction(saveOption)
        alertController.addAction(cancelOption)
        present(alertController, animated: true)
    }
}

Body:
block pop action till your changes are not saved like this

if changesMade {
        let alertController = UIAlertController(title: "Alert", message: "Changes made are not saved. Do you wish to save changes made?", preferredStyle: .alert)

        let cancelOption = UIAlertAction(title: "Cancel", style: .cancel)
        let saveOption = UIAlertAction(title: "Save", style: .default, handler: { (action) in
            self.saveSession()
            self.navigationController?.popViewController(animated: true)
        })

        alertController.addAction(saveOption)
        alertController.addAction(cancelOption)
        present(alertController, animated: true)
    }

Update - Add this below custom button and its action in child View controller which is being pushed from parent View Controller
so, without satisfying your condition user can not move from child to parent again

For customising action of navigation backButton you need to manually add a back Button using below line , you can Customise barButton being added here in DidLoad

 self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.backToInitial(sender:)))

It will perform required Action

 @objc func backToInitial(sender: AnyObject) {
        if changesMade {
            let alertController = UIAlertController(title: "Alert", message: "Changes made are not saved. Do you wish to save changes made?", preferredStyle: .alert)

            let cancelOption = UIAlertAction(title: "Cancel", style: .cancel)
            let saveOption = UIAlertAction(title: "Save", style: .default, handler: { (action) in
                self.saveSession()
                self.navigationController?.popViewController(animated: true)
            })

            alertController.addAction(saveOption)
            alertController.addAction(cancelOption)
            present(alertController, animated: true)
        }
    }

and I do not think you can stop default back button action task of navigation Controller as it is designed the way to perform it

But yes you can manage it in ViewWillDisappear as :

override func viewWillDisappear(_ animated: Bool) {
        if self.isMovingFromParentViewController || self.isBeingDismissed {
            self.navigationController?.popViewController(animated: false) //here task but will not result as Expected output
        }
    }

-----------------Re-Update ---------------

in swift I used a objective-C class to get output as expected now, childViewController pop action is being controller from a alert using default back button that we get from navigation controller

You can customise you pop action to perform or not until your condition is not satisfied
Github Link - https://github.com/RockinGarg/NavigationBackButton.git


问:
iPhone/iPad HTTP streaming library or server
Is there any available open-source (preferred) or commercial library for on-fly segmenting and streaming of video to iPhone / iPad?

Also, is there any open-source/commercial server (alternative to Wowza) which supports this?

答:
Your first preoccupation should be to try to peek a good segmenter (video speaking): Apple's one is fine.

Then, if you wan't in-memory segmenting, mount the input source folder to a RAMdisk...


问:
How do I split a Text with 3 delimiters in SQL (Oracle) into multiple rows and columns?
I need to split a text like "Aa:One|Bb:Two,Three,Four|Cc:Five,Six" into rows and columns for the result to look like -

Col1    Col2

AA       One

Bb       Two

Bb       Three

Bb       Four

Cc       Five

Cc       Six

I have tried using

```<code>SELECT REGEXP_SUBSTR (str, '[^:]+', 1, 1)    AS COL1
      ,REGEXP_SUBSTR (str, '[^:]+', 1, 2)    AS COL2
FROM (SELECT REGEXP_SUBSTR('Aa:One|Bb:Two,Three,Four|Cc:Five,Six', '[^|]+', 1, LEVEL) AS str
      FROM DUAL
      CONNECT BY INSTR('Aa:One|Bb:Two,Three,Four|Cc:Five,Six', '|', 1, LEVEL - 1) > 0
      )
</code>```

But I could only create

Col1    Col2

Aa   One

Bb   Two,Three,Four

Cc Five,Six

I am not sure how to split it further with  comma(,) in Col2 into rows against the Col1 value's first occurrence

Any help in this regard would be greatly appreciated.

Thanks in advance! :-)

答:
I just did this for SQL Server. You can get the same result from ORACLE using the alternates for the Functions in ORACLE.

```<code>DECLARE @Id VARCHAR(100)='Aa:One|Bb:Two,Three,Four|Cc:Five,Six'

SELECT LEFT(items, CHARINDEX(':',items)-1)Col1
    ,RIGHT(items, CHARINDEX(':',REVERSE(items))-1)Col2
INTO #Temp
FROM dbo.Split(@Id,'|')

SELECT p.Col1, colortable.items as Col2
FROM #Temp p
    cross apply split(p.Col2, ',') as colortable

DROP TABLE #Temp
</code>```

And my Result is:

```<code>Col1    Col2
Aa      One
Bb      Two
Bb      Three
Bb      Four
Cc      Five
Cc      Six
</code>```

Body:
I need to split a text like "Aa:One|Bb:Two,Three,Four|Cc:Five,Six" into rows and columns for the result to look like -

Col1    Col2

AA       One

Bb       Two

Bb       Three

Bb       Four

Cc       Five

Cc       Six

I have tried using

SELECT REGEXP_SUBSTR (str, '[^:]+', 1, 1)    AS COL1
      ,REGEXP_SUBSTR (str, '[^:]+', 1, 2)    AS COL2
FROM (SELECT REGEXP_SUBSTR('Aa:One|Bb:Two,Three,Four|Cc:Five,Six', '[^|]+', 1, LEVEL) AS str
      FROM DUAL
      CONNECT BY INSTR('Aa:One|Bb:Two,Three,Four|Cc:Five,Six', '|', 1, LEVEL - 1) > 0
      )

But I could only create

Col1    Col2

Aa   One

Bb   Two,Three,Four

Cc Five,Six

I am not sure how to split it further with  comma(,) in Col2 into rows against the Col1 value's first occurrence

Any help in this regard would be greatly appreciated.

Thanks in advance! :-)

Body:
I just did this for SQL Server. You can get the same result from ORACLE using the alternates for the Functions in ORACLE.

DECLARE @Id VARCHAR(100)='Aa:One|Bb:Two,Three,Four|Cc:Five,Six'

SELECT LEFT(items, CHARINDEX(':',items)-1)Col1
    ,RIGHT(items, CHARINDEX(':',REVERSE(items))-1)Col2
INTO #Temp
FROM dbo.Split(@Id,'|')

SELECT p.Col1, colortable.items as Col2
FROM #Temp p
    cross apply split(p.Col2, ',') as colortable

DROP TABLE #Temp

And my Result is:

Col1    Col2
Aa      One
Bb      Two
Bb      Three
Bb      Four
Cc      Five
Cc      Six


问:
Sharing to facebook unable to display the exact image
I am doing a facebook sharing using an App ID. I have this included in my page

```<code><script>
(function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = 'https://connect.facebook.net/en_US/sdk.js';
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
</code>```

Source : Detect Facebook share success?

My coding looked like this http://jsfiddle.net/benjasHu/3dhq9k21/

I manage to share the content to facebook with the correct image when there is only one image. So when I tried to share a page content which having more than 1 image, it seems like the facebook get confuse and the image container is just blank with the title displayed wrong.

The result is something like the picture below

答:
Finally found a very useful article explaining about Facebook open graph meta customization. http://drib.tech/programming/dynamically-change-facebook-open-graph-meta-data-javascript

From my coding, Instead of using this :

```<code>var options = ({
    method : 'share',
    href   : 'url goes here'
}),
</code>```

I replaced to :

```<code>var options = ({
    method: 'share_open_graph',
    action_type: 'og.shares',
    action_properties: JSON.stringify({
        object: {
            'og:url': 'url-to-share',
            'og:title': 'title-of-page-to-share',
            'og:description': 'description-of-page-to-share',
            'og:image': 'image-displayed-when-sharing'
        }
    })
}),
</code>```

Body:
I am doing a facebook sharing using an App ID. I have this included in my page

Source : Detect Facebook share success?

My coding looked like this http://jsfiddle.net/benjasHu/3dhq9k21/

I manage to share the content to facebook with the correct image when there is only one image. So when I tried to share a page content which having more than 1 image, it seems like the facebook get confuse and the image container is just blank with the title displayed wrong.

The result is something like the picture below

Body:
Finally found a very useful article explaining about Facebook open graph meta customization. http://drib.tech/programming/dynamically-change-facebook-open-graph-meta-data-javascript

From my coding, Instead of using this :

var options = ({
    method : 'share',
    href   : 'url goes here'
}),

I replaced to :

var options = ({
    method: 'share_open_graph',
    action_type: 'og.shares',
    action_properties: JSON.stringify({
        object: {
            'og:url': 'url-to-share',
            'og:title': 'title-of-page-to-share',
            'og:description': 'description-of-page-to-share',
            'og:image': 'image-displayed-when-sharing'
        }
    })
}),


问:
Access - Field size for numerical field?
With text boxes, you can set field size on how many characters can be entered.
Is it possible to do this to a numerical field?</p>

答:
No.
What you can do is to apply a validation rule to your number field in the table.
Like:

```<code>Len([enter your field name here])<=4
</code>```

Plus a validation message:

```<code>Number should be 4 digits at most
</code>```

There's other option too like applying a Before Update event in your form that you use to maintain the data.

And another possible option might be to apply a data macro.
Can't help you on that one as my Access version is pretty old.

Body:
No.
What you can do is to apply a validation rule to your number field in the table.
Like:

Len([enter your field name here])<=4

Plus a validation message:

Number should be 4 digits at most

There's other option too like applying a Before Update event in your form that you use to maintain the data.

And another possible option might be to apply a data macro.
Can't help you on that one as my Access version is pretty old.


问:
how to initializing a hash table in C
I have a program in C that creates a hash table.
memset is Okay but, i want to initialize with for loop.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define HSZ 127
#define HASHING(x) ((x)%HSZ)

struct node_t{
    int val;
    struct node_t *next;
};

struct node_t *hash_table[HSZ];

void init(void){
    int i;
    //memset(hash_table,0,sizeof(hash_table));
    for(i=0; i<HSZ; i++){
        hash_table[i]->val = 0;
        hash_table[i]->next = NULL;
    }
}

void insert_hash(int value){
    int key = HASHING(value);
    struct node_t *newNode = (struct node_t*)malloc(sizeof(struct node_t));

    newNode->val = value;
    newNode->next = NULL;

    if(hash_table[key] == NULL){
        hash_table[key] = newNode;
    } else {
        newNode->next = hash_table[key];
        hash_table[key] = newNode;
    }
}

int delete_hash(int value){
    int key = HASHING(value);
    if (hash_table[key] == NULL)
        return 0;

    struct node_t *delNode = NULL;

    if (hash_table[key]->val == value){
        delNode = hash_table[key];
        hash_table[key] = hash_table[key]->next;
    } else {
        struct node_t *node = &hash_table[key];
        struct node_t *next = hash_table[key]->next;
        while (next){
            if (next->val == value){
                node->next = next->next;
                delNode = next;
                break;
            }
            node = next;
            next = node->next;
        }
    }
    return 1;
    free(delNode);
}
void PrintAllHashData()
{
    printf("###Print All Hash Data###\n");
    for (int i = 0; i < HSZ; i++){
        if (hash_table[i] != NULL){
            printf("idx : %d ", i);
            struct node_t *node = hash_table[i];
            while (node->next){
                printf("%d ", node->val);
                node = node->next;
            }
            printf("%d\n", node->val);
        }
    }
}

int main(void){
    init();
    insert_hash(1);
    insert_hash(3);
    insert_hash(128);
    PrintAllHashData();
}
</code>```

look at this code.

```<code>for(i=0; i<HSZ; i++){
    hash_table[i]->val = 0;
    hash_table[i]->next = NULL;
}
</code>```

The IDE I am using does not throw up a compilation error when I compile the code, but during the execution the code faults and is terminated/haulted. I tried debugging the code, it faults at this line and is stopped, I think BAD ACCESS points to Segmentation Error.

then, I changed this line to

```<code>for(i=0; i<HSZ; i++){
    hash_table[i].val = 0;
    hash_table[i]->next = NULL;
}
</code>```

but, then I got the compilation error stating 'structure type require instead of 'struct node_t *'

I think that I don't understand clearly about struct in C.
How to fix this problem?

答:
struct node_t *hash_table[HSZ];
gives you an array of pointers that are unset (i.e. not pointing to anything)

```<code>void init(void) {
    int i;
    // memset(hash_table,0,sizeof(hash_table));
    for (i = 0; i < HSZ; i++) {
        hash_table[i]->val = 0;
        hash_table[i]->next = NULL;
</code>```

tries writing to your invalid pointers which gives undefined behavior.

Either make the array an array of structs (instead of pointers):

```<code>struct node_t hash_table[HSZ];
...
/* note use of . instead of -> since we have structs not pointers */
hash_table[i].val = 0;
</code>```

or allocate the necessary structs so the array points to something:

```<code>for (i = 0; i < HSZ; i++) {
    hash_table[i] = malloc(sizeof(struct node_t));
    hash_table[i]->val = 0;
    hash_table[i]->next = NULL;
}
</code>```

Title: how to initializing a hash table in C

Body:
I have a program in C that creates a hash table.
memset is Okay but, i want to initialize with for loop.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define HSZ 127
#define HASHING(x) ((x)%HSZ)

struct node_t{
    int val;
    struct node_t *next;
};

struct node_t *hash_table[HSZ];

void init(void){
    int i;
    //memset(hash_table,0,sizeof(hash_table));
    for(i=0; i<HSZ; i++){
        hash_table[i]->val = 0;
        hash_table[i]->next = NULL;
    }
}

void insert_hash(int value){
    int key = HASHING(value);
    struct node_t *newNode = (struct node_t*)malloc(sizeof(struct node_t));

    newNode->val = value;
    newNode->next = NULL;

    if(hash_table[key] == NULL){
        hash_table[key] = newNode;
    } else {
        newNode->next = hash_table[key];
        hash_table[key] = newNode;
    }
}

int delete_hash(int value){
    int key = HASHING(value);
    if (hash_table[key] == NULL)
        return 0;

    struct node_t *delNode = NULL;

    if (hash_table[key]->val == value){
        delNode = hash_table[key];
        hash_table[key] = hash_table[key]->next;
    } else {
        struct node_t *node = &hash_table[key];
        struct node_t *next = hash_table[key]->next;
        while (next){
            if (next->val == value){
                node->next = next->next;
                delNode = next;
                break;
            }
            node = next;
            next = node->next;
        }
    }
    return 1;
    free(delNode);
}
void PrintAllHashData()
{
    printf("###Print All Hash Data###\n");
    for (int i = 0; i < HSZ; i++){
        if (hash_table[i] != NULL){
            printf("idx : %d ", i);
            struct node_t *node = hash_table[i];
            while (node->next){
                printf("%d ", node->val);
                node = node->next;
            }
            printf("%d\n", node->val);
        }
    }
}

int main(void){
    init();
    insert_hash(1);
    insert_hash(3);
    insert_hash(128);
    PrintAllHashData();
}

look at this code.

for(i=0; i<HSZ; i++){
    hash_table[i]->val = 0;
    hash_table[i]->next = NULL;
}

The IDE I am using does not throw up a compilation error when I compile the code, but during the execution the code faults and is terminated/haulted. I tried debugging the code, it faults at this line and is stopped, I think BAD ACCESS points to Segmentation Error.

then, I changed this line to

for(i=0; i<HSZ; i++){
    hash_table[i].val = 0;
    hash_table[i]->next = NULL;
}

but, then I got the compilation error stating 'structure type require instead of 'struct node_t *'

I think that I don't understand clearly about struct in C.
How to fix this problem?

Body:
struct node_t *hash_table[HSZ];
gives you an array of pointers that are unset (i.e. not pointing to anything)

void init(void) {
    int i;
    // memset(hash_table,0,sizeof(hash_table));
    for (i = 0; i < HSZ; i++) {
        hash_table[i]->val = 0;
        hash_table[i]->next = NULL;

tries writing to your invalid pointers which gives undefined behavior.

Either make the array an array of structs (instead of pointers):

struct node_t hash_table[HSZ];
...
/* note use of . instead of -> since we have structs not pointers */
hash_table[i].val = 0;

or allocate the necessary structs so the array points to something:

for (i = 0; i < HSZ; i++) {
    hash_table[i] = malloc(sizeof(struct node_t));
    hash_table[i]->val = 0;
    hash_table[i]->next = NULL;
}

ContentLicense: CC BY-SA 4.0


问:
.Net WebAPI Post method is not working from Angular2 service
I am newbie in Angular 2. I am sending form data from angular 2 to webapi but it is not working.
WebAPI:

```<code>public class FetchDataController : ApiController
    {

        [HttpGet]
        public IList<Student> ListOfStudents()
        {
            AppRepository objapp = new AppRepository();
            IList<Student> objData = null;
            objData = objapp.getStudent();
            return objData;
        }

        [HttpPost]
        [Route("PostStudent")]
        public JsonResult<Boolean> PostStudent(Student value)
        {
            // Append text to an existing file named "WriteLines.txt".
            string data = "ID: " + value.Id + ", FirstName: " + value.FirstName + ",LastName: " + value.LastName + ",Salary: " + value.salary;
            using (StreamWriter outputFile = new StreamWriter(HttpContext.Current.Server.MapPath("~")+ "/TestVD/WriteLines.txt", true))
            {
                outputFile.WriteLine(data);
            }
            return Json(true);
        }

    }
</code>```

My WebAPIConfig.js is as follows. I have added CORS handling in here as well as Webconfig file:

```<code>var cors = new EnableCorsAttribute("http://localhost", "*", "*");
              config.EnableCors(cors);

            // Web API configuration and services
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
            // Web API routes
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
            name: "ListOfStudents",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { controller = "FetchData", action = "ListOfStudents", id = RouteParameter.Optional }
            );

            config.Routes.MapHttpRoute(
               name: "PostStudent",
               routeTemplate: "api/{controller}/{id}",
               defaults: new { controller = "FetchData", action = "PostStudent", id = RouteParameter.Optional }
            );
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
</code>```

Now, From Angular 2, I am able to show data using List of student webAPI method but while posting I am getting "405 (Method Not Allowed)" from my WEBAPI url.
I am gettling below response from WEBAPI post method.

```<code>ok
:
false
status
:
405
statusText
:
"Method Not Allowed"
type
:
2
url
:
"http://localhost/TestWebService/api/FetchData/"
_body
:
"{"Message":"The requested resource does not support http method 'POST'."}"
</code>```

My Angular 2 service code is as follows

```<code>@Injectable()
export class RssService {
private studentUrl = "http://localhost/TestWebService/api/FetchData/";
    constructor(private http: Http) {   }
    getStudentList() {
        return this.http.get(this.studentUrl)
            .map(res => <Student[]>res.json())
            .catch(this.handleError);
    }
    private handleError(error: Response) {
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }
    postStudent(model: any): Observable<any> {
        let body = JSON.stringify(model);
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        console.log('add Student start : ' + body);
        return this.http.post(this.studentUrl , body, options)
            .map((response: Response) => <any>response.json())
            .catch(this.handleError);
    }
}
</code>```

Could you please help me...

答:
You have a routing attribute [Route("PostStudent")] on your PostStudent method.

Because of it, URL for this action is not http://localhost/TestWebService/api/FetchData/, but http://localhost/TestWebService/PostStudent.

To use URL http://localhost/TestWebService/api/FetchData/ just remove this Route attribute.

If you still want to use specific Route for PostStudent action and access it via http://localhost/TestWebService/api/FetchData/PostStudent, add also RoutePrefix attribute on your controller:

```<code>[RoutePrefix("api/FetchData")]
public class FetchDataController : ApiController
</code>```

Check this article for mode details: Attribute Routing in ASP.NET Web API 2

Body:
I am newbie in Angular 2. I am sending form data from angular 2 to webapi but it is not working.
WebAPI:

public class FetchDataController : ApiController
    {

        [HttpGet]
        public IList<Student> ListOfStudents()
        {
            AppRepository objapp = new AppRepository();
            IList<Student> objData = null;
            objData = objapp.getStudent();
            return objData;
        }

        [HttpPost]
        [Route("PostStudent")]
        public JsonResult<Boolean> PostStudent(Student value)
        {
            // Append text to an existing file named "WriteLines.txt".
            string data = "ID: " + value.Id + ", FirstName: " + value.FirstName + ",LastName: " + value.LastName + ",Salary: " + value.salary;
            using (StreamWriter outputFile = new StreamWriter(HttpContext.Current.Server.MapPath("~")+ "/TestVD/WriteLines.txt", true))
            {
                outputFile.WriteLine(data);
            }
            return Json(true);
        }

    }

My WebAPIConfig.js is as follows. I have added CORS handling in here as well as Webconfig file:

var cors = new EnableCorsAttribute("http://localhost", "*", "*");
              config.EnableCors(cors);

            // Web API configuration and services
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
            // Web API routes
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
            name: "ListOfStudents",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { controller = "FetchData", action = "ListOfStudents", id = RouteParameter.Optional }
            );

            config.Routes.MapHttpRoute(
               name: "PostStudent",
               routeTemplate: "api/{controller}/{id}",
               defaults: new { controller = "FetchData", action = "PostStudent", id = RouteParameter.Optional }
            );
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

Now, From Angular 2, I am able to show data using List of student webAPI method but while posting I am getting "405 (Method Not Allowed)" from my WEBAPI url.
I am gettling below response from WEBAPI post method.

ok
:
false
status
:
405
statusText
:
"Method Not Allowed"
type
:
2
url
:
"http://localhost/TestWebService/api/FetchData/"
_body
:
"{"Message":"The requested resource does not support http method 'POST'."}"

My Angular 2 service code is as follows

@Injectable()
export class RssService {
private studentUrl = "http://localhost/TestWebService/api/FetchData/";
    constructor(private http: Http) {   }
    getStudentList() {
        return this.http.get(this.studentUrl)
            .map(res => <Student[]>res.json())
            .catch(this.handleError);
    }
    private handleError(error: Response) {
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }
    postStudent(model: any): Observable<any> {
        let body = JSON.stringify(model);
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        console.log('add Student start : ' + body);
        return this.http.post(this.studentUrl , body, options)
            .map((response: Response) => <any>response.json())
            .catch(this.handleError);
    }
}

Could you please help me...

Body:
You have a routing attribute [Route("PostStudent")] on your PostStudent method.

Because of it, URL for this action is not http://localhost/TestWebService/api/FetchData/, but http://localhost/TestWebService/PostStudent.

To use URL http://localhost/TestWebService/api/FetchData/ just remove this Route attribute.

If you still want to use specific Route for PostStudent action and access it via http://localhost/TestWebService/api/FetchData/PostStudent, add also RoutePrefix attribute on your controller:

[RoutePrefix("api/FetchData")]
public class FetchDataController : ApiController

Check this article for mode details: Attribute Routing in ASP.NET Web API 2


问:
Can't remove encoding returned in $_COOKIE in PHP (on MAMP Server)
I finally got cookies to work only for my output to display like this:

You last requested an internship opportunity on
  Wednesday%2C+November+15%2C+2017%2C+3%3A+33+AM.

I have tried using urldecode(),rawurldecode(), setrawcookie(), implode(), and explode(). None of these have had any affect on the output, and I haven't seen other suggestions in similar questions. If anyone has an idea of what might work, I would appreciate the information.

Below I have included some of the code (there's two files involved so I won't post those unless necessary).

Cookie info pulled from top of page

```<code>if(isset($_COOKIE['LastRequestDate']))
    $LastRequestDate = $_COOKIE['LastRequestDate'];
else
    $LastRequestDate = "";
</code>```

Cookie variable displayed

```<code>echo "<p>You last requested an internship opportunity on ".$LastRequestDate."</p>";
</code>```

Here's the code that set's the cookie from another page. I have tried removing the urlencode() but nothing changes.

```<code>setcookie("LastRequestDate", urlencode($DisplayDate), time()+60*60*24*7, "/");
</code>```

答:
use:</p>

```<code><?php
  $DisplayDate = date("l jS \of F Y h:i:s A") ;
  $base64 = base64_encode($DisplayDate);

  setcookie("LastRequestDate", $base64, time()+60*60*24*7, "/");

  $LastRequestDate = $_COOKIE['LastRequestDate'];
  echo base64_decode($LastRequestDate);
?>
</code>```

Body:
I finally got cookies to work only for my output to display like this:

You last requested an internship opportunity on
  Wednesday%2C+November+15%2C+2017%2C+3%3A+33+AM.

I have tried using urldecode(),rawurldecode(), setrawcookie(), implode(), and explode(). None of these have had any affect on the output, and I haven't seen other suggestions in similar questions. If anyone has an idea of what might work, I would appreciate the information.

Below I have included some of the code (there's two files involved so I won't post those unless necessary).

Cookie info pulled from top of page

if(isset($_COOKIE['LastRequestDate']))
    $LastRequestDate = $_COOKIE['LastRequestDate'];
else
    $LastRequestDate = "";

Cookie variable displayed

echo "
You last requested an internship opportunity on ".$LastRequestDate."
";

Here's the code that set's the cookie from another page. I have tried removing the urlencode() but nothing changes.

setcookie("LastRequestDate", urlencode($DisplayDate), time()+60*60*24*7, "/");

Body:
use:

<?php
  $DisplayDate = date("l jS \of F Y h:i:s A") ;
  $base64 = base64_encode($DisplayDate);

  setcookie("LastRequestDate", $base64, time()+60*60*24*7, "/");

  $LastRequestDate = $_COOKIE['LastRequestDate'];
  echo base64_decode($LastRequestDate);
?>


问:
Detect non-null reference in an array
I just asked a similar question, but then I realized I actually need something else. Since that question already has two answers, I do not want to edit my question. So here is what I actually need:

I want to detect whether a subrange of an array contains null references only. Somehow like this:

```<code>public static <T> boolean nullReferencesOnly
(T[] array, int fromInclusive, int toExclusive)
{
    for (int i = fromInclusive; i < toExclusive; ++i)
    {
        if (array[i] != null) return false;
    }
    return true;
}
</code>```

Is there a method like this in the Java library so I don't have to manually loop over the array?

答:
```<code>Collections.frequency(Arrays.asList(array), null) == array.length
</code>```

For a range, SLaks has already suggested .subList(from, to) in his answer.

Title: Detect non-null reference in an array

Body:
I just asked a similar question, but then I realized I actually need something else. Since that question already has two answers, I do not want to edit my question. So here is what I actually need:

I want to detect whether a subrange of an array contains null references only. Somehow like this:

public static <T> boolean nullReferencesOnly
(T[] array, int fromInclusive, int toExclusive)
{
    for (int i = fromInclusive; i < toExclusive; ++i)
    {
        if (array[i] != null) return false;
    }
    return true;
}

Is there a method like this in the Java library so I don't have to manually loop over the array?

Body:
Collections.frequency(Arrays.asList(array), null) == array.length

For a range, SLaks has already suggested .subList(from, to) in his answer.


问:
FindBugs raises a bug called EI_EXPOSE_REP caused by Array
FindBugs raises a bug called EI_EXPOSE_REP with the following description :

EI: May expose internal representation by returning reference to mutable object

Returning a reference to a mutable object value stored in one of the object's fields exposes the internal representation of the object. If instances are accessed by untrusted code, and unchecked changes to the mutable object would compromise security or other important properties, you will need to do something different. Returning a new copy of the object is a better approach in many situations.

```<code>class Person {
    private String[] hobbies;
    String[] getHobbies(){ return hobbies;}
    void setHobbies(String[] hobbies){ this.hobbies = hobbies;}
}
</code>```

I know some solutions：

getHobbies(){return hobbies.clone();}

use List instead of Array;

What I want to know is why just array raises this bug, a list doesn't have this problem? Why array is so different from other collections？

答:
Findbugs (which is now replaced by Spotbugs) raises a security issue. It is not a bug since it doesn't create an unwanted behavior by itself. But this exposure of the internal data CAN create bugs later in caller methods.

You guessed it, there are two ways to protect your getter against exposure:

Return a copy of your array with Arrays.copyOf(..)

Convert it to an "Immutable" List with Collections.unmodifiableList(..) (you can also use List.of(..) since Java 9)

A List will raise a similar warning unless made unmodifiable.
It's a good practice to use Collections instead of Arrays unless you really have a good reason not to.

In some cases, when you have few writes and many reads, the Class CopyOnWriteArrayList is a great alternative to have a simple immutable list getter.

What I want to know is why just array raises this bug.

It's just a warning. Findbugs displays a severity level next to the report.

Exposure is a medium one for security, but low for bugs.

A list doesn't have this problem?

It does. An ArrayList is just an Array with an additional layer of abstraction.

Why array is so different from other collections?

An Array is a native type, while Collections are not.

The behavior is similar, but you have less control over an Array than you have over a Collection.

Body:
FindBugs raises a bug called EI_EXPOSE_REP with the following description :

EI: May expose internal representation by returning reference to mutable object

Returning a reference to a mutable object value stored in one of the object's fields exposes the internal representation of the object. If instances are accessed by untrusted code, and unchecked changes to the mutable object would compromise security or other important properties, you will need to do something different. Returning a new copy of the object is a better approach in many situations.

class Person {
    private String[] hobbies;
    String[] getHobbies(){ return hobbies;}
    void setHobbies(String[] hobbies){ this.hobbies = hobbies;}
}

I know some solutions：

getHobbies(){return hobbies.clone();}

use List instead of Array;

What I want to know is why just array raises this bug, a list doesn't have this problem? Why array is so different from other collections？


问:
MS Office URL-authentication
We are willing to implement a web application with edit functionalities of WORD documents using WebDav.
We are starting to have a better picture of the implementation required however, we have read on your site (http://www.webdavsystem.com/server/documentation/ms_office_read_only) that it is possible to avoid MS office Word login dialog to open when URL-authentication is implemented.

We can hardly find solutions on how to achieve this or on how to use URL-authentication with MS Office.

Would you be able to point us in the right direction with this process or even let us know how to get some examples on that?

答:
Here are some options to avoid login dialog:

Implement URL authentication. You will need to include some session
ID in the URL. Note that you will need to include it in path. For
example:

https://server/[SessionID1234567890]/path/file.docx

Do not include your session ID in the query string, as MS Office will
truncate it when saving a document.

Implement cookies/Forms authentication. In this case you will need the IT Hit
WebDAV Ajax Library to open documents for editing. You will also need to install the protocol application (Edit Document Opener, supplied with the WebDAV Ajax Library) on a client machine.

Implement MS-OFBA authentication. You can generate sample MS-OFBA
code using 'Add WebDAV Server Implementation' wizard for Visual
Studio supplied with IT Hit WebDAV Server for .NET SDK.

Note that MS-OFBA will display an HTML login dialog inside MS Office UI, which is rendered by Internet Explorer. If you open a document from any other web browser the login dialog will be always displayed during first open.

To avoid login dialog during subsequent access you will need to set permanent
authentication cookie (check the 'Keep me logged-in' checkbox).

Use Kerberos authentication. By default Kerberos authentication will display login dialog during first document access only. This option can be configured in Active Directory policies.

Title: MS Office URL-authentication


问:
ASP.NET MVC razor: conditional attribute in CSS block
Can I use if condition in style tag like this?

```<code><style>
    @@media (min-width: 765px) {
    html,body
       {
        min-width: auto;
        width: 100%;
        @{
            if (ViewBag.type == "pic")
            {
                @:min-height:100vh;
                @:height:auto;
            }
            else {
                @:height: 100vh;
            }
          }
       }
    }
</style>
</code>```

Or I should use CSS directly in HTML?

答:
You should put your css in css files and target specific classes instead of loading files conditionally.
Then you can use Razor to include conditional classes on your tags. Something like:

```<code>@{
    var imgType = ViewBag.type == "mobile"?"for-mobile":"for-desktop";
}

<img class="@imgType" src="..."/>
</code>```

Then in your CSS file:

```<code>.for-mobile{
      min-height:100vh;
      height:auto;
}

.for-desktop{
     height: 100vh;
}
</code>```

Body:
Can I use if condition in style tag like this?

Or I should use CSS directly in HTML?

Body:
You should put your css in css files and target specific classes instead of loading files conditionally.
Then you can use Razor to include conditional classes on your tags. Something like:

@{
    var imgType = ViewBag.type == "mobile"?"for-mobile":"for-desktop";
}

<img class="@imgType" src="..."/>

Then in your CSS file:

.for-mobile{
      min-height:100vh;
      height:auto;
}

.for-desktop{
     height: 100vh;
}


问:
How to add extra methods in generated classes using jaxb-xjc schema
Is there's a way to have extra methods in an class generated with JAXB ... To be more specific I would like make changes in my .xsd files and not code some methods in a "first.java" class and then make my .xsd generated classes inherit from "first.java" .. My goal is to modify only my .jaxb file .. so can we create methods with .xsd ?

I have an ".xsd" file that generates a class. And I want to know if it's possible to add to this generated class some other methods besides the getters and setters.
I search around tutorials and some StackOverflow topics but I didn't find  instructions on how can I add custom methods to a generated class described on XML Schema.

Here's my .xsd file :

```<code><?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:jxb="http://java.sun.com/xml/ns/jaxb" jxb:version="2.1">
    <xs:element name="Myclass" />
    <xs:complexType name="Myclass">
        <xs:complexContent>
        </xs:complexContent>
    </xs:complexType>
</xs:schema>
</code>```

And here's the class generated with this .xsd file :

```<code>@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Myclass")
public class Myclass
{

}
</code>```

Here's an example of a class that I want to generate with

```<code>@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Myclass")
public class Myclass
{
     public String method(){
                return "Hello";
       }
}
</code>```

Thank's in advance :)

答:
If you receive the XSDs from a client and they can change often, I would recommend not making changes to the XSDs as a design decision. I would recommend the java route as mentioned on the JAXB documentation:
https://javaee.github.io/jaxb-v2/doc/user-guide/ch03.html#compiling-xml-schema-adding-behaviors</p>

Body:
Is there's a way to have extra methods in an class generated with JAXB ... To be more specific I would like make changes in my .xsd files and not code some methods in a "first.java" class and then make my .xsd generated classes inherit from "first.java" .. My goal is to modify only my .jaxb file .. so can we create methods with .xsd ?

I have an ".xsd" file that generates a class. And I want to know if it's possible to add to this generated class some other methods besides the getters and setters.
I search around tutorials and some StackOverflow topics but I didn't find  instructions on how can I add custom methods to a generated class described on XML Schema.

Here's my .xsd file :

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:jxb="http://java.sun.com/xml/ns/jaxb" jxb:version="2.1">
    <xs:element name="Myclass" />
    <xs:complexType name="Myclass">
        <xs:complexContent>
        </xs:complexContent>
    </xs:complexType>
</xs:schema>

And here's the class generated with this .xsd file :

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Myclass")
public class Myclass
{

}

Here's an example of a class that I want to generate with

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Myclass")
public class Myclass
{
     public String method(){
                return "Hello";
       }
}

Thank's in advance :)