问:
Displaying portion of text from text file in C
I have a text file and I wanted to extract only a specific part of it at a particular time.For that ,I used ftell() while writing to note the start and end positions and then use fseek() to jump to that particular location.

```<code>     int main()
    {
       FILE *fp=fopen("myt","w+");
       char s[80];
       printf ( "\nEnter a few lines of text:\n" ) ;
       while ( strlen ( gets ( s ) ) > 0 )  //user inputs random data
      {                                     //till enter is pressed
       fputs ( s, fp ) ;
       fputs ( "\n", fp ) ;
      }

     long int a=ftell(fp);
     fputs("this line is supposed to be printed only ",fp);//line to be
                                                           // displayed
     fputs("\n",fp);
     long int b=ftell(fp);
     printf("start is %ld",a);
     printf("\nend is %ld",b);
     printf("here is the data...\n");
     rewind(fp);
     fseek(fp,a,SEEK_CUR);   //move to the starting position of text to be
                            //displayed
     char x[1000];
     fgets(x,b-a,SEEK_CUR);
     printf("%s",x);
     return 1;
  }
</code>```

I tried this but face a unexpected abnormal termination of program.Please guide me as to how correctly implement my task.

答:
You want this:

Comments starting with //// are mine

```<code>#include <stdio.h>     //// include required header files
#include <string.h>

int main()
{
  FILE *fp = fopen("myt", "w+");

  if (fp == NULL)     //// test if file has been opened sucessfully
  {
    printf("Can't open file\n");
    return 1;         //// return 1 in case of failure
  }

  char s[80];
  printf("\nEnter a few lines of text:\n");
  while (strlen(gets(s)) > 0)  //user inputs random data
  {                                     //till enter is pressed
    fputs(s, fp);
    fputs("\n", fp);
  }

  long int a = ftell(fp);
  fputs("this line is supposed to be printed only ", fp);//line to be
                                                         // displayed
  fputs("\n", fp);
  long int b = ftell(fp);
  printf("start is %ld", a);
  printf("\nend is %ld", b);
  printf("here is the data...\n");
  rewind(fp);
  fseek(fp, a, SEEK_CUR);   //move to the starting position of text to be
                            //displayed
  char x[1000];
  fgets(x, sizeof(x), fp); //// the usage of fgets was totally wrong
  printf("%s", x);

  return 0;   //// return 0 in case of success, no one
}
</code>```

Disclaimer: The first part reading the strings using gets is still sloppy, you should never use gets, it's an old deprecated function. Use fgets  instead.

Body:
I have a text file and I wanted to extract only a specific part of it at a particular time.For that ,I used ftell() while writing to note the start and end positions and then use fseek() to jump to that particular location.

     int main()
    {
       FILE *fp=fopen("myt","w+");
       char s[80];
       printf ( "\nEnter a few lines of text:\n" ) ;
       while ( strlen ( gets ( s ) ) > 0 )  //user inputs random data
      {                                     //till enter is pressed
       fputs ( s, fp ) ;
       fputs ( "\n", fp ) ;
      }

     long int a=ftell(fp);
     fputs("this line is supposed to be printed only ",fp);//line to be
                                                           // displayed
     fputs("\n",fp);
     long int b=ftell(fp);
     printf("start is %ld",a);
     printf("\nend is %ld",b);
     printf("here is the data...\n");
     rewind(fp);
     fseek(fp,a,SEEK_CUR);   //move to the starting position of text to be
                            //displayed
     char x[1000];
     fgets(x,b-a,SEEK_CUR);
     printf("%s",x);
     return 1;
  }

I tried this but face a unexpected abnormal termination of program.Please guide me as to how correctly implement my task.

Body:
You want this:

Comments starting with //// are mine

#include <stdio.h>     //// include required header files
#include <string.h>

int main()
{
  FILE *fp = fopen("myt", "w+");

  if (fp == NULL)     //// test if file has been opened sucessfully
  {
    printf("Can't open file\n");
    return 1;         //// return 1 in case of failure
  }

  char s[80];
  printf("\nEnter a few lines of text:\n");
  while (strlen(gets(s)) > 0)  //user inputs random data
  {                                     //till enter is pressed
    fputs(s, fp);
    fputs("\n", fp);
  }

  long int a = ftell(fp);
  fputs("this line is supposed to be printed only ", fp);//line to be
                                                         // displayed
  fputs("\n", fp);
  long int b = ftell(fp);
  printf("start is %ld", a);
  printf("\nend is %ld", b);
  printf("here is the data...\n");
  rewind(fp);
  fseek(fp, a, SEEK_CUR);   //move to the starting position of text to be
                            //displayed
  char x[1000];
  fgets(x, sizeof(x), fp); //// the usage of fgets was totally wrong
  printf("%s", x);

  return 0;   //// return 0 in case of success, no one
}

Disclaimer: The first part reading the strings using gets is still sloppy, you should never use gets, it's an old deprecated function. Use fgets  instead.


来源: stackexchange

问:
UIBarButtonItem tint color not working
I have recently noticed that the behaviour of the tintColor property has changed significantly in one of the recent iOS 10 updates.

I had a code which was working perfectly previously and which now is not working at all.

In one of my apps I have a collection of UIBarButtonItems which are added to the toolbarItems array of the view controller. They are displayed fine.

However, at some point I want to change the tint color of certain items in response to the user action. The code is trivial:

```<code>flagButton.tintColor = [UIColor redColor];
</code>```

This code used to work before, but now it doesn't work! I have verified that a reference to the UIBarButtonItem exists and that this line of code is executed. However, the tint color is not changing as it should.

In the description of the tintColor property it says:

To refresh subview rendering when this property changes, override the tintColorDidChange() method.

I tried adding the tintColorDidChange method but it is not called. My assumption at this stage is that once tintColor is changed my button is not refreshed automatically.

Could someone help with finding a way to refresh it manually? The button is a standard UIBarButtonItem with an image.

Update 1

Actually I noticed that if I change the tintColor of the toolbar instead of an individual item the code is working. It seems that for some reason setting the tint color on individual items no longer works. Does anyone know why this is the case?

Update 2

Thanks to matt's hint I was able to find the source of the problem. It was caused by the code executed when the app was launched:

```<code>[[UITableViewCell appearance] setTintColor:[ColourTheme sharedTheme].navBackground];
</code>```

Now, I am completely puzzled as to why this line caused problems with the UIBarButtonItem tint color... It might be because it introduced some ambiguities into the UIAppearance. Anyway, as I no longer need this line myself I can remove it easily. I will still leave my question open as I think that such behaviour is super weird and so, in a way, the question is still unanswered.

Just as an additional info - the view controller which experienced these problems contained a table view in it.

答:
I guess you are using UIImageRenderingMode.alwaysOriginal and it causes a problem.

```<code>public enum UIImageRenderingMode : Int {

     case automatic // Use the default rendering mode for the context where the image is used
     case alwaysOriginal // Always draw the original image, without treating it as a template
     case alwaysTemplate // Always draw the image as a template image, ignoring its color information

}
</code>```

Use .alwaysTemplate instead

ContentLicense: CC BY-SA 3.0

Title: UIBarButtonItem tint color not working

Body:
I have recently noticed that the behaviour of the tintColor property has changed significantly in one of the recent iOS 10 updates.

I had a code which was working perfectly previously and which now is not working at all.

In one of my apps I have a collection of UIBarButtonItems which are added to the toolbarItems array of the view controller. They are displayed fine.

However, at some point I want to change the tint color of certain items in response to the user action. The code is trivial:

flagButton.tintColor = [UIColor redColor];

This code used to work before, but now it doesn't work! I have verified that a reference to the UIBarButtonItem exists and that this line of code is executed. However, the tint color is not changing as it should.

In the description of the tintColor property it says:

To refresh subview rendering when this property changes, override the tintColorDidChange() method.

I tried adding the tintColorDidChange method but it is not called. My assumption at this stage is that once tintColor is changed my button is not refreshed automatically.

Could someone help with finding a way to refresh it manually? The button is a standard UIBarButtonItem with an image.

Update 1

Actually I noticed that if I change the tintColor of the toolbar instead of an individual item the code is working. It seems that for some reason setting the tint color on individual items no longer works. Does anyone know why this is the case?

Update 2

Thanks to matt's hint I was able to find the source of the problem. It was caused by the code executed when the app was launched:

[[UITableViewCell appearance] setTintColor:[ColourTheme sharedTheme].navBackground];

Now, I am completely puzzled as to why this line caused problems with the UIBarButtonItem tint color... It might be because it introduced some ambiguities into the UIAppearance. Anyway, as I no longer need this line myself I can remove it easily. I will still leave my question open as I think that such behaviour is super weird and so, in a way, the question is still unanswered.

Just as an additional info - the view controller which experienced these problems contained a table view in it.

Body:
I guess you are using UIImageRenderingMode.alwaysOriginal and it causes a problem.

public enum UIImageRenderingMode : Int {

     case automatic // Use the default rendering mode for the context where the image is used
     case alwaysOriginal // Always draw the original image, without treating it as a template
     case alwaysTemplate // Always draw the image as a template image, ignoring its color information

}

Use .alwaysTemplate instead


问:
Retrieving source code using XMLhttpRequest in javascript
I am trying to get the source code of a website by using XMLhttpRequest in javascript, but I cannot get the response. How do I get source code using XMLhttpRequest? Here is what I have right now:</p>

```<code><script language="Javascript" type="text/javascript">
var req = new XMLHttpRequest();
req.open(
    "GET",
    "http://www.google.com",
    true);
req.onreadystatechange = statusListener;
req.send(null);

function statusListener()
{
if (req.readyState == 4)
    {
        var docx=req.responseXML;
        alert(docx);
    }
}
</script>
</code>```

答:
You can't do a xmlHttpRequest to a different domain than your page, but you can still retrieve the contents with a proxy script in your domain:

```<code>#proxy-script (proxy.php)
<?php
echo file_get_contents ( $_GET['url'] );
?>
</code>```

And your javascript should look like this:

```<code><script language="Javascript" type="text/javascript">
var myUrl = "http://www.google.com";
var req = new XMLHttpRequest();
req.open(
    "GET",
    "/proxy.php?url="+encodeURIComponent(myUrl),
    true);
req.onreadystatechange = statusListener;
req.send(null);

function statusListener()
{
if (xmlhttp.readyState == 4)
    {
        var docx=xmlhttp.responseXML;
        alert(docx);
    }
}
</script>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You can't do a xmlHttpRequest to a different domain than your page, but you can still retrieve the contents with a proxy script in your domain:

#proxy-script (proxy.php)
<?php
echo file_get_contents ( $_GET['url'] );
?>

And your javascript should look like this:

<script language="Javascript" type="text/javascript">
var myUrl = "http://www.google.com";
var req = new XMLHttpRequest();
req.open(
    "GET",
    "/proxy.php?url="+encodeURIComponent(myUrl),
    true);
req.onreadystatechange = statusListener;
req.send(null);

function statusListener()
{
if (xmlhttp.readyState == 4)
    {
        var docx=xmlhttp.responseXML;
        alert(docx);
    }
}
</script>


问:
Streaming blob using Spring batch
I need to write a ETL where I need to migrate blob(s) from one storage to another. Size of the individual blob can be as big as 100gb.

Is it possible to stream those blob using Spring batch framework? I see there is a concept of reader, processor and writer. What I'm not sure is, if it's possible to get a handle of my blob source InputStream in the Spring batch writer, so that I can stream data from my source to sink datasource.

Thanks.

答:
I think ItemReader/Processor/Writer will not help you here. This abstraction is good for transforming records within database. But in your case it's complicated because record will not fit into the memory.

What you can get use of Reader/Processor/Writer approach (and spring batch) is transaction handling and restartability.

So main problem here: you need to find proper way how to stream blobs from one storage to another. Then this logic should go to either Processor or Writer.

Title: Streaming blob using Spring batch


问:
Vue Directive not updating it's value - Jquery Chosen
I am using Jquery Chosen along with Vue. This is my Vue directive:

```<code>Vue.component("chosen-select", {
    props: {
        value: [String, Array],
        multiple: Boolean
    },
    template: `<select :multiple="multiple"><slot></slot></select>`,
    mounted() {
        $(this.$el)
            .val(this.value)
            .chosen({ width: '100%' })
            .on("change", e => this.$emit('input', $(this.$el).val()))
    },
    watch: {
        value(val) {
            $(this.$el).val(val).trigger('chosen:updated');
        }
    },
    destroyed() {
        $(this.$el).chosen('destroy');
    }
});
</code>```

And using it like this:

```<code><chosen-select v-model="basicDetailsModel.stateID" v-validate="'required'" data-vv-as="state" :state="errors.has('stateID') ? 'invalid' : 'valid'" name="stateID">
                        <option :value="null">Please select an option</option>
                        <option v-for="(state, index) in states" :key="index" :value="state.sid">{{state.nm}}</option>
                    </chosen-select>
</code>```

If the states are assigned static value it works fine as per expectation but if I fetch the states value dynamically the chosen is not updated with latest values. It stays with the initial values.

How would I fix this issue?

Edit: This one works. Do you think this is the right way?

```<code>Vue.component("chosen-select", {
    data() {
        return { observer: null }
    },
    props: {
        value: [String, Array],
        multiple: Boolean
    },
    template: `<select :multiple="multiple"><slot></slot></select>`,
    mounted() {
        // Create the observer (and what to do on changes...)
        this.observer = new MutationObserver(function (mutations) {
            $(this.$el).trigger("chosen:updated");
        }.bind(this));

        // Setup the observer
        this.observer.observe(
            $(this.$el)[0],
            { childList: true }
        );
        $(this.$el)
            .val(this.value)
            .chosen({ width: '100%' })
            .on("change", e => this.$emit('input', $(this.$el).val()))
    },
    watch: {
        value(val) {
            $(this.$el).val(val);
        }
    },
    destroyed() {
        $(this.$el).chosen('destroy');
    }
});
</code>```

答:
The easiest way to fix this issue is simply not to render the select until you have options to render using v-if.

```<code><chosen-select v-if="states && states.length > 0" v-model="basicDetailsModel.stateID" v-validate="'required'" data-vv-as="state" :state="errors.has('stateID') ? 'invalid' : 'valid'" name="stateID">
</code>```

You could also play around with emitting the chosen:updated event when the component is updated.

```<code>updated(){
  $(this.$el).trigger("chosen:updated")
},
</code>```

which works for multiple selects, but mysteriously not for single selects.

Body:
I am using Jquery Chosen along with Vue. This is my Vue directive:

Vue.component("chosen-select", {
    props: {
        value: [String, Array],
        multiple: Boolean
    },
    template: `<select :multiple="multiple"><slot></slot></select>`,
    mounted() {
        $(this.$el)
            .val(this.value)
            .chosen({ width: '100%' })
            .on("change", e => this.$emit('input', $(this.$el).val()))
    },
    watch: {
        value(val) {
            $(this.$el).val(val).trigger('chosen:updated');
        }
    },
    destroyed() {
        $(this.$el).chosen('destroy');
    }
});

And using it like this:

<chosen-select v-model="basicDetailsModel.stateID" v-validate="'required'" data-vv-as="state" :state="errors.has('stateID') ? 'invalid' : 'valid'" name="stateID">
                        <option :value="null">Please select an option</option>
                        <option v-for="(state, index) in states" :key="index" :value="state.sid">{{state.nm}}</option>
                    </chosen-select>

If the states are assigned static value it works fine as per expectation but if I fetch the states value dynamically the chosen is not updated with latest values. It stays with the initial values.

How would I fix this issue?

Edit: This one works. Do you think this is the right way?

Vue.component("chosen-select", {
    data() {
        return { observer: null }
    },
    props: {
        value: [String, Array],
        multiple: Boolean
    },
    template: `<select :multiple="multiple"><slot></slot></select>`,
    mounted() {
        // Create the observer (and what to do on changes...)
        this.observer = new MutationObserver(function (mutations) {
            $(this.$el).trigger("chosen:updated");
        }.bind(this));

        // Setup the observer
        this.observer.observe(
            $(this.$el)[0],
            { childList: true }
        );
        $(this.$el)
            .val(this.value)
            .chosen({ width: '100%' })
            .on("change", e => this.$emit('input', $(this.$el).val()))
    },
    watch: {
        value(val) {
            $(this.$el).val(val);
        }
    },
    destroyed() {
        $(this.$el).chosen('destroy');
    }
});

Body:
The easiest way to fix this issue is simply not to render the select until you have options to render using v-if.

<chosen-select v-if="states && states.length > 0" v-model="basicDetailsModel.stateID" v-validate="'required'" data-vv-as="state" :state="errors.has('stateID') ? 'invalid' : 'valid'" name="stateID">

You could also play around with emitting the chosen:updated event when the component is updated.

updated(){
  $(this.$el).trigger("chosen:updated")
},

which works for multiple selects, but mysteriously not for single selects.


问:
bqplot: performance issue
I was playing around with on_drag features of bqplot. and I noticed that it is slightly lagging..
I am not sure if this is

real issue

I do something inappropriate

meant to work like it is

so the code I have is the following

```<code>from bqplot import pyplot as plt
import numpy as np
fig=plt.figure()
lin=plt.plot([0,1],
             [0,0])
scatt1=plt.scatter([0],[0],colors=['Red'])
scatt2=plt.scatter([1],[0],enable_move=True)

plt.xlim(-3,3)
plt.ylim(-3,3)
fig.layout.height = '500px'
fig.layout.width = '500px'
plt.show()
def call_back2(name, value):
   #print(value,name)
   if value['point']:
       X=value['point']['x']
       Y=value['point']['y']
       lin.x=[scatt1.x[0],(X-scatt1.x)[0]]
       lin.y=[scatt1.y[0],(Y-scatt1.y)[0]]

scatt2.on_drag_start(call_back2)
scatt2.on_drag(call_back2)
scatt2.on_drag_end(call_back2)
</code>```

it is simply two points connected
and you can drag the blue one around
what I notice is that the line ever so slightly lags behind the blue dot.

答:
You can't directly drag a point on a line.  Your method is only way to do it that I know of and so the line will always follow the scatter point.   I couldn't get your code to go noticeably faster.

```<code>from bqplot import pyplot as plt
import numpy as np
fig = plt.figure()
lin=plt.plot([0,1],
             [0,0])
scatt1=plt.scatter([0],[0],colors=['Red'])
scatt2=plt.scatter([1],[0],enable_move=True)
# scatt2.update_on_move = True

plt.xlim(-3,3)
plt.ylim(-3,3)
fig.layout.height = '500px'
fig.layout.width = '500px'
plt.show()
def call_back2(name, value):
#     with lin.hold_sync():
   lin.x=[lin.x[0], value['point']['x']]
   lin.y=[lin.y[0], value['point']['y']]

# scatt2.on_drag_start(call_back2)
scatt2.on_drag(call_back2 )
# scatt2.on_drag_end(call_back2)
</code>```

Edit:

Actually it can be done.  Use jslink.  The traits must be the same type and length/size. In this case, the 'x' and 'y' traits for the line and scatter marks are arrays of length 2.

from bqplot import pyplot as plt
from ipywidgets import jslink

fig = plt.figure()

# Strange bug when 1st point is 0,0. Red point flickers.
lin=plt.plot([0.0001,1],
             [0.0001,0])

scatt2=plt.scatter(lin.x, lin.y, enable_move = True, colors = ['Red','blue'])
scatt2.update_on_move = True

# Cover up 1st point so it can't be moved.
# Just remove this line if you want both points to be moveable
scatt3=plt.scatter([lin.x[0]], [lin.y[0]], colors = ['Red'])

plt.xlim(-3,3)
plt.ylim(-3,3)
fig.layout.height = '500px'
fig.layout.width = '500px'
plt.show()

jslink((scatt2, 'x'), (lin, 'x'))
jslink((scatt2, 'y'), (lin, 'y'))
```

<p>Jslink doesn't need the Python kernel for the interactivity to work.
You you can create a html file (and js directory) by:</p>

```import ipyvolume.embed
ipyvolume.embed.embed_html("bqplot.html", fig, offline=True, devmode=False)
```

Title: bqplot: performance issue

Body:
I was playing around with on_drag features of bqplot. and I noticed that it is slightly lagging..
I am not sure if this is

real issue

I do something inappropriate

meant to work like it is

so the code I have is the following

from bqplot import pyplot as plt
import numpy as np
fig=plt.figure()
lin=plt.plot([0,1],
             [0,0])
scatt1=plt.scatter([0],[0],colors=['Red'])
scatt2=plt.scatter([1],[0],enable_move=True)

plt.xlim(-3,3)
plt.ylim(-3,3)
fig.layout.height = '500px'
fig.layout.width = '500px'
plt.show()
def call_back2(name, value):
   #print(value,name)
   if value['point']:
       X=value['point']['x']
       Y=value['point']['y']
       lin.x=[scatt1.x[0],(X-scatt1.x)[0]]
       lin.y=[scatt1.y[0],(Y-scatt1.y)[0]]

scatt2.on_drag_start(call_back2)
scatt2.on_drag(call_back2)
scatt2.on_drag_end(call_back2)

it is simply two points connected
and you can drag the blue one around
what I notice is that the line ever so slightly lags behind the blue dot.

Body:
You can't directly drag a point on a line.  Your method is only way to do it that I know of and so the line will always follow the scatter point.   I couldn't get your code to go noticeably faster.

from bqplot import pyplot as plt
import numpy as np
fig = plt.figure()
lin=plt.plot([0,1],
             [0,0])
scatt1=plt.scatter([0],[0],colors=['Red'])
scatt2=plt.scatter([1],[0],enable_move=True)
# scatt2.update_on_move = True

plt.xlim(-3,3)
plt.ylim(-3,3)
fig.layout.height = '500px'
fig.layout.width = '500px'
plt.show()
def call_back2(name, value):
#     with lin.hold_sync():
   lin.x=[lin.x[0], value['point']['x']]
   lin.y=[lin.y[0], value['point']['y']]

# scatt2.on_drag_start(call_back2)
scatt2.on_drag(call_back2 )
# scatt2.on_drag_end(call_back2)

Edit:

Actually it can be done.  Use jslink.  The traits must be the same type and length/size. In this case, the 'x' and 'y' traits for the line and scatter marks are arrays of length 2.

from bqplot import pyplot as plt
from ipywidgets import jslink

fig = plt.figure()

# Strange bug when 1st point is 0,0. Red point flickers.
lin=plt.plot([0.0001,1],
             [0.0001,0])

scatt2=plt.scatter(lin.x, lin.y, enable_move = True, colors = ['Red','blue'])
scatt2.update_on_move = True

# Cover up 1st point so it can't be moved.
# Just remove this line if you want both points to be moveable
scatt3=plt.scatter([lin.x[0]], [lin.y[0]], colors = ['Red'])

plt.xlim(-3,3)
plt.ylim(-3,3)
fig.layout.height = '500px'
fig.layout.width = '500px'
plt.show()

jslink((scatt2, 'x'), (lin, 'x'))
jslink((scatt2, 'y'), (lin, 'y'))

Jslink doesn't need the Python kernel for the interactivity to work.
You you can create a html file (and js directory) by:

import ipyvolume.embed
ipyvolume.embed.embed_html("bqplot.html", fig, offline=True, devmode=False)


问:
PHP foreach object error
I used a POST method later I want to add POST request to a variable but I get an error. Why I get object error?

Error code

PHP Catchable fatal error:  Object of class stdClass could not be converted to string

POST data

```<code>array(16) { ["lat"]=> string(15) "41.008550564147" ["lng"]=> string(15) "28.978239484058" ["time"]=> string(1) "6" ["type"]=> string(6) "status" ["status"]=> string(0) "" ["category"]=> string(0) "" ["subCategory"]=> string(0) "" ["room"]=> string(0) "" ["buildingAge"]=> string(0) "" ["sfloor"]=> string(0) "" ["floor"]=> string(0) "" ["square"]=> string(0) "" ["price"]=> string(0) "" ["currency"]=> string(0) "" ["value"]=> string(0) "" ["feedback"]=> string(0) "" }
</code>```

PHP code

```<code>    foreach ($_POST as $key => $value) {
        $params .= $key . "=" . $value . "&";
    }
    echo $params;
</code>```

答:
Use http_build_query instead.</p>

```<code>echo http_build_query($_POST);
</code>```

Title: PHP foreach object error

Body:
I used a POST method later I want to add POST request to a variable but I get an error. Why I get object error?

Error code

PHP Catchable fatal error:  Object of class stdClass could not be converted to string

POST data

array(16) { ["lat"]=> string(15) "41.008550564147" ["lng"]=> string(15) "28.978239484058" ["time"]=> string(1) "6" ["type"]=> string(6) "status" ["status"]=> string(0) "" ["category"]=> string(0) "" ["subCategory"]=> string(0) "" ["room"]=> string(0) "" ["buildingAge"]=> string(0) "" ["sfloor"]=> string(0) "" ["floor"]=> string(0) "" ["square"]=> string(0) "" ["price"]=> string(0) "" ["currency"]=> string(0) "" ["value"]=> string(0) "" ["feedback"]=> string(0) "" }

PHP code

    foreach ($_POST as $key => $value) {
        $params .= $key . "=" . $value . "&";
    }
    echo $params;

Body:
Use http_build_query instead.

echo http_build_query($_POST);


问:
Reference in two projects
I've two projects say P1 and P2.

P1 has a reference of P2.

so I can access P2's methods from P1. But what if I want to access P1's methods from P2 then how can I access them?

I know I can't add P1's reference in P2?

If it is possible? If yes, then how?

答:
Another way to achieve this is to have P1 reference P2 as project in the solution, but have P2 reference P1 just by its output DLL or EXE.

You lose some cross project / dependency checking, but it does allow you to cross reference.

I had to do this with a long-running WinForms application that was originally written in VB but moved to C# after some years. All new Windows Forms were written in C#, which couldn't be the same project as the VB forms, but some VB forms needed to call the new C# forms and vice verca.

EDIT 1

One drawback with this is that, if P2 references P1 as it's project output DLL/EXE and then, when you clean / rebuild the solution, there's an error, you are in the position where the output DLL/EXE no longer exists and can't be recreated until you resolve the error, but the solution can no longer be built as it has a missing reference.  Not a good place to be, so make sure to keep a copy of your output DLL/EXE from time to time so you can get out of this if it ever happens.

Title: Reference in two projects


问:
How to use if statement inside JSON?
How to use if statement inside JSON Here is the code:
.......................................................................................

```<code>var config =
             [
                {
                    "name"      : "SiteTitle",
                    "bgcolor"   : "",
                    "color"     : "",
                    "position"  : "TL",
                    "text"      : "step1",
                    "time"      : 5000
                },
                {
                    "name"      : "Jawal",
                    "bgcolor"   : "",
                    "color"     : "",
                    "text"      : "step2",
                    "position"  : "BL",
                    "time"      : 5000
                },
                {
                    "name"      : "Password",
                    "bgcolor"   : "",
                    "color"     : "",
                    "text"      : "step3",
                    "position"  : "TL",
                    "time"      : 5000
                }
            ],

            //define if steps should change automatically
            autoplay    = false,
            //timeout for the step
            showtime,
            //current step of the tour
            step        = 0,
            //total number of steps
            total_steps = config.length;
</code>```

This is the required result something like this:

```<code>    var config =
         [

    if(page==true)  {
            {
                "name"      : "SiteTitle",
                "bgcolor"   : "",
                "color"     : "",
                "position"  : "TL",
                "text"      : "step1",
                "time"      : 5000
            },
            {
                "name"      : "Jawal",
                "bgcolor"   : "",
                "color"     : "",
                "text"      : "step2",
                "position"  : "BL",
                "time"      : 5000
            }
    } else {
            {
                "name"      : "Password",
                "bgcolor"   : "",
                "color"     : "",
                "text"      : "step3",
                "position"  : "TL",
                "time"      : 5000
            }
    }
        ],

            //define if steps should change automatically
            autoplay    = false,
            //timeout for the step
            showtime,
            //current step of the tour
            step        = 0,
            //total number of steps
            total_steps = config.length;
</code>```

Actually this way is wrong and makes a JavaScript syntax error.

答:
You can do it this way also (not saying this is the best way but it's another way and could be useful in some scenarios)</p>

```<code>let config = [];
if (page) {
   config.push({
        "name"      : "SiteTitle",
        "bgcolor"   : "",
        "color"     : "",
        "position"  : "TL",
        "text"      : "step1",
        "time"      : 5000
    });
   config.push({
        "name"      : "Jawal",
        "bgcolor"   : "",
        "color"     : "",
        "text"      : "step2",
        "position"  : "BL",
        "time"      : 5000
    });
} else {
    config.push({
        "name"      : "Password",
        "bgcolor"   : "",
        "color"     : "",
        "text"      : "step3",
        "position"  : "TL",
        "time"      : 5000
    });
}
</code>```

Title: How to use if statement inside JSON?

Body:
How to use if statement inside JSON Here is the code:
.......................................................................................

var config =
             [
                {
                    "name"      : "SiteTitle",
                    "bgcolor"   : "",
                    "color"     : "",
                    "position"  : "TL",
                    "text"      : "step1",
                    "time"      : 5000
                },
                {
                    "name"      : "Jawal",
                    "bgcolor"   : "",
                    "color"     : "",
                    "text"      : "step2",
                    "position"  : "BL",
                    "time"      : 5000
                },
                {
                    "name"      : "Password",
                    "bgcolor"   : "",
                    "color"     : "",
                    "text"      : "step3",
                    "position"  : "TL",
                    "time"      : 5000
                }
            ],

            //define if steps should change automatically
            autoplay    = false,
            //timeout for the step
            showtime,
            //current step of the tour
            step        = 0,
            //total number of steps
            total_steps = config.length;

This is the required result something like this:

    var config =
         [

    if(page==true)  {
            {
                "name"      : "SiteTitle",
                "bgcolor"   : "",
                "color"     : "",
                "position"  : "TL",
                "text"      : "step1",
                "time"      : 5000
            },
            {
                "name"      : "Jawal",
                "bgcolor"   : "",
                "color"     : "",
                "text"      : "step2",
                "position"  : "BL",
                "time"      : 5000
            }
    } else {
            {
                "name"      : "Password",
                "bgcolor"   : "",
                "color"     : "",
                "text"      : "step3",
                "position"  : "TL",
                "time"      : 5000
            }
    }
        ],

            //define if steps should change automatically
            autoplay    = false,
            //timeout for the step
            showtime,
            //current step of the tour
            step        = 0,
            //total number of steps
            total_steps = config.length;

Actually this way is wrong and makes a JavaScript syntax error.

Body:
You can do it this way also (not saying this is the best way but it's another way and could be useful in some scenarios)

let config = [];
if (page) {
   config.push({
        "name"      : "SiteTitle",
        "bgcolor"   : "",
        "color"     : "",
        "position"  : "TL",
        "text"      : "step1",
        "time"      : 5000
    });
   config.push({
        "name"      : "Jawal",
        "bgcolor"   : "",
        "color"     : "",
        "text"      : "step2",
        "position"  : "BL",
        "time"      : 5000
    });
} else {
    config.push({
        "name"      : "Password",
        "bgcolor"   : "",
        "color"     : "",
        "text"      : "step3",
        "position"  : "TL",
        "time"      : 5000
    });
}


问:
How to get youtube channel id using channel custom name?
My question is very similar to this one,
I want to get channel id using channel custom name.

The answer on the question mentioned above which is:

```<code>GET https://www.googleapis.com/youtube/v3/search?part=id%2Csnippet&q=annacavalli&type=channel&key={YOUR_API_KEY}
</code>```

doesn't work on small channels, for ex. when I run it with this channel: https://www.youtube.com/AnnaShearerfashionfettish it returns nothing.

答:
I didn't find a direct way to do this. I did a GET request to get the channel page HTML and parse it.

I used Jsoup to parse the html response.

```<code>val doc = Jsoup.parseBodyFragment(body)
val links = doc.select("link[rel=canonical]")
val channelUrl = links.first().attributes().get("href")
</code>```

Body:
My question is very similar to this one,
I want to get channel id using channel custom name.

The answer on the question mentioned above which is:

GET https://www.googleapis.com/youtube/v3/search?part=id%2Csnippet&q=annacavalli&type=channel&key={YOUR_API_KEY}

doesn't work on small channels, for ex. when I run it with this channel: https://www.youtube.com/AnnaShearerfashionfettish it returns nothing.

Body:
I didn't find a direct way to do this. I did a GET request to get the channel page HTML and parse it.

I used Jsoup to parse the html response.

val doc = Jsoup.parseBodyFragment(body)
val links = doc.select("link[rel=canonical]")
val channelUrl = links.first().attributes().get("href")


问:
how to correctly handle csv.reader headers
When reading csv files, sometimes the first row (or more than one) are headers that we don't want to include in our data.

If I don't need the data from the headers I just use next before declaring the reader (if more than one row is used for headers I can call next multiple times):

```<code>with open('myfile.csv', 'rb') as f:
    next(f)                         #skip first row
    reader = csv.reader(f)
    for row in reader:
        #process my data
</code>```

Sometimes however I don't want to include the headers in my data but still need their values. In that case I transform the csv.reader into a list and handle the headers separately.

```<code>with open('myfile.csv', 'rb') as f:
    reader = list(csv.reader(f))

    my_header = reader.pop(0)   #remove header

    for row in reader:
        #process my data
</code>```

This works and I'm happy about it. But I'm not sure if it's the "best practice" way of using csv.reader and there are other ways worth exploring.

答:
It's indeed not the best practice - it reads the whole file in memory for no good reason.  The funny part is that there's almost nothing to change to your first snippet to get the headers...

next(iterator) does return the "current" element:

```<code>>>> it = iter(["hello", "world"])
>>> next(it)
'hello'
>>> next(it)
'world'
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
</code>```

So all you have to do is

```<code>with open('myfile.csv', 'rb') as f:
    reader = csv.reader(f)
    headers = next(reader)
    for row in reader:
        #process my data
</code>```

FWIW, the way you skip "the first row" in your first snippet is brittle - you're actually skipping the first line, which is not necessarily the first row (some csv format have newlines embeded in rows), so for the "no header" version you actually want:

```<code>with open('myfile.csv', 'rb') as f:
    reader = csv.reader(f)
    next(reader) # skip first row
    for row in reader:
        #process my data
</code>```

Body:
When reading csv files, sometimes the first row (or more than one) are headers that we don't want to include in our data.

If I don't need the data from the headers I just use next before declaring the reader (if more than one row is used for headers I can call next multiple times):

with open('myfile.csv', 'rb') as f:
    next(f)                         #skip first row
    reader = csv.reader(f)
    for row in reader:
        #process my data

Sometimes however I don't want to include the headers in my data but still need their values. In that case I transform the csv.reader into a list and handle the headers separately.

with open('myfile.csv', 'rb') as f:
    reader = list(csv.reader(f))

    my_header = reader.pop(0)   #remove header

    for row in reader:
        #process my data

This works and I'm happy about it. But I'm not sure if it's the "best practice" way of using csv.reader and there are other ways worth exploring.

Body:
It's indeed not the best practice - it reads the whole file in memory for no good reason.  The funny part is that there's almost nothing to change to your first snippet to get the headers...

next(iterator) does return the "current" element:

>>> it = iter(["hello", "world"])
>>> next(it)
'hello'
>>> next(it)
'world'
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

So all you have to do is

with open('myfile.csv', 'rb') as f:
    reader = csv.reader(f)
    headers = next(reader)
    for row in reader:
        #process my data

FWIW, the way you skip "the first row" in your first snippet is brittle - you're actually skipping the first line, which is not necessarily the first row (some csv format have newlines embeded in rows), so for the "no header" version you actually want:

with open('myfile.csv', 'rb') as f:
    reader = csv.reader(f)
    next(reader) # skip first row
    for row in reader:
        #process my data


问:
How to test different permissions of CLLocationManager in test cases
I am writing a test to test CoreLocation related function. This function will throw an error if the location services is not enabled.

```<code>func someFunction() throws {
    guard CLLocationManager.locationServicesEnabled() throw NSError.init(
            domain: kCLErrorDomain,
            code: CLError.Code.denied.rawValue,
            userInfo: nil)
    }
    ...
}
</code>```

In my tests, CLLocationManager.locationServicesEnabled() is always true. Is there a way to test the false scenario?

答:
Instead of using static methods directly, wrap this call in a class and make that class adopt a protocol, so your code will depend on that interface instead of the concrete implementation.

```<code>protocol LocationManager {
    var islocationServicesEnabled: Bool { get }
}

class CoreLocationManager: LocationManager {
    var islocationServicesEnabled: Bool  {
        return CLLocationManager.locationServicesEnabled()
    }
}
</code>```

Then your function (or class) should receive that dependency instead of owning it (dependency injection):

```<code>func someFunction(locationManager: LocationManager) throws {
    guard locationManager.islocationServicesEnabled else {
        //...
    }
}
</code>```

In your tests you can pass a "Fake" LocationManager and test all the scenarios. (In your production code you pass the CoreLocationManager.)

That's a general advice for any dependency.

Body:
I am writing a test to test CoreLocation related function. This function will throw an error if the location services is not enabled.

func someFunction() throws {
    guard CLLocationManager.locationServicesEnabled() throw NSError.init(
            domain: kCLErrorDomain,
            code: CLError.Code.denied.rawValue,
            userInfo: nil)
    }
    ...
}

In my tests, CLLocationManager.locationServicesEnabled() is always true. Is there a way to test the false scenario?

Body:
Instead of using static methods directly, wrap this call in a class and make that class adopt a protocol, so your code will depend on that interface instead of the concrete implementation.

protocol LocationManager {
    var islocationServicesEnabled: Bool { get }
}

class CoreLocationManager: LocationManager {
    var islocationServicesEnabled: Bool  {
        return CLLocationManager.locationServicesEnabled()
    }
}

Then your function (or class) should receive that dependency instead of owning it (dependency injection):

func someFunction(locationManager: LocationManager) throws {
    guard locationManager.islocationServicesEnabled else {
        //...
    }
}

In your tests you can pass a "Fake" LocationManager and test all the scenarios. (In your production code you pass the CoreLocationManager.)

That's a general advice for any dependency.


问:
laravel pivot table get wrong records
this is "evalution" table

```<code>-id
-title
-slug
</code>```

this is "member" table

```<code>-id
-name
-surname
</code>```

this is "evalution_member" pivot table

```<code>-evalution_id
-member_id
</code>```

evalution table has 3 records as below

```<code>id | title | slug
1 | a | a
2 | b | b
3 | c | c
</code>```

member table has 10 records as below

```<code>id | name | surname
1 | xx1 | xx1
2 | xx2 | xx2
3 | xx3 | xx3
4 | xx4 | xx4
5 | xx5 | xx5
6 | xx6 | xx6
7 | xx7 | xx7
8 | xx8 | xx8
9 | xx9 | xx9
10 | xx10 | xx10
</code>```

evalution_member table has 10 record as below

```<code>evalution_id |member_id
1 | 1
1 | 2
1 | 3
3 | 4
3 | 5
3 | 6
3 | 7
3 | 8
3 | 9
3 | 10
</code>```

this is my Evalution model

```<code>public function members()
{
    return $this->belongsToMany('App\Member');
}
</code>```

this is my Member model

```<code>public function evalutions()
{
    return $this->belongsToMany('App\Evalution');
}
</code>```

And this is my code :

$evalution = Evalution::find($id)->with('members')->first();

Return member list from this code but coming wrong records . Right records must start on 4th item and end on last item but return list contains first 3 records.

if i change Evalution model as below :

```<code>public function members()
{
    return $this->belongsToMany('App\Http\Models\Member', 'evalution_member', 'evalution_id', 'member_id');
}
</code>```

return list contain only 1 record that is last record on the evalution_member table.

why ?

what is the problem in there ?

答:
Add pivot table name to methods like this.</p>

```<code>public function members()
{
    return $this->belongsToMany('App\Member', 'evalution_member');
}
</code>```

Title: laravel pivot table get wrong records

Body:
this is "evalution" table

-id
-title
-slug

this is "member" table

-id
-name
-surname

this is "evalution_member" pivot table

-evalution_id
-member_id

evalution table has 3 records as below

id | title | slug
1 | a | a
2 | b | b
3 | c | c

member table has 10 records as below

id | name | surname
1 | xx1 | xx1
2 | xx2 | xx2
3 | xx3 | xx3
4 | xx4 | xx4
5 | xx5 | xx5
6 | xx6 | xx6
7 | xx7 | xx7
8 | xx8 | xx8
9 | xx9 | xx9
10 | xx10 | xx10

evalution_member table has 10 record as below

evalution_id |member_id
1 | 1
1 | 2
1 | 3
3 | 4
3 | 5
3 | 6
3 | 7
3 | 8
3 | 9
3 | 10

this is my Evalution model

public function members()
{
    return $this->belongsToMany('App\Member');
}

this is my Member model

public function evalutions()
{
    return $this->belongsToMany('App\Evalution');
}

And this is my code :

$evalution = Evalution::find($id)->with('members')->first();

Return member list from this code but coming wrong records . Right records must start on 4th item and end on last item but return list contains first 3 records.

if i change Evalution model as below :

public function members()
{
    return $this->belongsToMany('App\Http\Models\Member', 'evalution_member', 'evalution_id', 'member_id');
}

return list contain only 1 record that is last record on the evalution_member table.

why ?

what is the problem in there ?

Body:
Add pivot table name to methods like this.

public function members()
{
    return $this->belongsToMany('App\Member', 'evalution_member');
}


问:
how to fetch not null value data from mysql table
```<code><form action="" method="POST">   <?php  $que = $con->query("SELECT *
FROM ques");       while ($row=mysqli_fetch_array($que)){
          echo "Q.".$row['id'].":".$row['que']."<br>";    echo "<input type='radio'
name='".$row['id']."'value='".$row['ans']."'>".$row['ans']."<br>";
echo "<input type='radio'
name='".$row['id']."'value='".$row['op1']."'>".$row['op1']."<br>";
echo "<input type='radio'
name='".$row['id']."'value='".$row['op2']."'>".$row['op2']."<br>";
echo <input type='radio'
name='".$row['id']."'value='".$row['op3']."'>".$row['op3']."<br>";  }
    ?> <br> <input type="submit" name="sub" value="submit"> </form
>
</code>```

答:
you need to add where clause to your query.

instead of:

SELECT * FROM ques

Something like this:

```<code>SELECT * FROM ques
WHERE yourField is not null
</code>```

change the yourField to what ever field you are checking.

Body:
<form action="" method="POST">   <?php  $que = $con->query("SELECT *
FROM ques");       while ($row=mysqli_fetch_array($que)){
          echo "Q.".$row['id'].":".$row['que']."
";    echo "<input type='radio'
name='".$row['id']."'value='".$row['ans']."'>".$row['ans']."
";
echo "<input type='radio'
name='".$row['id']."'value='".$row['op1']."'>".$row['op1']."
";
echo "<input type='radio'
name='".$row['id']."'value='".$row['op2']."'>".$row['op2']."
";
echo <input type='radio'
name='".$row['id']."'value='".$row['op3']."'>".$row['op3']."
";  }
    ?>
 <input type="submit" name="sub" value="submit"> </form
>

Body:
you need to add where clause to your query.

instead of:

SELECT * FROM ques

Something like this:

SELECT * FROM ques
WHERE yourField is not null

change the yourField to what ever field you are checking.


问:
NotSerializableException - FacesCtrlActionBinding
We are using some adf internal classes to control our views, we are working on a clustering environment, the problem
is that sometimes the view page get some errors and in the log shows:

```<code>2017-11-14T09:42:15.424-02:00] [adf_server1] [ERROR] [] [oracle.adfinternal.controller.state.SessionBasedScopeMap] [tid: [ACTIVE].[[
java.io.NotSerializableException: oracle.adfinternal.view.faces.model.binding.FacesCtrlActionBinding
</code>```

Weblogic 12.1.3.0.0 ADF 12c

Does anybody know how can I make adf internal classes serializable or have another solution?

答:
These classes usually uses internal representation of the components, which are not serializable.
I would suggest to not use any ADF internal classes, since:

1) You will get warnings in JDeveloper

2) It is hard to control it!

However if you must, I would wrap declare these members as transient (to solve the serialization problem (that means this property will not be high available).

Body:
We are using some adf internal classes to control our views, we are working on a clustering environment, the problem
is that sometimes the view page get some errors and in the log shows:

2017-11-14T09:42:15.424-02:00] [adf_server1] [ERROR] [] [oracle.adfinternal.controller.state.SessionBasedScopeMap] [tid: [ACTIVE].[[
java.io.NotSerializableException: oracle.adfinternal.view.faces.model.binding.FacesCtrlActionBinding

Weblogic 12.1.3.0.0 ADF 12c

Does anybody know how can I make adf internal classes serializable or have another solution?


问:
Accessing Android drawable resource with a string
I apologize if this seems really simple but I can't figure it out. I have an ImageButton that I want to change the image of at run-time based on a button click. I have 5 images in my res folder. When the user hits the "Next" button, I want it to go to the next image. The file names of the images are image1.png, image2.png, etc.

I know I you can change the image by doing:

```<code>imgButton.setImageResource(R.drawable.image2);
</code>```

I have a counter (int) to keep track of the image number being displayed. But how would i change the image to the next image? Any help would be appreciated.

答:
Create an Array of integers to hold the references to your images, e.g.

```<code>int[] images = new int[5];
images[0] = R.drawable.image001;
images[1] = R.drawable.image002;
images[2] = R.drawable.image003;
images[3] = R.drawable.image004;
images[4] = R.drawable.image005;
</code>```

And then increment your counter on each click, and set the image resource using a value from your array:

```<code>imgButton.setImageResource(images[counter]);
</code>```

Easy when you know how... ;)

Body:
I apologize if this seems really simple but I can't figure it out. I have an ImageButton that I want to change the image of at run-time based on a button click. I have 5 images in my res folder. When the user hits the "Next" button, I want it to go to the next image. The file names of the images are image1.png, image2.png, etc.

I know I you can change the image by doing:

imgButton.setImageResource(R.drawable.image2);

I have a counter (int) to keep track of the image number being displayed. But how would i change the image to the next image? Any help would be appreciated.

Body:
Create an Array of integers to hold the references to your images, e.g.

int[] images = new int[5];
images[0] = R.drawable.image001;
images[1] = R.drawable.image002;
images[2] = R.drawable.image003;
images[3] = R.drawable.image004;
images[4] = R.drawable.image005;

And then increment your counter on each click, and set the image resource using a value from your array:

imgButton.setImageResource(images[counter]);

Easy when you know how... ;)


问:
"_" parameter of Ruby block
I met this when I read ZenTest source code:

Here is the definition of add_mapping method:

```<code>def add_mapping(regexp, &proc)
  @test_mappings << [regexp, proc]
end
</code>```

In the Autottest.initailize(), add_method get called to add mapping for implementations.

```<code>self.add_mapping(/^lib\/.*\.rb$/) do |filename, _|
  possible = File.basename(filename).gsub '_', '_?'
  files_matching %r%^test/.*#{possible}$%
end
</code>```

My question is what "_", the second parameter of the block, means? Seems it is not used in the block.

Thanks

答:
It's an idiom used to indicate the the parameter bound to '_' is not used, even though it's required to be passed to the block/method.

example:

```<code>def blah
   yield 1,2
end

blah {|a,b|
  puts a
  # b is never used
}
</code>```

compare to the identical:

```<code>blah {|a,_|
   puts a
}
</code>```

Note that '_' is a perfectly legal variable name in ruby, so the two versions are identical, the following works as well:

```<code>blah {|a,_|
   puts _
}
</code>```

Using '_' is nothing more than a convention like using i for counters, 'x' and 'y' or 'foo' and 'bar'.

It means you're cool because you've been dabbling with functional programming, which is, I believe, where this idiom orignates...

Title: "_" parameter of Ruby block

Body:
I met this when I read ZenTest source code:

Here is the definition of add_mapping method:

def add_mapping(regexp, &proc)
  @test_mappings << [regexp, proc]
end

In the Autottest.initailize(), add_method get called to add mapping for implementations.

self.add_mapping(/^lib\/.*\.rb$/) do |filename, _|
  possible = File.basename(filename).gsub '_', '_?'
  files_matching %r%^test/.*#{possible}$%
end

My question is what "_", the second parameter of the block, means? Seems it is not used in the block.

Thanks

Body:
It's an idiom used to indicate the the parameter bound to '_' is not used, even though it's required to be passed to the block/method.

example:

def blah
   yield 1,2
end

blah {|a,b|
  puts a
  # b is never used
}

compare to the identical:

blah {|a,_|
   puts a
}

Note that '_' is a perfectly legal variable name in ruby, so the two versions are identical, the following works as well:

blah {|a,_|
   puts _
}

Using '_' is nothing more than a convention like using i for counters, 'x' and 'y' or 'foo' and 'bar'.

It means you're cool because you've been dabbling with functional programming, which is, I believe, where this idiom orignates...


问:
Workaround to not shutdown DefaultHttpClient() each time after usage
Each time I do a Http request I invoke this method

```<code>private JSONObject getRequest(HttpUriRequest requestType) {
        httpClient = new DefaultHttpClient(); // Creating an instance here
        try {
            httpResponse = httpClient.execute(requestType);
            if (httpResponse != null && httpResponse.getStatusLine().getStatusCode() == 200) {
                httpEntity = httpResponse.getEntity();

                if (httpEntity != null) {
                    InputStream instream = httpEntity.getContent();
                    String convertedString = convertStreamToString(instream);
                    return convertToJSON(convertedString);
                } else return null;

            } else return null;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            httpClient.getConnectionManager().shutdown(); // Close the instance here
        }
    }
</code>```

So each time I create new DefaultHttpClient() object and close it after usage. If I don't close it I have numerous troubles with my application (Android). I have a foreboding this is not the cheapest operation and I need to improve this somehow. Is it possible to flush the connection somehow so I don't need to call shutdown method each time?

答:
I am sure you can re-use the same httpClient object after processing a request. You can look at This Program to see a reference code.

Just make sure after each request is executed, you clean entities off the response object. Something like:

```<code>        // Must call this to release the connection
        // #1.1.5 @
        // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html
        HttpEntity enty = response.getEntity();
        if (enty != null)
            enty.consumeContent();
</code>```

BTW, what kind of issues are you getting into, if you dont shutdown the connection mgr.

Body:
Each time I do a Http request I invoke this method

private JSONObject getRequest(HttpUriRequest requestType) {
        httpClient = new DefaultHttpClient(); // Creating an instance here
        try {
            httpResponse = httpClient.execute(requestType);
            if (httpResponse != null && httpResponse.getStatusLine().getStatusCode() == 200) {
                httpEntity = httpResponse.getEntity();

                if (httpEntity != null) {
                    InputStream instream = httpEntity.getContent();
                    String convertedString = convertStreamToString(instream);
                    return convertToJSON(convertedString);
                } else return null;

            } else return null;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            httpClient.getConnectionManager().shutdown(); // Close the instance here
        }
    }

So each time I create new DefaultHttpClient() object and close it after usage. If I don't close it I have numerous troubles with my application (Android). I have a foreboding this is not the cheapest operation and I need to improve this somehow. Is it possible to flush the connection somehow so I don't need to call shutdown method each time?

Body:
I am sure you can re-use the same httpClient object after processing a request. You can look at This Program to see a reference code.

Just make sure after each request is executed, you clean entities off the response object. Something like:

        // Must call this to release the connection
        // #1.1.5 @
        // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html
        HttpEntity enty = response.getEntity();
        if (enty != null)
            enty.consumeContent();

BTW, what kind of issues are you getting into, if you dont shutdown the connection mgr.


问:
Only show new content of PHP array with jQuery request
I'm working on improving my chat script using jQuery to display and autoscroll the messages. It already works pretty good, but I want to get rid of the 'refresh' effect when replacing the 'div' with updated content from the JSON object, which gets encoded from a PHP array containing the messages with every jQuery request.

How can I achieve this?

This is what works now for me:

```<code><head>
  <script>
    $(document).ready(function(){
      $.ajaxSetup({cache:false});
      $("a").click(function(){
        $("div").empty(); // removing this will get rid of the 'refresh' effect, but it endlessly appends the message log

        $.getJSON('ajax.php', function(data){
          $.each(data, function(i, field){
            $("div").append(field + "<br>");
          });
          $(document).scrollTop($(document).height());
        });
      });
    });

    window.onload = function() {
      document.getElementsByClassName("refreshB")[0].click();
    };

    var intervalID = window.setInterval(refresh, 10000);

    function refresh() {
      document.getElementsByClassName("refreshB")[0].click();
    }
  </script>
</head>

<body>
  <a class="refreshB"></a>
  <div></div>
</body>
</code>```

答:
First of all you must get only new rows from db.

add new column to table (for example readed) then every time update this column to know which data is new

and you won't need this $("div").empty();


问:
How to read and parse xml file present in azure data lake store using .NET?
I have few xml files in azure data lake store. i want to fetch those files from azure data lake and parse it.
How can i do that?</p>

答:
I've performed this type of operation with a custom extractor. There were two parts to it: 1., A class that mapped the XML elements to properties using System.Xml.Serialization, and 2., The extractor method which creates an XmlSerializer object of that class type, and invokes the Deserialize method of that object over input.Basestream (the data). Finally, query with U-SQL using your custom extractor--which requires the library to be compiled, uploaded, registered, and, finally, referenced--before it is invoked with the USING statement of your query.

Part 1:

```<code>[XmlRoot("SomeRoot")]
public class MyDataClass
{
    [XmlElement("ELEMENT_0")]
    public Guid Column0 { get; set; }

    [XmlElement("ELEMENT_1")]
    public long Column1 { get; set; }

    [XmlElement("ELEMENT_2")]
    public string Column2 { get; set; }
}`enter code here`
</code>```

Part 2:

```<code>[SqlUserDefinedExtractor(AtomicFileProcessing = true)]
public class Xml : IExtractor
{
    public override IEnumerable<IRow> Extract(IUnstructuredReader input, IUpdatableRow output)
    {
        XmlSerializer ser = new XmlSerializer(typeof(MyDataClass));

        MyDataClass data = (MyDataClass)ser.Deserialize(input.BaseStream);

        //blah blah

        output.Set<Guid>(0, data.Column0);
        output.Set<long>(1, data.Column1);
        output.Set<string>(2, data.Column2);
</code>```

Body:
I've performed this type of operation with a custom extractor. There were two parts to it: 1., A class that mapped the XML elements to properties using System.Xml.Serialization, and 2., The extractor method which creates an XmlSerializer object of that class type, and invokes the Deserialize method of that object over input.Basestream (the data). Finally, query with U-SQL using your custom extractor--which requires the library to be compiled, uploaded, registered, and, finally, referenced--before it is invoked with the USING statement of your query.

Part 1:

[XmlRoot("SomeRoot")]
public class MyDataClass
{
    [XmlElement("ELEMENT_0")]
    public Guid Column0 { get; set; }

    [XmlElement("ELEMENT_1")]
    public long Column1 { get; set; }

    [XmlElement("ELEMENT_2")]
    public string Column2 { get; set; }
}`enter code here`

Part 2:

[SqlUserDefinedExtractor(AtomicFileProcessing = true)]
public class Xml : IExtractor
{
    public override IEnumerable<IRow> Extract(IUnstructuredReader input, IUpdatableRow output)
    {
        XmlSerializer ser = new XmlSerializer(typeof(MyDataClass));

        MyDataClass data = (MyDataClass)ser.Deserialize(input.BaseStream);

        //blah blah

        output.Set<Guid>(0, data.Column0);
        output.Set<long>(1, data.Column1);
        output.Set<string>(2, data.Column2);


问:
How to bind a value from a select?
How can I bind a value selected with aurelia?
I have this select bellow:

```<code><select id="user" class="form-control" value.bind="filters[0].value" change.delegate="userDropdownChanged(filters[0].value)">
  <option repeat.for="user of users" model.bind="user.uuid">${user.name}</option>
</select>
</code>```

I tried bind the value, but it is showing the whole list of the select, it is a way to show just the user selected in my h1?

```<code><h1 repeat.for="user of users" model.bind="user.uuid">${user.name} </h1>
</code>```

答:
If you do the following:

```<code><select value.bind="selectedUser">
  <option repeat.for="user of users" model.bind="user.uuid">${user.name}</option>
</select>
</code>```

The value selected in your <select> will be bound to a variable in your viewmodel called selectedUser.

You can then bind that to your
 like so:

```<code><h1>${selectedUser.name}</h1>
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to bind a value from a select?

Body:
How can I bind a value selected with aurelia?
I have this select bellow:

<select id="user" class="form-control" value.bind="filters[0].value" change.delegate="userDropdownChanged(filters[0].value)">
  <option repeat.for="user of users" model.bind="user.uuid">${user.name}</option>
</select>

I tried bind the value, but it is showing the whole list of the select, it is a way to show just the user selected in my h1?

${user.name}

Body:
If you do the following:

<select value.bind="selectedUser">
  <option repeat.for="user of users" model.bind="user.uuid">${user.name}</option>
</select>

The value selected in your <select> will be bound to a variable in your viewmodel called selectedUser.

You can then bind that to your <h1> like so:

<h1>${selectedUser.name}</h1>


问:
SEGMENTATION FAULT (11) for one of my 2d arrays?
I have 2x 2D arrays as a pointer.
one is "int ** field" and the other one "char **mask".
I want to create 2 2D arrays and initialise them.
The code I have works for the int array but not for the char array, although the code is the same... why?

```<code>Minesweeper * createField(int n, int m){

    Minesweeper *ms = (Minesweeper *) malloc(sizeof(Minesweeper *));

    ms->m = m;
    ms->n = n;

    ms->field = (int **) malloc(sizeof(int *) * n);
    ms->mask  = (char **) malloc(sizeof(char *) * n);
    for(int i=0; i<n; i++){
        ms->field[i] = (int *) malloc(sizeof(int *) * m);
        ms->mask[i] = (char *) malloc(sizeof(char *) * m);
    }

    for(int k=0; k<n; k++){
        for(int j=0; j<m; j++){
            ms->field[k][j] = 0;
            ms->mask[k][j] = 'x';
        }
    }

    return ms;
}
</code>```

By the way:

Minesweeper is a typedef struct with 4 attributes: int** field, char** mask, int m and int n.

I always get Segmentation fault when I want to initialize my mask array...

答:
here is what you can use easily instead of your code :)

```<code>Minesweeper * createField(int n, int m){

    Minesweeper *ms = (Minesweeper *) malloc(sizeof(Minesweeper));

    ms->m = m;
    ms->n = n;

    ms->field = (int **) malloc(sizeof(int *) * n);
    ms->mask  = (char **) malloc(sizeof(char *) * n);
    for(int i=0; i<n; i++){
        ms->field[i] = (int *) malloc(sizeof(int ) * m);
        ms->mask[i] = (char *) malloc(sizeof(char) * m);
    }

    for(int k=0; k<n; k++){
        for(int j=0; j<m; j++){
            ms->field[k][j] = 0;
            ms->mask[k][j] = 'x';
        }
    }

     return ms;
}
</code>```

malloc declaration was not correct.
You are declaring a pointer with size of a type then you need to write as sizeof(<type>) instead of sizeof(*<type>) which will give size of pointer instead of the actual storage. It will solve the error :)

Body:
I have 2x 2D arrays as a pointer.
one is "int ** field" and the other one "char **mask".
I want to create 2 2D arrays and initialise them.
The code I have works for the int array but not for the char array, although the code is the same... why?

Minesweeper * createField(int n, int m){

    Minesweeper *ms = (Minesweeper *) malloc(sizeof(Minesweeper *));

    ms->m = m;
    ms->n = n;

    ms->field = (int **) malloc(sizeof(int *) * n);
    ms->mask  = (char **) malloc(sizeof(char *) * n);
    for(int i=0; i<n; i++){
        ms->field[i] = (int *) malloc(sizeof(int *) * m);
        ms->mask[i] = (char *) malloc(sizeof(char *) * m);
    }

    for(int k=0; k<n; k++){
        for(int j=0; j<m; j++){
            ms->field[k][j] = 0;
            ms->mask[k][j] = 'x';
        }
    }

    return ms;
}

By the way:

Minesweeper is a typedef struct with 4 attributes: int** field, char** mask, int m and int n.

I always get Segmentation fault when I want to initialize my mask array...

Body:
here is what you can use easily instead of your code :)

Minesweeper * createField(int n, int m){

    Minesweeper *ms = (Minesweeper *) malloc(sizeof(Minesweeper));

    ms->m = m;
    ms->n = n;

    ms->field = (int **) malloc(sizeof(int *) * n);
    ms->mask  = (char **) malloc(sizeof(char *) * n);
    for(int i=0; i<n; i++){
        ms->field[i] = (int *) malloc(sizeof(int ) * m);
        ms->mask[i] = (char *) malloc(sizeof(char) * m);
    }

    for(int k=0; k<n; k++){
        for(int j=0; j<m; j++){
            ms->field[k][j] = 0;
            ms->mask[k][j] = 'x';
        }
    }

     return ms;
}

malloc declaration was not correct.
You are declaring a pointer with size of a type then you need to write as sizeof(<type>) instead of sizeof(*<type>) which will give size of pointer instead of the actual storage. It will solve the error :)


问:
How can I get the number of elements of any variable of type set?
AFAIK there's no built-in function for that. Searching the web I found this function and it works for me, but I prefer not to use it since it's assembly and I can't understand what it is doing. So I wrote this function that also works:

function Cardinality(const PSet: PByteArray;
  const SizeOfSet(*in bytes*): Integer): Integer;
const
  Masks: array[0..7] of Byte = (1, 2, 4, 8, 16, 32, 64, 128);
var
  I, J: Integer;
begin
  Result := 0;
  for I := 0 to SizeOfSet - 1 do
    for J := 0 to 7 do
      if (PSet^[I] and Masks[J]) > 0 then
        Inc(Result);
end;
```

Now, I want to know if I can rely on this function? Or maybe there's a trick behind the set data type and that's why delphi doesn't have a built-in method for that.

But if my function is reliable then how can I improve it to:

Pass constants to it

Do a type check and make sure that a set is passed to the function

Pass the value instead of its address

Get rid of SizeOfSet parameter

I want to call it like Cardinality(AnySet) instead of Cardinality(@AnySet, SizeOf(TAnySet)).

By the way, I need to compile this in both XE and XE5.

答:
In earlier version of Delphi you can do this :</p>

```<code>function Card(ASet: TSet): Integer;
var
  k: TSetElement;
begin
  Result := 0;
  for k in ASet do Inc(Result);
end;
</code>```

Body:
AFAIK there's no built-in function for that. Searching the web I found this function and it works for me, but I prefer not to use it since it's assembly and I can't understand what it is doing. So I wrote this function that also works:

function Cardinality(const PSet: PByteArray;
  const SizeOfSet(*in bytes*): Integer): Integer;
const
  Masks: array[0..7] of Byte = (1, 2, 4, 8, 16, 32, 64, 128);
var
  I, J: Integer;
begin
  Result := 0;
  for I := 0 to SizeOfSet - 1 do
    for J := 0 to 7 do
      if (PSet^[I] and Masks[J]) > 0 then
        Inc(Result);
end;

Now, I want to know if I can rely on this function? Or maybe there's a trick behind the set data type and that's why delphi doesn't have a built-in method for that.

But if my function is reliable then how can I improve it to:

Pass constants to it

Do a type check and make sure that a set is passed to the function

Pass the value instead of its address

Get rid of SizeOfSet parameter

I want to call it like Cardinality(AnySet) instead of Cardinality(@AnySet, SizeOf(TAnySet)).

By the way, I need to compile this in both XE and XE5.

Body:
In earlier version of Delphi you can do this :

function Card(ASet: TSet): Integer;
var
  k: TSetElement;
begin
  Result := 0;
  for k in ASet do Inc(Result);
end;


问:
How to validate PFX with public-key privacy/integrity mode
I have a piece of embedded software generating P12/PFX formatted output data.

The PFX is not password protected, that means instead of using a password-derived encryption/mac key the data is encrypted with a public key and signed with my private key.

In RFC7292 section 3.1 this is called public-key privacy and integrity modes.

My question is, how can I validate the PFX I receive, e.g. using openssl? (I'm not restricted to use openssl, by the way I google'd around but could not find a way...)

I tried

```<code>openssl pkcs12 -info -in test.pfx
</code>```

but openssl requests a password, which is not applicable here. Did I miss any option to not being asked for a password?

答:
```<code>openssl pkcs12 -in keyStoreWithoutPW.p12 -info -passin pass: -passout pass:
</code>```

Body:
I have a piece of embedded software generating P12/PFX formatted output data.

The PFX is not password protected, that means instead of using a password-derived encryption/mac key the data is encrypted with a public key and signed with my private key.

In RFC7292 section 3.1 this is called public-key privacy and integrity modes.

My question is, how can I validate the PFX I receive, e.g. using openssl? (I'm not restricted to use openssl, by the way I google'd around but could not find a way...)

I tried

openssl pkcs12 -info -in test.pfx

but openssl requests a password, which is not applicable here. Did I miss any option to not being asked for a password?


问:
Recursively Search Dirs & SubDirs And Numerically Rename Files
I am attempting to recursively scan a directory and rename all .jpg and .jpeg files in the dirs (and sub dirs) to a numeric naming convention.

I have this syntax

```<code>get-childitem -Recurse -path C:\Users\jsimpson\Desktop\Test123 | where {($_.extension -eq '.jpg') -or ($_.extension -eq '.jpeg') | %{Rename-Item $_ -NewName (‘MyFile{0}.txt’ -f $nr++)}
</code>```

However - this gives me an error of

Missing closing '}' in statement block or type definition.

      + CategoryInfo          : ParserError: (:) [],
ParentContainsErrorRecordException

      + FullyQualifiedErrorId : MissingEndCurlyBrace

I am sure this is something mundane on my end that I am overlooking - but what would be the proper syntax to numerically rename all files?

EDIT

Current filename is P1870426.jpeg I want to rename it to 1.jpeg

The files are all an import from a digital camera and Since the files have garbage names - I am basically wanting a way to import them into a program and have the files remain in the same order.

答:
As the error message says, there's a } missing to close Where :

```<code>Get-ChildItem -Recurse -Path 'C:\Users\jsimpson\Desktop\Test123' | Where-Object {$_.Extension -match 'jpg|jpeg'} | ForEach-Object {
    $newFile = "{0}$($_.Extension)" -f $nr++
    Rename-Item $_.FullName -NewName $newFile -Force
}
</code>```

Body:
I am attempting to recursively scan a directory and rename all .jpg and .jpeg files in the dirs (and sub dirs) to a numeric naming convention.

I have this syntax

get-childitem -Recurse -path C:\Users\jsimpson\Desktop\Test123 | where {($_.extension -eq '.jpg') -or ($_.extension -eq '.jpeg') | %{Rename-Item $_ -NewName (‘MyFile{0}.txt’ -f $nr++)}

However - this gives me an error of

Missing closing '}' in statement block or type definition.

      + CategoryInfo          : ParserError: (:) [],
ParentContainsErrorRecordException

      + FullyQualifiedErrorId : MissingEndCurlyBrace

I am sure this is something mundane on my end that I am overlooking - but what would be the proper syntax to numerically rename all files?

EDIT

Current filename is P1870426.jpeg I want to rename it to 1.jpeg

The files are all an import from a digital camera and Since the files have garbage names - I am basically wanting a way to import them into a program and have the files remain in the same order.

Body:
As the error message says, there's a } missing to close Where :

Get-ChildItem -Recurse -Path 'C:\Users\jsimpson\Desktop\Test123' | Where-Object {$_.Extension -match 'jpg|jpeg'} | ForEach-Object {
    $newFile = "{0}$($_.Extension)" -f $nr++
    Rename-Item $_.FullName -NewName $newFile -Force
}


问:
AudioKit FFT conversion to dB?
First time posting, thanks for the great community!

I am using AudioKit and trying to add frequency weighting filters to the microphone input and so I am trying to understand the values that are coming out of the AudioKit AKFFTTap.

Currently I am trying to just print the FFT buffer converted into dB values

```<code>for i in 0..<self.bufferSize {
    let db = 20 * log10((self.fft?.fftData[Int(i)])!)
    print(db)
}
</code>```

I was expecting values ranging in the range of about -128 to 0, but I am getting strange values of nearly -200dB and when I blow on the microphone to peg out the readings it only reaches about -60. Am I not approaching this correctly? I was assuming that the values being output from the EZAudioFFT engine would be plain amplitude values and that the normal dB conversion math would work. Anyone have any ideas?

Thanks in advance for any discussion about this issue!

答: You need to add all of the values from self.fft?.fftData (consider changing negative values to positive before adding) and then change that to decibels

Title: AudioKit FFT conversion to dB?

Body:
First time posting, thanks for the great community!

I am using AudioKit and trying to add frequency weighting filters to the microphone input and so I am trying to understand the values that are coming out of the AudioKit AKFFTTap.

Currently I am trying to just print the FFT buffer converted into dB values

for i in 0..<self.bufferSize {
    let db = 20 * log10((self.fft?.fftData[Int(i)])!)
    print(db)
}

I was expecting values ranging in the range of about -128 to 0, but I am getting strange values of nearly -200dB and when I blow on the microphone to peg out the readings it only reaches about -60. Am I not approaching this correctly? I was assuming that the values being output from the EZAudioFFT engine would be plain amplitude values and that the normal dB conversion math would work. Anyone have any ideas?

Thanks in advance for any discussion about this issue!


问:
How to handle shared projects in multiple repos Git VisualStudio Solutions
How to handle shared projects in multiple repos Git VisualStudio Solutions?

For instance I have 3 projects:

Project_1

Project_2

CommonSharedProject

Earlier in TFS, I use to have a single repository (Generics) for all
 the project thus it was easy for me to share "CommonSharedProject"
 between the other two.

Now I have created 2 different Git Repository, i.e a.

Generic.Sender(contains Project_1)

Generic.Reciever(contians Projetc_2)

Now how to handle "CommonSharedProject"?

1st approach is that I can create one more repo for this and create NuGet packages for the common codes. But doing so will consume extra
time and effort in doing minor changes. Please suggest some good
approach.

答: Use Git submodules or subtrees. A submodule is basically a pointer to a remote repository within an existing repository.</p>


问:
How to horizontally center a div which is wider than the mobile screen?
Targeting mobile screens only, I want a circular div element which is wider than the mobile screen and is centred. This div must be an exact circle.

I've got this JSFiddle but I can't increase the width to be greater than the screen width.

I'm calculating the width based on the div height if the height is greater than the screen width. Otherwise, the width should have some minimum value greater than the current screen width.

I'm looking for a JavaScript-only solution (no jQuery), if possible. This question is a possible duplicate of this and this but I specifically need the #circle element to be wider than the screen and using position: absolute (as suggested in one of the answers over there) would cause a lot of chaos.

答:
A CSS only answer should also be okay? You can add these settings to the element in question:

```<code>position: relative;
left: 50%;
transform: translateX(-50%);
</code>```

https://jsfiddle.net/asn8mv7o/1/

Body:
A CSS only answer should also be okay? You can add these settings to the element in question:

position: relative;
left: 50%;
transform: translateX(-50%);

https://jsfiddle.net/asn8mv7o/1/


问:
How to distribute portable MPI applications?
I am working for a simulation software vendor. We are now starting to implement distributed computing with MPI for our software. I don't really understand how we should distribute our MPI capable software product.

So, MPI is a interface specification, so the actual MPI implementation should be replaceable, right? Whoever runs the cluster can provide a very specialized MPI implementation for the hardware/communication layer they use. This makes sense to me.

On the other hand, when I run ldd mympiapp I see

```<code>libmpi.so.12 => /home/mpiuser/mpich-3.2-install/lib/libmpi.so.12 (0x00007fae34684000)
</code>```

It seems that after building, my application is linked against my specific version of MPI. We already ship our application in different versions for different OSes. Should we now also add combinations for different MPI implementations? Or should we also distribute the shared libraries together with our application? What is expected from the side of users/cluster providers?

I read a lot of web resources, but most stuff I find is written from the standpoint that the one who compiles it also runs it.

答:
This issue is similar to any other software you want to ship in binary format.

If you want to support multiple platforms, and multiple OSes you have to provide binary packages. This way (were applicable) you can enforce some requirements (e.g like in RPMs).

You can also provide your binary code packed with libraries compiled for given platform (and make sure to link your binary with these libraries - e.g. using rpath).

There is no simple solution here, as you want to support different platforms, different OSes and (most probably) different compilers. An alternative is to distribute MPI part of your code as source code and providing code you want to "hide" as shared library. But this is oh, so much case dependent.

Body:
I am working for a simulation software vendor. We are now starting to implement distributed computing with MPI for our software. I don't really understand how we should distribute our MPI capable software product.

So, MPI is a interface specification, so the actual MPI implementation should be replaceable, right? Whoever runs the cluster can provide a very specialized MPI implementation for the hardware/communication layer they use. This makes sense to me.

On the other hand, when I run ldd mympiapp I see

libmpi.so.12 => /home/mpiuser/mpich-3.2-install/lib/libmpi.so.12 (0x00007fae34684000)

It seems that after building, my application is linked against my specific version of MPI. We already ship our application in different versions for different OSes. Should we now also add combinations for different MPI implementations? Or should we also distribute the shared libraries together with our application? What is expected from the side of users/cluster providers?

I read a lot of web resources, but most stuff I find is written from the standpoint that the one who compiles it also runs it.


问:
how do i format my JSON responce in PHP to look like this
My PHP code:

```<code>require ("connect.php");

$input = $_GET["query"];
$data = array();

$query = mysql_query("SELECT `abbr` FROM `states_list` WHERE `abbr` LIKE '{$input}%'") or die(mysql_error());
while ($obj = mysql_fetch_object($query)) {
    //$json = array();
    //$json['query'] = $input;
    //$json['suggestion'] = $row['abbr'];
    $json[] = $obj;
    $data = array("query"=>"$input", "suggestion"=>array($obj));
}
header("Content-type: application/json");
//echo json_encode($data);
echo '{"query":'.$input.' "suggestion":'.json_encode($json).'}';
</code>```

This is my actual response:

```<code>{"query":c "suggestion":[{"abbr":"CA"},{"abbr":"CO"},{"abbr":"CT"}]}
</code>```

This is how I would like it to look like:

```<code>{"query":c "suggestion":["CA","CO","CT"]}
</code>```

I can't seem to figure out the right way to arrange the output to get what I want ;(

答:
I'd rewrite it to this- the while loop creates an array consisting of suggestions, then it is encoded.

```<code>require ("connect.php");

$input = mysql_real_escape_string($_GET["query"]);
$data = array();

$query = mysql_query("SELECT `abbr` FROM `states_list` WHERE `abbr` LIKE '{$input}%'") or die(mysql_error());
while ($obj = mysql_fetch_object($query)) {
    $data[] = $obj->abbr;
}
header("Content-type: application/json");
echo '{"query":'.$input.' "suggestion":'.json_encode($data).'}';
</code>```

P.S. Also, don't forget to properly escape the string taken from user input in order to  avoid sql injections.

Body:
My PHP code:

require ("connect.php");

$input = $_GET["query"];
$data = array();

$query = mysql_query("SELECT `abbr` FROM `states_list` WHERE `abbr` LIKE '{$input}%'") or die(mysql_error());
while ($obj = mysql_fetch_object($query)) {
    //$json = array();
    //$json['query'] = $input;
    //$json['suggestion'] = $row['abbr'];
    $json[] = $obj;
    $data = array("query"=>"$input", "suggestion"=>array($obj));
}
header("Content-type: application/json");
//echo json_encode($data);
echo '{"query":'.$input.' "suggestion":'.json_encode($json).'}';

This is my actual response:

{"query":c "suggestion":[{"abbr":"CA"},{"abbr":"CO"},{"abbr":"CT"}]}

This is how I would like it to look like:

{"query":c "suggestion":["CA","CO","CT"]}

I can't seem to figure out the right way to arrange the output to get what I want ;(

Body:
I'd rewrite it to this- the while loop creates an array consisting of suggestions, then it is encoded.

require ("connect.php");

$input = mysql_real_escape_string($_GET["query"]);
$data = array();

$query = mysql_query("SELECT `abbr` FROM `states_list` WHERE `abbr` LIKE '{$input}%'") or die(mysql_error());
while ($obj = mysql_fetch_object($query)) {
    $data[] = $obj->abbr;
}
header("Content-type: application/json");
echo '{"query":'.$input.' "suggestion":'.json_encode($data).'}';

P.S. Also, don't forget to properly escape the string taken from user input in order to  avoid sql injections.


问:
Excel VBA copy cell formatting to range
I am creating a macro using conditional formatting. Purpose of the macro is to change the formatting (cell color and text font (bold/italic/...) and size) of cells in columns A to M, depending on the value of column M.

I defined 5 conditions and changed the conditional formatting of the cells of column M, so far so good, but I don't seem to be able to copy those formats using the PasteSpecial command.

In short: cells A3 to M3 should have the same formatting as N3, A4 to M4 the same as N4, and so on.

VBA included below, thanks in advance!

```<code>Sub VoorwaardelijkeOpmaak()
'
' VoorwaardelijkeOpmaak Macro
'
' Sneltoets: Ctrl+Shift+Z
'
If ActiveSheet.Name <> "gedetailleerde meetstaat" Then
    MsgBox "Deze macro kan alleen in het werkblad 'gedetailleerde meetstaat' worden toegepast"
Else
Dim rg As Range
Dim cond1 As FormatCondition, cond2 As FormatCondition, cond3 As FormatCondition, cond4 As FormatCondition, cond5 As FormatCondition
Set rg = Range("N3", Range("N3").End(xlDown))

'clear any existing conditional formatting
rg.FormatConditions.Delete

'define the rule for each conditional format
Set cond1 = rg.FormatConditions.Add(xlCellValue, xlEqual, "1")
Set cond2 = rg.FormatConditions.Add(xlCellValue, xlEqual, "2")
Set cond3 = rg.FormatConditions.Add(xlCellValue, xlEqual, "3")
Set cond4 = rg.FormatConditions.Add(xlCellValue, xlEqual, "4")
Set cond5 = rg.FormatConditions.Add(xlCellValue, xlEqual, "5")

'define the format applied for each conditional format
With cond1
.Font.Color = RGB(0, 0, 0)
.Font.Bold = True
End With

With cond2
.Font.Color = RGB(128, 0, 0)
.Font.Bold = True
End With

With cond3
.Font.Color = RGB(255, 0, 0)
.Font.Bold = True
End With

With cond4
.Font.Color = RGB(0, 176, 80)
.Font.Bold = True
End With

With cond5
.Font.Color = RGB(31, 73, 125)
.Font.Bold = True
End With

Range("N3", Range("N3").End(xlDown)).Select
Selection.Copy
Range("A3:M3", Range("A3:M3").End(xlDown)).Select
Selection.PasteSpecial (xlPasteFormats)

End If

End Sub
</code>```

答:
Your code works fine for me (even if column N has a diff number of rows than A-M).

Have you tried clearing all conditional formats on the sheet before running it?

Title: Excel VBA copy cell formatting to range

Body:
I am creating a macro using conditional formatting. Purpose of the macro is to change the formatting (cell color and text font (bold/italic/...) and size) of cells in columns A to M, depending on the value of column M.

I defined 5 conditions and changed the conditional formatting of the cells of column M, so far so good, but I don't seem to be able to copy those formats using the PasteSpecial command.

In short: cells A3 to M3 should have the same formatting as N3, A4 to M4 the same as N4, and so on.

VBA included below, thanks in advance!

Sub VoorwaardelijkeOpmaak()
'
' VoorwaardelijkeOpmaak Macro
'
' Sneltoets: Ctrl+Shift+Z
'
If ActiveSheet.Name <> "gedetailleerde meetstaat" Then
    MsgBox "Deze macro kan alleen in het werkblad 'gedetailleerde meetstaat' worden toegepast"
Else
Dim rg As Range
Dim cond1 As FormatCondition, cond2 As FormatCondition, cond3 As FormatCondition, cond4 As FormatCondition, cond5 As FormatCondition
Set rg = Range("N3", Range("N3").End(xlDown))

'clear any existing conditional formatting
rg.FormatConditions.Delete

'define the rule for each conditional format
Set cond1 = rg.FormatConditions.Add(xlCellValue, xlEqual, "1")
Set cond2 = rg.FormatConditions.Add(xlCellValue, xlEqual, "2")
Set cond3 = rg.FormatConditions.Add(xlCellValue, xlEqual, "3")
Set cond4 = rg.FormatConditions.Add(xlCellValue, xlEqual, "4")
Set cond5 = rg.FormatConditions.Add(xlCellValue, xlEqual, "5")

'define the format applied for each conditional format
With cond1
.Font.Color = RGB(0, 0, 0)
.Font.Bold = True
End With

With cond2
.Font.Color = RGB(128, 0, 0)
.Font.Bold = True
End With

With cond3
.Font.Color = RGB(255, 0, 0)
.Font.Bold = True
End With

With cond4
.Font.Color = RGB(0, 176, 80)
.Font.Bold = True
End With

With cond5
.Font.Color = RGB(31, 73, 125)
.Font.Bold = True
End With

Range("N3", Range("N3").End(xlDown)).Select
Selection.Copy
Range("A3:M3", Range("A3:M3").End(xlDown)).Select
Selection.PasteSpecial (xlPasteFormats)

End If

End Sub


问:
React native - exposed method
I am implementing custom component for React Native using Android. I would like to implement an function that will be executable from React native. I have found out that there is an @ReactMethod annotation, but it is taken into consideration by React only when I use it in a class that extends:

ReactContextBaseJavaModule

But my needs are different. I need to execute a function on my component. I was trying to expose function by @ReactNative annotation in my class that extends:

ViewGroupManager

but this function is not visible for react at all. Is there any possibility to get access to the ViewGroupManager object from ReactContextBaseJavaModule object? If not than what is the most convenient way to expose function from native component to ReactNative?

here is my ReactContextBaseJavaModule implementation:

```<code> public class VidyoModule extends ReactContextBaseJavaModule {

    public VidyoModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Override
    public String getName() {
        return "RNTVideoManager";
    }

    @ReactMethod
    public void showToast(){
        Toast.makeText(getCurrentActivity(), "Test", Toast.LENGTH_SHORT).show();
    }

    @ReactMethod
    public void connectToRoom(){

    }
}
</code>```

I am able to execute both showToast and connectToRoom functions from react.

Here is an implementation of ViewGroupManager:

```<code>public class VidyoComponentManager extends ViewGroupManager<VidyoView> {
    private static final String COMPONENT_NAME = "RNTVideo";

    public VidyoComponentManager(){
    }

    @Override
    public String getName() {
        return COMPONENT_NAME;
    }

    @Override
    protected VidyoView createViewInstance(ThemedReactContext reactContext) {
        return new VidyoView(reactContext);
    }

    @ReactMethod
    public void connectToRoom(){

    }
}
</code>```

My ReactPackage looks like this:

```<code>public class VidyoPackage implements ReactPackage {

    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        List<NativeModule> modules = new ArrayList<>();
        VidyoModule module = new VidyoModule(reactContext);
        modules.add(module);
        return modules;
    }

    @Override
    public List<Class<? extends JavaScriptModule>> createJSModules() {
        return Collections.emptyList();
    }

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Collections.<ViewManager>singletonList(
                new VidyoComponentManager()
        );
    }
}
</code>```

and in this case function connectToRoom is not visible for ReactNative. What shouldI do here? Should I user commands?

```<code>public Map<String, Integer> getCommandsMap() {
    return MapBuilder.<String, Integer>builder()
            .put("connectToRoom", 1)
            .build();
}
</code>```

答:
Solution has been found. To make functions from ViewManager(android side) visible to React Native we need to implement getCommandsMap, than iterate through commands and "registrate" them as available functions on React side

```<code>const commands = NativeModules.UIManager.RNTVideo.Commands;

Object.keys(commands).forEach(command => {
  NativeModules.RNTVideoManager[command] = (handle, ...rawArgs) => {
    const args = rawArgs.map(arg => {
      if (typeof arg === 'function') {
        callbackMap.set(nextCallbackId, arg);
        return nextCallbackId++;
      }
      return arg;
    });
    NativeModules.UIManager.dispatchViewManagerCommand(handle, commands[command], args);
  };
});
</code>```

If there is any better solution please tell me about it :)

Title: React native - exposed method

Body:
I am implementing custom component for React Native using Android. I would like to implement an function that will be executable from React native. I have found out that there is an @ReactMethod annotation, but it is taken into consideration by React only when I use it in a class that extends:

ReactContextBaseJavaModule

But my needs are different. I need to execute a function on my component. I was trying to expose function by @ReactNative annotation in my class that extends:

ViewGroupManager

but this function is not visible for react at all. Is there any possibility to get access to the ViewGroupManager object from ReactContextBaseJavaModule object? If not than what is the most convenient way to expose function from native component to ReactNative?

here is my ReactContextBaseJavaModule implementation:

 public class VidyoModule extends ReactContextBaseJavaModule {

    public VidyoModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Override
    public String getName() {
        return "RNTVideoManager";
    }

    @ReactMethod
    public void showToast(){
        Toast.makeText(getCurrentActivity(), "Test", Toast.LENGTH_SHORT).show();
    }

    @ReactMethod
    public void connectToRoom(){

    }
}

I am able to execute both showToast and connectToRoom functions from react.

Here is an implementation of ViewGroupManager:

public class VidyoComponentManager extends ViewGroupManager<VidyoView> {
    private static final String COMPONENT_NAME = "RNTVideo";

    public VidyoComponentManager(){
    }

    @Override
    public String getName() {
        return COMPONENT_NAME;
    }

    @Override
    protected VidyoView createViewInstance(ThemedReactContext reactContext) {
        return new VidyoView(reactContext);
    }

    @ReactMethod
    public void connectToRoom(){

    }
}

My ReactPackage looks like this:

public class VidyoPackage implements ReactPackage {

    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        List<NativeModule> modules = new ArrayList<>();
        VidyoModule module = new VidyoModule(reactContext);
        modules.add(module);
        return modules;
    }

    @Override
    public List<Class<? extends JavaScriptModule>> createJSModules() {
        return Collections.emptyList();
    }

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Collections.<ViewManager>singletonList(
                new VidyoComponentManager()
        );
    }
}

and in this case function connectToRoom is not visible for ReactNative. What shouldI do here? Should I user commands?

public Map<String, Integer> getCommandsMap() {
    return MapBuilder.<String, Integer>builder()
            .put("connectToRoom", 1)
            .build();
}

Body:
Solution has been found. To make functions from ViewManager(android side) visible to React Native we need to implement getCommandsMap, than iterate through commands and "registrate" them as available functions on React side

const commands = NativeModules.UIManager.RNTVideo.Commands;

Object.keys(commands).forEach(command => {
  NativeModules.RNTVideoManager[command] = (handle, ...rawArgs) => {
    const args = rawArgs.map(arg => {
      if (typeof arg === 'function') {
        callbackMap.set(nextCallbackId, arg);
        return nextCallbackId++;
      }
      return arg;
    });
    NativeModules.UIManager.dispatchViewManagerCommand(handle, commands[command], args);
  };
});

If there is any better solution please tell me about it :)