问:
Issues with Registering PSRepository and Installing VMWare PowerCLI Module
My Setup: Windows 10.17134, PowerShell 5.1.17134.407

When trying to Register a new PSRepository using the Code below….

```<code>Register-PSRepository -Name "PSGallery" –SourceLocation "https://www.powershellgallery.com/api/v2/" -InstallationPolicy Trusted
</code>```

….it gives me the following error:

FullyQualifiedErrorId : UseDefaultParameterSetOnRegisterPSRepository,Register-PSRepository

I am not able to install the VMWare PowerCLI Module with this command:

```<code>Save-module -Name vmware.powercli -path c:\temp
</code>```

….it gives me this error:

FullyQualifiedErrorId : NoMatchFoundForCriteria,Microsoft.PowerShell.PackageManagement.Cmdlets.SavePackage

答:
Here are the results of a days googling

I'm running

Register-PSRepository
    -Name "PSGallery"
    –SourceLocation "https://www.powershellgallery.com/api/v2/"
    -InstallationPolicy Trusted

(multiline for clarity)

and I kept getting

Register-PSRepository : Use 'Register-PSRepository -Default' to
  register the PSGallery repository. At line:1 char:1
  + Register-PSRepository -Name "PSGallery" –SourceLocation "https://www. ...
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  + CategoryInfo          : InvalidArgument: (PSGallery:String) [Register-PSRepository], ArgumentException
  + FullyQualifiedErrorId : UseDefaultParameterSetOnRegisterPSRepository,Register-PSRepository

I assumed this was to do with proxy settings so I tried all of the various methods of setting the proxy in powershell to no avail.

Finally I ran

Get-PSRepository

and discovered that the repository was already registered, it was just untrusted

So I ran

Set-PSRepository -Name PSGallery -InstallationPolicy Trusted

The original reason I had for doIng this is because when I run

Install-PackageProvider -Name NuGet -Force -Scope CurrentUser

I get

Install-PackageProvider : No match was found for the specified search
  criteria for the provider 'NuGet'. The package provider requires
  'PackageManagement' and 'Provider' tags. Please check if the specified
  package has the tags. At line:1 char:1
  + Install-PackageProvider -Name NuGet -Force -Scope CurrentUser
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  + CategoryInfo          : InvalidArgument: (Microsoft.PowerShel\u2026tallPackageProvider:InstallPackageProvider)
  [Install-PackageProvider], Exception
  + FullyQualifiedErrorId : NoMatchFoundForProvider,Microsoft.PowerShell.PackageManagement.Cmdlets.InstallPackageProvider

Unfortunately, making the repository trusted did no help with my issue

... and the original reason for doing this was so I could run

Install-Module -Name SqlServer -Force -Verbose -Scope CurrentUser

Which was failing (sorry no error message, it was so long ago)

After all my fiddling however, this statement now works without error.

Not sure if it was all the proxy config, or making NuGet trusted or both

Body:
My Setup: Windows 10.17134, PowerShell 5.1.17134.407

When trying to Register a new PSRepository using the Code below….

Register-PSRepository -Name "PSGallery" –SourceLocation "https://www.powershellgallery.com/api/v2/" -InstallationPolicy Trusted

….it gives me the following error:

FullyQualifiedErrorId : UseDefaultParameterSetOnRegisterPSRepository,Register-PSRepository

I am not able to install the VMWare PowerCLI Module with this command:

Save-module -Name vmware.powercli -path c:\temp

….it gives me this error:

FullyQualifiedErrorId : NoMatchFoundForCriteria,Microsoft.PowerShell.PackageManagement.Cmdlets.SavePackage


来源: stackexchange

问:
How to find the car speed on iPhone?
I want to find the car speed on my iPhone when driving so what should I use and how?
Core Motion or Core Location? Is there any documentation or sample code?</p>

答:
Hey - You'll want core location for this.

There is a really good tutorial here - http://www.vellios.com/2010/08/16/core-location-gps-tutorial/ that I followed once. There is a whole series but this one shows you how to calculate the position and speed of your device. There is a sample project to download too. Hope this helps!

ContentLicense: CC BY-SA 3.0

Title: How to find the car speed on iPhone?


问:
How to use telnet in a script?
I need to connect in a system where I have to SSH first then telnet. Then I can start executing some command.
I am struggling about the telnet part. Can you tell me how I can make it please? Is there another alternative than spawn please? Thank you

```<code>#!/bin/bash
cat command.sh | sshpass -p 'passowrd' ssh -q -o StrictHostKeyChecking=no root@pc1;
</code>```

Then my command.sh

```<code>#!/bin/bash
spawn telnet pc_modem
expect "login:"
send "root"
expect "Password:"
send "youyou"

cliclient GetMonitoringData;
</code>```

答:
I find out the answer and works perfectly :</p>

```<code>/bin/expect <<<'spawn telnet pc_modem
expect "login:"
send "root\r"
expect "Password: ";
send "youyou\r"

send "yourcommand1\r"
send "yourcommand2\r"

expect eof
'
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to use telnet in a script?

Body:
I need to connect in a system where I have to SSH first then telnet. Then I can start executing some command.
I am struggling about the telnet part. Can you tell me how I can make it please? Is there another alternative than spawn please? Thank you

#!/bin/bash
cat command.sh | sshpass -p 'passowrd' ssh -q -o StrictHostKeyChecking=no root@pc1;

Then my command.sh

#!/bin/bash
spawn telnet pc_modem
expect "login:"
send "root"
expect "Password:"
send "youyou"

cliclient GetMonitoringData;

Body:
I find out the answer and works perfectly :

/bin/expect <<<'spawn telnet pc_modem
expect "login:"
send "root\r"
expect "Password: ";
send "youyou\r"

send "yourcommand1\r"
send "yourcommand2\r"

expect eof
'


问:
The error "only length-1 arrays can be converted to Python scalars" when trying to multiply matrix elements within a loop?
The function alpha_j should return a 3x3 matrix. The input A, is a block diagonal matrix and a is a scalar, (V_0 * 3 * chi)/(chi + 3). Rho is a random 3x1 matrix.

I am trying to create this 3x3 matrix by multiplying rho, the scalar alpha, and the matrix A together.

```<code>def alpha_j(a, A):
    alph = np.array([[0,0,0],[0,0,0],[0,0,0]],complex)
    rho = np.random.rand(3,1)
    for i in range(0, 2):
        for j in range(0, 2):
            alph[i][j] = (rho[i] * a * A[i][j])
    return alph

chi = 10 + 1j
V_0 = (0.05)**3
alpha = (V_0 * 3 * chi)/(chi + 3)
A = np.matlib.identity(3)

test = alpha_j(alpha, A)
print(test)
</code>```

I keep getting thrown the error "only length-1 arrays can be converted to Python scalars." I don't understand what is wrong. pls help :/

答:
Your indexing seems to be incorrect. You're using [i][j] when you need to use [i,j] for numpy arrays.

>> A = np.matlib.identity(3)
>> A
matrix([[1., 0., 0.],
        [0., 1., 0.],
        [0., 0., 1.]])

>> A[0][0]
matrix([[1., 0., 0.]])
>> A[0,0]
1.0
```

Thus, you're getting a row vector when you're expecting a scalar.

I should mention that a Google search on your error message turned up TypeError: only length-1 arrays can be converted to Python scalars while plot showing , which was helpful.

It's also good practice to print(type(suspect_thing)) or set breakpoints and use the debugger to inspect variables as you go. That can bubble these problems up right where you can see them. I, for example, copied your code into my editor and ran it, noting the line number where things went wrong. I was then able to see which variables needed checking out.

Body:
The function alpha_j should return a 3x3 matrix. The input A, is a block diagonal matrix and a is a scalar, (V_0 * 3 * chi)/(chi + 3). Rho is a random 3x1 matrix.

I am trying to create this 3x3 matrix by multiplying rho, the scalar alpha, and the matrix A together.

def alpha_j(a, A):
    alph = np.array([[0,0,0],[0,0,0],[0,0,0]],complex)
    rho = np.random.rand(3,1)
    for i in range(0, 2):
        for j in range(0, 2):
            alph[i][j] = (rho[i] * a * A[i][j])
    return alph

chi = 10 + 1j
V_0 = (0.05)**3
alpha = (V_0 * 3 * chi)/(chi + 3)
A = np.matlib.identity(3)

test = alpha_j(alpha, A)
print(test)

I keep getting thrown the error "only length-1 arrays can be converted to Python scalars." I don't understand what is wrong. pls help :/

Body:
Your indexing seems to be incorrect. You're using [i][j] when you need to use [i,j] for numpy arrays.

>> A = np.matlib.identity(3)
>> A
matrix([[1., 0., 0.],
        [0., 1., 0.],
        [0., 0., 1.]])

>> A[0][0]
matrix([[1., 0., 0.]])
>> A[0,0]
1.0

Thus, you're getting a row vector when you're expecting a scalar.

I should mention that a Google search on your error message turned up TypeError: only length-1 arrays can be converted to Python scalars while plot showing , which was helpful.

It's also good practice to print(type(suspect_thing)) or set breakpoints and use the debugger to inspect variables as you go. That can bubble these problems up right where you can see them. I, for example, copied your code into my editor and ran it, noting the line number where things went wrong. I was then able to see which variables needed checking out.


问:
How can stdin / stdout of unrelated & previously running processes be accessed?
Given two programs Program1.c and Program2.c, which are both executed separately as their own unrelated programs/processes:

Program1 knows the PID of Program2, and vise versa.

What C code (not shell commands) must both programs use to link their stdin/stdout to the other's stdout/stdin?

答: It's not possible (at least as far as I know). The memory for stdin and stdout is deallocated as soon as the program ends.


问:
how to get a valid response from a php web service on GWT
I'm trying to get data from a php web service (that I've put in my localhost - tested and works fine) in the client side of my GWT application.

I've tried to use the following package com.google.gwt.http.client.* it looks like the code works fine but the response is always 0, it's highly likely to be a corss problem but I still can't figure how to solve it even though I've tried to use requestBuilder.setHeader(..);

here's the code I'm working on:

```<code>    String url = "http://localhost/geoTrackerTest.php?id=15";
    RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));

    requestBuilder.setHeader("Access-Control-Allow-Origin", "http://localhost");
    requestBuilder.setHeader("Access-Control-Allow-Methods", "POST, GET, UPDATE, OPTIONS");
    requestBuilder.setHeader("Access-Control-Allow-Headers", "x-http-method-override");

    try {
        Request request = requestBuilder.sendRequest(null, new RequestCallback() {
          public void onError(Request request, Throwable exception) {
             GWT.log("Error: "+exception.getMessage());
          }

          public void onResponseReceived(Request request, Response response) {

            if (200 == response.getStatusCode()) {
                GWT.log("response: "+response.getText());
            } else {
                GWT.log("response code: "+response.getStatusCode());
            }

          }
      });
    } catch (RequestException e) {
      GWT.log("Request Exception: "+e.getMessage());
    }
</code>```

I'm still getting 0 as a response.

答:
You will need to set the header in response from server side (not from the GWT client side), then you can make Cross Site Requests from GWT RequestBuilder. Something like this on server side:

```<code>Response.setHeader("Access-Control-Allow-Origin","http://localhost");
</code>```

If you only need to send GET requests, you can use JSONP (http://www.gwtproject.org/javadoc/latest/com/google/gwt/jsonp/client/JsonpRequestBuilder.html) instead to send cross domain requests, without headers setting on server side.

Body:
I'm trying to get data from a php web service (that I've put in my localhost - tested and works fine) in the client side of my GWT application.

I've tried to use the following package com.google.gwt.http.client.* it looks like the code works fine but the response is always 0, it's highly likely to be a corss problem but I still can't figure how to solve it even though I've tried to use requestBuilder.setHeader(..);

here's the code I'm working on:

    String url = "http://localhost/geoTrackerTest.php?id=15";
    RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));

    requestBuilder.setHeader("Access-Control-Allow-Origin", "http://localhost");
    requestBuilder.setHeader("Access-Control-Allow-Methods", "POST, GET, UPDATE, OPTIONS");
    requestBuilder.setHeader("Access-Control-Allow-Headers", "x-http-method-override");

    try {
        Request request = requestBuilder.sendRequest(null, new RequestCallback() {
          public void onError(Request request, Throwable exception) {
             GWT.log("Error: "+exception.getMessage());
          }

          public void onResponseReceived(Request request, Response response) {

            if (200 == response.getStatusCode()) {
                GWT.log("response: "+response.getText());
            } else {
                GWT.log("response code: "+response.getStatusCode());
            }

          }
      });
    } catch (RequestException e) {
      GWT.log("Request Exception: "+e.getMessage());
    }

I'm still getting 0 as a response.

Body:
You will need to set the header in response from server side (not from the GWT client side), then you can make Cross Site Requests from GWT RequestBuilder. Something like this on server side:

Response.setHeader("Access-Control-Allow-Origin","http://localhost");

If you only need to send GET requests, you can use JSONP (http://www.gwtproject.org/javadoc/latest/com/google/gwt/jsonp/client/JsonpRequestBuilder.html) instead to send cross domain requests, without headers setting on server side.


问:
Problems with stem - can't stem correctly, and with identify in R using plot
I'm trying to use the stem function to create a stem and leaf plot, but as far as I know it isn't working good, and I don't know why.

I'm doing something like this:

```<code>d= c(60,85,72,59,37,75,93,7,98,63,41,90,5,17,97)

stem(d,scale=1)
</code>```

And I'm getting stem like this:

```<code>  0 | 577
  2 | 7
  4 | 19
  6 | 0325
  8 | 50378
</code>```

As far as I know there isn't any 27 value in d, or two times 7 value...

It's working weirdly and incorrect, and I don't know why. Additionally, I know that there should be one more column with numbers of observation, and my stem doesn't have it...

答:
The data is being collapsed into groups of 20, not 10. You can see that the stem portion goes up in 2s, so all data are collapsed into groups represented in the stem steps.

If you lengthen the plot with scale, e.g. stem(d, scale = 2) this becomes obvious, and the diagram looks more obviously correct. You can see that what looks like a '27' in your plot above, is actually the 37.

```<code>  0 | 57
  1 | 7
  2 |
  3 | 7
  4 | 1
  5 | 9
  6 | 03
  7 | 25
  8 | 5
  9 | 0378
</code>```

Body:
I'm trying to use the stem function to create a stem and leaf plot, but as far as I know it isn't working good, and I don't know why.

I'm doing something like this:

d= c(60,85,72,59,37,75,93,7,98,63,41,90,5,17,97)

stem(d,scale=1)

And I'm getting stem like this:

  0 | 577
  2 | 7
  4 | 19
  6 | 0325
  8 | 50378

As far as I know there isn't any 27 value in d, or two times 7 value...

It's working weirdly and incorrect, and I don't know why. Additionally, I know that there should be one more column with numbers of observation, and my stem doesn't have it...

Body:
The data is being collapsed into groups of 20, not 10. You can see that the stem portion goes up in 2s, so all data are collapsed into groups represented in the stem steps.

If you lengthen the plot with scale, e.g. stem(d, scale = 2) this becomes obvious, and the diagram looks more obviously correct. You can see that what looks like a '27' in your plot above, is actually the 37.

  0 | 57
  1 | 7
  2 |
  3 | 7
  4 | 1
  5 | 9
  6 | 03
  7 | 25
  8 | 5
  9 | 0378


问:
Java Meta Annotations at Runtime
I have a java meta annotation as such

```<code>@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.ANNOTATION_TYPE })
public @interface Qualifier {
}
</code>```

I then have another annotation:

```<code>@Qualifier
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.TYPE })
public @interface LeafEntity {
   String name() default "";
}
</code>```

At runtime I can extract the LeafEntity annotation using

```<code>getClass().getAnnotation(LeafEntity.class);
</code>```

However, I would like to know if it is possible to access anything about the Qualifier? I mean what is the purpose of annotations on annotations if you can't access anything about them?

I have tried all of the following:

```<code>getClass().getAnnotation(Qualifier.class);
getClass().getAnnotation(LeafEntity.class).getClass().getAnnotation(Qualifier.class);
getClass().getAnnotation(LeafEntity.class) instanceof Qualifier.class;
</code>```

If someone knows how to access the Qualifier annotation I would appreciate an example..

The reason this is important is that I have a base annotation called Qualifier. I would like to allow my users to define any annotation they like simply applying the Qualifier annotation to it. Then I would scan the class for any annotation that was annotated by the Qualifier annotation. But that's impossible if I can't access or identify Qualifier annotations.

Thanks in Advance.

答:
Couldn't you give Qualifier a value with a default? This way you'll be able to extract it.</p>

```<code>public @interface Qualifier {
    boolean value default true;
}
</code>```

Title: Java Meta Annotations at Runtime

Body:
I have a java meta annotation as such

@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.ANNOTATION_TYPE })
public @interface Qualifier {
}

I then have another annotation:

@Qualifier
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.TYPE })
public @interface LeafEntity {
   String name() default "";
}

At runtime I can extract the LeafEntity annotation using

getClass().getAnnotation(LeafEntity.class);

However, I would like to know if it is possible to access anything about the Qualifier? I mean what is the purpose of annotations on annotations if you can't access anything about them?

I have tried all of the following:

getClass().getAnnotation(Qualifier.class);
getClass().getAnnotation(LeafEntity.class).getClass().getAnnotation(Qualifier.class);
getClass().getAnnotation(LeafEntity.class) instanceof Qualifier.class;

If someone knows how to access the Qualifier annotation I would appreciate an example..

The reason this is important is that I have a base annotation called Qualifier. I would like to allow my users to define any annotation they like simply applying the Qualifier annotation to it. Then I would scan the class for any annotation that was annotated by the Qualifier annotation. But that's impossible if I can't access or identify Qualifier annotations.

Thanks in Advance.

Body:
Couldn't you give Qualifier a value with a default? This way you'll be able to extract it.

public @interface Qualifier {
    boolean value default true;
}


问:
Pyomo and dynamic objective function creation
I want to iteratively add to a Pyomo objective function based upon rows in a pandas dataframe.  I've created variables based upon the size of the dataframe:

model.A = Var(range(0,len(arc_decvars)), initialize=0,within=Integers,bounds=(0,5))

where arc_decvars is a list in the same order as the corresponding pandas dataframe series.

What I would like to do is create an objective function like this, but without having to specify the indices explicitly in the code:

model.ObjFcn = ( df.coefficient[0] * model.A[0] * ( 1- df.coefficient[0] * model.A[0]) ) + ( df.coefficient[1] * model.A[1] * ( 1- df.coefficient[1] * model.A[1]) +...+ ( df.coefficient[999] * model.A[999] * ( 1- df.coefficient[999] * model.A[999]) )

Any idea on how to do this?

---- Followup:

I am adding a series of constraints like this, one for each node:

```<code>def NodeA(model):
    k = sum(
        model.ArcVar[i] * node_arc_matrix[i,0]
        for i in model.ArcVar
            )
    return k ==  2*model.NodeVar[1]
model.NodeAConstraint=Constraint(rule=NodeA)
</code>```

Where the 0-index in node_arc_matrix refers to the column corresponding to Node_A.  Instead of creating a constriant for each node manually can I create constraints across both i (arcs) and j (nodes)?

答:
Try using Python list comprehension into the summation formulation.

Considering df.coefficient and model.A have arc_decvars as the domain and that arc_decvars is in a Pyomo Set, you can create your objective function this way:

```<code>model.ObjFcn = sum(
    df.coefficient[i] * model.A[i] * ( 1- df.coefficient[i] * model.A[i])
    for i in model.arc_devcars
)
</code>```

Body:
I want to iteratively add to a Pyomo objective function based upon rows in a pandas dataframe.  I've created variables based upon the size of the dataframe:

model.A = Var(range(0,len(arc_decvars)), initialize=0,within=Integers,bounds=(0,5))

where arc_decvars is a list in the same order as the corresponding pandas dataframe series.

What I would like to do is create an objective function like this, but without having to specify the indices explicitly in the code:

model.ObjFcn = ( df.coefficient[0] * model.A[0] * ( 1- df.coefficient[0] * model.A[0]) ) + ( df.coefficient[1] * model.A[1] * ( 1- df.coefficient[1] * model.A[1]) +...+ ( df.coefficient[999] * model.A[999] * ( 1- df.coefficient[999] * model.A[999]) )

Any idea on how to do this?

---- Followup:

I am adding a series of constraints like this, one for each node:

def NodeA(model):
    k = sum(
        model.ArcVar[i] * node_arc_matrix[i,0]
        for i in model.ArcVar
            )
    return k ==  2*model.NodeVar[1]
model.NodeAConstraint=Constraint(rule=NodeA)

Where the 0-index in node_arc_matrix refers to the column corresponding to Node_A.  Instead of creating a constriant for each node manually can I create constraints across both i (arcs) and j (nodes)?

Body:
Try using Python list comprehension into the summation formulation.

Considering df.coefficient and model.A have arc_decvars as the domain and that arc_decvars is in a Pyomo Set, you can create your objective function this way:

model.ObjFcn = sum(
    df.coefficient[i] * model.A[i] * ( 1- df.coefficient[i] * model.A[i])
    for i in model.arc_devcars
)


问:
Using multiple TinyMCE editors on a single page
Using multiple textareas results in TinyMCE only using the last configuration, rather than applying the correct config to each textarea.

I've tried several answers from Stack Overflow. None of them solved the problem. Many answers are from previous versions of TinyMCE, but do not specify what version the answers are for -- which makes obsolete answers seem relevant when they're not. Most troubling is that the official documentation from TinyMCE 4 is also apparently wrong.

This is the "official" way to specify more than one selector:

```<code>    tinymce.init({

      selector: "#textarea1",

    });

</code>```

```<code>    tinymce.init({

      selector: "#textarea2",

    });

</code>```

The actual outcome is that TinyMCE only uses the last configuration ("#textarea2").

Other solutions that you find on Stack Overflow and elsewhere do not solve the problem (using "exact" mode, specifying "textareas", etc.). The official documentation for tinyMCE v4 also uses the above method, though it is clearly wrong.

You can see this in the docs for yourself at the following link: https://www.tiny.cloud/docs/general-configuration-guide/multiple-editors/

Since using more than one editor on a page is basic functionality, I don't understand how there are so many possible "right" answers to the same question (note: this question is specifically about tinyMCE version 4), and apparently no definitive simple, correct answer. There's no reason for it to be a question to spend hours answering in several different possible ways without a clear solution. We're not exactly sending humans to Mars, here...

Thanks in advance for help on this issue.

答:
That link you posted is to version 5 of tinymce, but changing the version to 4 and looking at the multiple config example:
https://www.tiny.cloud/docs-4x/general-configuration-guide/multiple-editors/

It runs fine for me in chrome on windows 10:
https://jsbin.com/rehamun/edit?html,output

Close the trial warnings, and then click each line, the first gets undo etc, the second gets rich edit, two separate configs

Example repeated here to please automated answer moderation...

```<code><!DOCTYPE html>
<html>
<head>
  <script src="https://cloud.tinymce.com/stable/tinymce.min.js"></script>
  <script type="text/javascript">
  tinymce.init({
    selector: '#myeditable-h1',
    inline: true,
    menubar: false,
    toolbar: 'undo redo'
  });
  </script>
  <script>
  tinymce.init({
    selector: '#myeditable-div',
    inline: true
  });
  </script>
</head>

<body>
  <form method="post">
    <h1 id="myeditable-h1">This Title Can Be Edited If You Click Here</h1>
  </form>

  <form method="post">
    <div id="myeditable-div">
      <p>This section of content can be edited. Click here to see how.</p>
    </div>
  </form>
</body>
</html>
</code>```

Body:
Using multiple textareas results in TinyMCE only using the last configuration, rather than applying the correct config to each textarea.

I've tried several answers from Stack Overflow. None of them solved the problem. Many answers are from previous versions of TinyMCE, but do not specify what version the answers are for -- which makes obsolete answers seem relevant when they're not. Most troubling is that the official documentation from TinyMCE 4 is also apparently wrong.

This is the "official" way to specify more than one selector:

    tinymce.init({

      selector: "#textarea1",

    });

    tinymce.init({

      selector: "#textarea2",

    });

The actual outcome is that TinyMCE only uses the last configuration ("#textarea2").

Other solutions that you find on Stack Overflow and elsewhere do not solve the problem (using "exact" mode, specifying "textareas", etc.). The official documentation for tinyMCE v4 also uses the above method, though it is clearly wrong.

You can see this in the docs for yourself at the following link: https://www.tiny.cloud/docs/general-configuration-guide/multiple-editors/

Since using more than one editor on a page is basic functionality, I don't understand how there are so many possible "right" answers to the same question (note: this question is specifically about tinyMCE version 4), and apparently no definitive simple, correct answer. There's no reason for it to be a question to spend hours answering in several different possible ways without a clear solution. We're not exactly sending humans to Mars, here...

Thanks in advance for help on this issue.

Body:
That link you posted is to version 5 of tinymce, but changing the version to 4 and looking at the multiple config example:
https://www.tiny.cloud/docs-4x/general-configuration-guide/multiple-editors/

It runs fine for me in chrome on windows 10:
https://jsbin.com/rehamun/edit?html,output

Close the trial warnings, and then click each line, the first gets undo etc, the second gets rich edit, two separate configs

Example repeated here to please automated answer moderation...

<!DOCTYPE html>
<html>
<head>
  <script src="https://cloud.tinymce.com/stable/tinymce.min.js"></script>
  <script type="text/javascript">
  tinymce.init({
    selector: '#myeditable-h1',
    inline: true,
    menubar: false,
    toolbar: 'undo redo'
  });
  </script>
  <script>
  tinymce.init({
    selector: '#myeditable-div',
    inline: true
  });
  </script>
</head>

<body>
  <form method="post">
    <h1 id="myeditable-h1">This Title Can Be Edited If You Click Here</h1>
  </form>

  <form method="post">
    <div id="myeditable-div">
      <p>This section of content can be edited. Click here to see how.</p>
    </div>
  </form>
</body>
</html>


问:
malloc(): corrupted top size
I am working on a program that decrypts some line of text in a file. First, another source code I created asks for shift and some text. Source code encrypts the text and writes it into a file.

Then, I try to decrypt the specified file using the below code -another source code. Name of the file is obtained. From file name, shift is obtained. Every character written inside the file is copied, shifted by the value of shift with the aid of the function caesar_decrypt -reversing caesar encrypt which I also have. However, given characters must be of ascii value between 32 and 127 to be transformed to another character of ascii value between 32 and 127.

I defined my modulo function encapsulating the remainder operator -modulo of positive numbers- and modulo of negative numbers. I also defined strip function which works the same as strip function in python does. Aside from spaces, it removes all literals. I also have getIn(), which is input() of python.

I tried to debug by printing and using gdb. No effective result. I have researched about this topic in stackoverflow. Found one entry. Answer did not address my specific issue.

NOTE: I copied the whole program since I thought you would need  the necessary detailed information.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
#include <fcntl.h>

/*GETIN FUNCTION*/
char* getIn()
{
    char *line = NULL, *tmp = NULL;
    size_t size = 0, index = 0;
    int ch = EOF;

    while (ch)
    {
        ch = getc(stdin);

        /* Check if we need to stop. */
        if (ch == EOF || ch == '\n')
        ch = 0;

        /* Check if we need to expand. */
        if (size <= index)
        {
            size += sizeof(char);
            tmp = realloc(line, size);
            if (!tmp)
            {
                free(line);
                line = NULL;
                break;
            }
        line = tmp;
        }

    /* Actually store the thing. */
    line[index++] = ch;
    }

    return line;
}
/*FUNCTION THAT CONVERTS TO NUMERIC CHARACTER, PRECURSOR OF DIGITS OF SHIFT*/
char make_numeric(char ch)
{
    if(ch<91 && ch>63) return ch-16;
    if(ch<123 && ch>95) return ch-48;
    if(ch<58 && ch>47) return ch;
    return ch+16;
}

 /*STRIP FUNCTION*/
char* strip(char* str,int length)
{
    char *start=str,*end=&str[length-1];

    while(*start>0 && *start<33 || *start==127) ++start;
    if(!*start) return start;

    while(*end>=0 && *end<33 || *end==127) --end;
    ++end;
    *end=0;

    return start;
}
/*DECRYPTOR FUNCTION*/
char *caesar_decrypt(char *message_to_decrypt, void *shift)
{
    int length=strlen(message_to_decrypt),i;
    char* decrypted_message;

    if(!message_to_decrypt) return NULL;

    if(!(decrypted_message=calloc(length+1,sizeof(char)))) return NULL;

    for(i=0;i<length;++i)
    {
    decrypted_message[i]=mod((message_to_decrypt[i]-33-*((int*)shift)),94)+33;
    }

return decrypted_message;
}

/*THE MAIN PROGRAM*/
int main()
{

int shift,len_chshift,init,len_filename,i=0;
char *chshift,*line=NULL,*decrypted_line,*stripped_line,chinit,chlen_chshift;
char *filename=NULL,*newfilename=NULL;
FILE *oldfile=NULL;
FILE *newfile=NULL;
size_t lenline,len=0;

printf("-9");
/*FILENAME*/
printf("Enter the file name: ");
/*printf("-8");*/
filename=getIn();
/*printf("-7");*/
if(!access(filename,F_OK))
{
    len_filename=strlen(filename);
    /*printf("-6");*/
    i=len_filename;
    while(filename[i]!='.') --i;
    chlen_chshift=filename[i-1];
    chlen_chshift=make_numeric(chlen_chshift);
    len_chshift=chlen_chshift-48;
    /*printf("-5");*/
    chshift=calloc(len_chshift+1,1);
    /*NEWFILENAME*/
    newfilename=calloc(i+1,1);
    /*printf("-4");*/
    strncpy(newfilename,filename,i);
    /*printf("-3");*/
    strcat(newfilename,"(decrypted).txt");
    /*printf("-2");*/
    chinit=make_numeric(filename[0]);
    init=chinit-48;
    /*SHIFT*/
    i=0;
    /*printf("-1");*/
    while(i!=len_chshift)
    {
        chshift[i]=make_numeric(filename[(i+1)*init]);
        ++i;
    }
    /*printf("0");*/
    shift=atoi(chshift);

    /*printf("1");*/
    if(!(oldfile=fopen(filename,"r")))
    {
        perror("Error");
        if(newfilename) free(newfilename);
        if(filename) free(filename);
        if(chshift) free(chshift);
        exit(1);
    }
    /*printf("2");*/

    if(!(newfile=fopen(newfilename,"+ab")))
    {
        perror("Error");
        if(newfilename) free(newfilename);
        if(filename) free(filename);
        if(chshift) free(chshift);
        fclose(oldfile);
        exit(1);
    }
    while ((lenline = getline(&line, &len, oldfile)) != -1)
    {
        stripped_line=strip(line,lenline);
        decrypted_line=caesar_decrypt(stripped_line, &shift);
        if(!decrypted_line)
        {
            printf("Could not allocate memory\n");
            if(newfilename) free(newfilename);
            if(filename) free(filename);
            if(chshift) free(chshift);
            exit(1);
        }

        fprintf(newfile,"%s\n",decrypted_line);

        if(decrypted_line) free(decrypted_line);
        decrypted_line=NULL;

        free(line);
        line=NULL;
        stripped_line=NULL;
        decrypted_line=NULL;
    }
    free(line);
    line=NULL;
}
else
{
    printf("Cannot access the file.");
    if(filename) free(filename);
    exit(0);
}

if(newfilename) free(newfilename);
if(filename) free(filename);
if(chshift) free(chshift);

fclose(oldfile);
fclose(newfile);
return 0;
}
</code>```

The program is required to create a file, context of which is the decrypted clone of the other file, name of which is provided in the beginning by the user. However, it throws, just before the first fopen:

```<code>malloc(): corrupted top size
Aborted (core dumped)
</code>```

When I uncomment every printf line, it gives the same error between the lines of getIn() and printf("-7");. When printfs are commented, I observe that filename holds the written value, which is returned by getIn(). Therefore, I do not think getIn() is the problem.

EDIT(1): I added 2 headers that were missing, but still raising the same error.

EDIT(2): I removed all unnecessary headers.

EDIT(3): Since I am requested, I will try to illuminate by an example: Suppose I have a file named

```<code>2/b*A".txt
</code>```

with two lines of code

```<code>%52
abcd
</code>```

I enter the file name into program.

1)The very last character before . is ", converted into number 2. We understand shift is a two digit number.

2)The first character is the initiator, which is 2 , is the number of characters we need to jump repeatedly. We will jump two characters twice since we have a shift number of two digits.

3)We have, now characters b and A, converted to 2 and 1 respectively. Our shift is 21. The very first character %(37) is shifted backwards to n(110) and so on, we need to create a new file with the content:

```<code>n~#
LMNO
</code>```

I appreciate any help. Thank you in advance. In addition, the variables I mentioned are any arbitrary characters between specific intervals. For details, check the source code,or I suggest you to work locally, since I provided with the whole program.

For ascii codes:
https://www.asciitable.com/

If you are interested in Caesar's cipher:
https://en.wikipedia.org/wiki/Caesar_cipher

答:
You have a buffer overflow in newfilename:

```<code>/* here you declare that the string pointed to by newfilename may contain `i`
   chars + zero-termination...*/
newfilename=calloc(i+1,1);

/* Here `i` is less than `strlen(filename)`, so only i characters from `filename`
   will be copied, that does NOT include the zero-termination
   (but it will be zero-terminated because the last byte in the buffer was
   already cleared by `calloc`) */
strncpy(newfilename,filename,i);

/* Here `newfilename` is full, and `strcat` will write outside buffer!! Whatever
   happens after this line is undefined behaviour */
strcat(newfilename,"(decrypted).txt");
</code>```

So you have to allocate enough space for newfilename:

```<code>newfilename = calloc (i + strlen("(decrypted).txt") + 1, 1);
</code>```

Title: malloc(): corrupted top size

Body:
I am working on a program that decrypts some line of text in a file. First, another source code I created asks for shift and some text. Source code encrypts the text and writes it into a file.

Then, I try to decrypt the specified file using the below code -another source code. Name of the file is obtained. From file name, shift is obtained. Every character written inside the file is copied, shifted by the value of shift with the aid of the function caesar_decrypt -reversing caesar encrypt which I also have. However, given characters must be of ascii value between 32 and 127 to be transformed to another character of ascii value between 32 and 127.

I defined my modulo function encapsulating the remainder operator -modulo of positive numbers- and modulo of negative numbers. I also defined strip function which works the same as strip function in python does. Aside from spaces, it removes all literals. I also have getIn(), which is input() of python.

I tried to debug by printing and using gdb. No effective result. I have researched about this topic in stackoverflow. Found one entry. Answer did not address my specific issue.

NOTE: I copied the whole program since I thought you would need  the necessary detailed information.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
#include <fcntl.h>

/*GETIN FUNCTION*/
char* getIn()
{
    char *line = NULL, *tmp = NULL;
    size_t size = 0, index = 0;
    int ch = EOF;

    while (ch)
    {
        ch = getc(stdin);

        /* Check if we need to stop. */
        if (ch == EOF || ch == '\n')
        ch = 0;

        /* Check if we need to expand. */
        if (size <= index)
        {
            size += sizeof(char);
            tmp = realloc(line, size);
            if (!tmp)
            {
                free(line);
                line = NULL;
                break;
            }
        line = tmp;
        }

    /* Actually store the thing. */
    line[index++] = ch;
    }

    return line;
}
/*FUNCTION THAT CONVERTS TO NUMERIC CHARACTER, PRECURSOR OF DIGITS OF SHIFT*/
char make_numeric(char ch)
{
    if(ch<91 && ch>63) return ch-16;
    if(ch<123 && ch>95) return ch-48;
    if(ch<58 && ch>47) return ch;
    return ch+16;
}

 /*STRIP FUNCTION*/
char* strip(char* str,int length)
{
    char *start=str,*end=&str[length-1];

    while(*start>0 && *start<33 || *start==127) ++start;
    if(!*start) return start;

    while(*end>=0 && *end<33 || *end==127) --end;
    ++end;
    *end=0;

    return start;
}
/*DECRYPTOR FUNCTION*/
char *caesar_decrypt(char *message_to_decrypt, void *shift)
{
    int length=strlen(message_to_decrypt),i;
    char* decrypted_message;

    if(!message_to_decrypt) return NULL;

    if(!(decrypted_message=calloc(length+1,sizeof(char)))) return NULL;

    for(i=0;i<length;++i)
    {
    decrypted_message[i]=mod((message_to_decrypt[i]-33-*((int*)shift)),94)+33;
    }

return decrypted_message;
}

/*THE MAIN PROGRAM*/
int main()
{

int shift,len_chshift,init,len_filename,i=0;
char *chshift,*line=NULL,*decrypted_line,*stripped_line,chinit,chlen_chshift;
char *filename=NULL,*newfilename=NULL;
FILE *oldfile=NULL;
FILE *newfile=NULL;
size_t lenline,len=0;

printf("-9");
/*FILENAME*/
printf("Enter the file name: ");
/*printf("-8");*/
filename=getIn();
/*printf("-7");*/
if(!access(filename,F_OK))
{
    len_filename=strlen(filename);
    /*printf("-6");*/
    i=len_filename;
    while(filename[i]!='.') --i;
    chlen_chshift=filename[i-1];
    chlen_chshift=make_numeric(chlen_chshift);
    len_chshift=chlen_chshift-48;
    /*printf("-5");*/
    chshift=calloc(len_chshift+1,1);
    /*NEWFILENAME*/
    newfilename=calloc(i+1,1);
    /*printf("-4");*/
    strncpy(newfilename,filename,i);
    /*printf("-3");*/
    strcat(newfilename,"(decrypted).txt");
    /*printf("-2");*/
    chinit=make_numeric(filename[0]);
    init=chinit-48;
    /*SHIFT*/
    i=0;
    /*printf("-1");*/
    while(i!=len_chshift)
    {
        chshift[i]=make_numeric(filename[(i+1)*init]);
        ++i;
    }
    /*printf("0");*/
    shift=atoi(chshift);

    /*printf("1");*/
    if(!(oldfile=fopen(filename,"r")))
    {
        perror("Error");
        if(newfilename) free(newfilename);
        if(filename) free(filename);
        if(chshift) free(chshift);
        exit(1);
    }
    /*printf("2");*/

    if(!(newfile=fopen(newfilename,"+ab")))
    {
        perror("Error");
        if(newfilename) free(newfilename);
        if(filename) free(filename);
        if(chshift) free(chshift);
        fclose(oldfile);
        exit(1);
    }
    while ((lenline = getline(&line, &len, oldfile)) != -1)
    {
        stripped_line=strip(line,lenline);
        decrypted_line=caesar_decrypt(stripped_line, &shift);
        if(!decrypted_line)
        {
            printf("Could not allocate memory\n");
            if(newfilename) free(newfilename);
            if(filename) free(filename);
            if(chshift) free(chshift);
            exit(1);
        }

        fprintf(newfile,"%s\n",decrypted_line);

        if(decrypted_line) free(decrypted_line);
        decrypted_line=NULL;

        free(line);
        line=NULL;
        stripped_line=NULL;
        decrypted_line=NULL;
    }
    free(line);
    line=NULL;
}
else
{
    printf("Cannot access the file.");
    if(filename) free(filename);
    exit(0);
}

if(newfilename) free(newfilename);
if(filename) free(filename);
if(chshift) free(chshift);

fclose(oldfile);
fclose(newfile);
return 0;
}

The program is required to create a file, context of which is the decrypted clone of the other file, name of which is provided in the beginning by the user. However, it throws, just before the first fopen:

malloc(): corrupted top size
Aborted (core dumped)

When I uncomment every printf line, it gives the same error between the lines of getIn() and printf("-7");. When printfs are commented, I observe that filename holds the written value, which is returned by getIn(). Therefore, I do not think getIn() is the problem.

EDIT(1): I added 2 headers that were missing, but still raising the same error.

EDIT(2): I removed all unnecessary headers.

EDIT(3): Since I am requested, I will try to illuminate by an example: Suppose I have a file named

2/b*A".txt

with two lines of code

%52
abcd

I enter the file name into program.

1)The very last character before . is ", converted into number 2. We understand shift is a two digit number.

2)The first character is the initiator, which is 2 , is the number of characters we need to jump repeatedly. We will jump two characters twice since we have a shift number of two digits.

3)We have, now characters b and A, converted to 2 and 1 respectively. Our shift is 21. The very first character %(37) is shifted backwards to n(110) and so on, we need to create a new file with the content:

n~#
LMNO

I appreciate any help. Thank you in advance. In addition, the variables I mentioned are any arbitrary characters between specific intervals. For details, check the source code,or I suggest you to work locally, since I provided with the whole program.

For ascii codes:
https://www.asciitable.com/

If you are interested in Caesar's cipher:
https://en.wikipedia.org/wiki/Caesar_cipher

Body:
You have a buffer overflow in newfilename:

/* here you declare that the string pointed to by newfilename may contain `i`
   chars + zero-termination...*/
newfilename=calloc(i+1,1);

/* Here `i` is less than `strlen(filename)`, so only i characters from `filename`
   will be copied, that does NOT include the zero-termination
   (but it will be zero-terminated because the last byte in the buffer was
   already cleared by `calloc`) */
strncpy(newfilename,filename,i);

/* Here `newfilename` is full, and `strcat` will write outside buffer!! Whatever
   happens after this line is undefined behaviour */
strcat(newfilename,"(decrypted).txt");

So you have to allocate enough space for newfilename:

newfilename = calloc (i + strlen("(decrypted).txt") + 1, 1);


问:
How to fix problem with Roboto font load in Google Chrome?
I'm trying to render my website and I takes a lot of time in Google Chrome, but in Mozilla works perfectly. The console shows the error

```<code>GET file://fonts.googleapis.com/css?family=RobotoDraft:300,400,500,700,400italic net::ERR_FILE_NOT_FOUND
</code>```

I tried to import directy in the CSS and in the HTML this:

```<code>@import url(http://fonts.googleapis.com/css?family=Roboto:400,400italic,500,500italic,700,700italic,900,900italic,300italic,300,100italic,100);

body {
   font-family: 'Roboto', sans-serif;
}
</code>```

But it still doesn't work, it throws the same error.

Here is the full HTML code of my website:

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"> </meta>
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"></meta>
        <title>Sign in</title>
        <style>
            @import url('https://fonts.googleapis.com/css?family=Roboto&display=swap');
        </style>
        <!-- JQuery Mobile -->
        <link rel="stylesheet" href="./jquery/jquery.mobile-1.4.5.css"></link>
        <!-- Project CSS -->
        <link rel="stylesheet" href="./css/style.css"></link>
        <!-- NativeDroid2 CSS -->
        <link rel="stylesheet" href="./bower_components/nativeDroid2/css/nativedroid2.css"></link>
    </head>
    <body>
        <div data-role="main" class="ui-content">
            <form method="post">
                <div class="img-container">
                    <img src="img/logo_gemott.png" alt="No es pot carregar la imatge" height="110" width="350">
                </div>

                <div>
                    <h2>Registre</h2>
                    <hr>
                    <label for="mail"><b>Correu electrònic</b></label>
                    <input type="text" placeholder="Introduir correu electrònic..." name="mail" required>
                    <label for="psw"><b>Contrasenya</b></label>
                    <input type="password" placeholder="Introduir contrasenya..." name="psw" required>
                    <div class="center-text">
                        <p>Al registrar-te, acceptes els <a href=#>termes de privacitat</a></p>
                        <p>Ja estàs <a href="login.html">registrat?</a></p>
                    </div>
                </div>

                <a href="javascript:registry()" class="ui-btn ui-btn-raised clr-primary">Registrar-me</a>

                <div class="img-container" id="uab-logo">
                    <img src="img/UAB.jpg" alt="No es pot carrerar la imatge" height="150" witdh="150">
                </div>
            </form>
        </div>
        <!-- JQuery -->
        <script type="text/javascript" src="jquery/jquery-2.2.4.js"></script>
        <!-- Project Js -->
        <script type="text/javascript" src="js/app.js"></script>
        <!-- JQuery Mobile -->
        <script type="text/javascript" src="jquery/jquery.mobile-1.4.5.min.js"></script>
        <!-- NativeDroid2 Js -->
        <script type="text/javascript" src="bower_components/Waves/dist/waves.js"></script>
        <script type="text/javascript" src="bower_components/nativeDroid2/nd2settings.js"></script>
        <script type="text/javascript" src="bower_components/nativeDroid2/js/nativedroid2.js"></script>
    </body>
</html>
</code>```

答:
Add this:

```<code><link rel="preload" href="https://fonts.gstatic.com/s/roboto/v19/KFOmCnqEu92Fr1Mu7GxKOzY.woff2" as="font" crossorigin="anonymous"/>
<link rel="preload" href="https://fonts.gstatic.com/s/roboto/v19/KFOmCnqEu92Fr1Mu4mxK.woff2" as="font" crossorigin="anonymous"/>
</code>```

to your  section.
And this:

```<code>@font-face {
  font-family: "Roboto";
  src: url("https://fonts.gstatic.com/s/roboto/v19/KFOmCnqEu92Fr1Mu7GxKOzY.woff2") format("woff2"), url("https://fonts.gstatic.com/s/roboto/v19/KFOmCnqEu92Fr1Mu4mxK.woff2") format("woff2")
  font-weight: 400;
  font-display: swap;
  font-style: Roboto; }
</code>```

add to your css.
And add the css file with this method:

```<code><link rel="preload" href="css/style.css" as="style" onload="this.rel='stylesheet'"><noscript><link rel="stylesheet" href="css/style.css"></noscript>
</code>```

Body:
I'm trying to render my website and I takes a lot of time in Google Chrome, but in Mozilla works perfectly. The console shows the error

GET file://fonts.googleapis.com/css?family=RobotoDraft:300,400,500,700,400italic net::ERR_FILE_NOT_FOUND

I tried to import directy in the CSS and in the HTML this:

@import url(http://fonts.googleapis.com/css?family=Roboto:400,400italic,500,500italic,700,700italic,900,900italic,300italic,300,100italic,100);

body {
   font-family: 'Roboto', sans-serif;
}

But it still doesn't work, it throws the same error.

Here is the full HTML code of my website:

<!DOCTYPE html>

        <meta charset="utf-8"> </meta>
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"></meta>
        <title>Sign in</title>

        <link rel="stylesheet" href="./jquery/jquery.mobile-1.4.5.css"></link>

        <link rel="stylesheet" href="./css/style.css"></link>

        <link rel="stylesheet" href="./bower_components/nativeDroid2/css/nativedroid2.css"></link>

            <form method="post">

Registre

                    Correu electrònic
                    <input type="text" placeholder="Introduir correu electrònic..." name="mail" required>
                    Contrasenya
                    <input type="password" placeholder="Introduir contrasenya..." name="psw" required>

Al registrar-te, acceptes els termes de privacitat

Ja estàs registrat?

                Registrar-me

            </form>

Body:
Add this:

<link rel="preload" href="https://fonts.gstatic.com/s/roboto/v19/KFOmCnqEu92Fr1Mu7GxKOzY.woff2" as="font" crossorigin="anonymous"/>
<link rel="preload" href="https://fonts.gstatic.com/s/roboto/v19/KFOmCnqEu92Fr1Mu4mxK.woff2" as="font" crossorigin="anonymous"/>

to your <head> section.
And this:

@font-face {
  font-family: "Roboto";
  src: url("https://fonts.gstatic.com/s/roboto/v19/KFOmCnqEu92Fr1Mu7GxKOzY.woff2") format("woff2"), url("https://fonts.gstatic.com/s/roboto/v19/KFOmCnqEu92Fr1Mu4mxK.woff2") format("woff2")
  font-weight: 400;
  font-display: swap;
  font-style: Roboto; }

add to your css.
And add the css file with this method:

<link rel="preload" href="css/style.css" as="style" onload="this.rel='stylesheet'"><noscript><link rel="stylesheet" href="css/style.css"></noscript>


问:
Print out a selected number of a string problem
The exercise says "Make a function with two parameters a string (s) and an integer(n). The function then will return the first n characters. That's what I did, but I'm getting a compiler error "[Warning] passing arg 1 of `symbolse' makes pointer from integer without a cast". I've tried to do some changes, to override this error but then I don't get  the result I want or the program crashes.

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

 void symbolse(char s[50],int n){
    int i;
    for(i=0;i<n;i++)
    printf("%c ",s[i]);

 }

main(){
   int m;
   char a[50];
   printf("Give integer: ");
   scanf("%d",&m);
   printf("Give string: ");
   a[50]=getchar();
   symbolse(a[50],m);

   system("pause");

 }
</code>```

Ex. The user gives m=3 and a[50]=House . The program should print Hou .

答:
You can not use a[50]=getchar(); because getchar only takes a single char.

Use scanf("%s",a); inplace of a[50]=getchar();

Body:
The exercise says "Make a function with two parameters a string (s) and an integer(n). The function then will return the first n characters. That's what I did, but I'm getting a compiler error "[Warning] passing arg 1 of `symbolse' makes pointer from integer without a cast". I've tried to do some changes, to override this error but then I don't get  the result I want or the program crashes.

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

 void symbolse(char s[50],int n){
    int i;
    for(i=0;i<n;i++)
    printf("%c ",s[i]);

 }

main(){
   int m;
   char a[50];
   printf("Give integer: ");
   scanf("%d",&m);
   printf("Give string: ");
   a[50]=getchar();
   symbolse(a[50],m);

   system("pause");

 }

Ex. The user gives m=3 and a[50]=House . The program should print Hou .


问:
how to change 'return' button in keyboard?
How can I change the return button to some other native buttons ios has?

Now it shows the grey return button and instead I want it to be blue with some other text like the example below:

EXAMPLE:

答:
Update 2019: Using version react-native 0.57 the accepted answer is no longer valid as "Go" is not one of the accepted values, use "go" without capitalisation instead

Actual react-native 0.57 contract states the following enums:

```<code>    /**
     * enum('default', 'go', 'google', 'join', 'next', 'route', 'search', 'send', 'yahoo', 'done', 'emergency-call')
     * Determines how the return key should look.
     */
    returnKeyType?: ReturnKeyTypeOptions;
</code>```

Body:
Update 2019: Using version react-native 0.57 the accepted answer is no longer valid as "Go" is not one of the accepted values, use "go" without capitalisation instead

Actual react-native 0.57 contract states the following enums:

    /**
     * enum('default', 'go', 'google', 'join', 'next', 'route', 'search', 'send', 'yahoo', 'done', 'emergency-call')
     * Determines how the return key should look.
     */
    returnKeyType?: ReturnKeyTypeOptions;


问:
Hot to fix Android Studio's documentation lookup "Documentation not found"
I cant seem to get flutter based documentation on android studio when i select quick documentation (control Q)

I have tried reinstalling android studio and have tried re-applying the documentation in the SDK manager.

I expect there to be some documentation of what methods are in the class

答:
Try installing this Extention

Install Android Studio
Android Studio offers a complete, integrated IDE experience for Flutter.

Android Studio, version 3.0 or later
Alternatively, you can also use IntelliJ:

IntelliJ IDEA Community, version 2017.1 or later
IntelliJ IDEA Ultimate, version 2017.1 or later
Install the Flutter and Dart plugins
To install these:

Start Android Studio.

Open plugin preferences  (Preferences > Plugins on macOS, File >
Settings > Plugins on Windows & Linux).

Select Browse repositories, select the Flutter plugin and click
Install.

Click Yes when prompted to install the Dart plugin.

Click Restart when prompted. Ne


问:
How to wait 'return' until 'dispatch' finish
[React JS]How to wait 'return' until 'dispatch' finish in action creator?
I don't know how handle this ;(

i made some code. this is a part of action creator. But it return before dispatch finish. i want to dispatch finish before 'return'. help me please

```<code>export const Hello = param=> dispatch => {
  return postApi('/hello', param)
    .then(async res => {
      await dispatch(goHello(res));
       return true;
})
</code>```

答:
By default, there really is no need to call return after dispatching an action. But if you'd like, you could use the getState() method to check that your action was processed before returning. getState() is the second argument of the redux-thunk function you are returning in your action-creator.

```<code>export const Hello = (param) => async (dispatch, getState) => {
   postApi("/hello", param)
     .then((res) => {
         await dispatch(goHello(res))
    })
     .catch((err) => {
         console.log(err.response.data)
    })

   //check if reducer was updated
    const value = getState().keyOfReducerInStore <-- returns the state of your reducer, you can follow this up with whatever value you want to check
    if(value){
        return true
    }
}
</code>```

Body:
[React JS]How to wait 'return' until 'dispatch' finish in action creator?
I don't know how handle this ;(

i made some code. this is a part of action creator. But it return before dispatch finish. i want to dispatch finish before 'return'. help me please

export const Hello = param=> dispatch => {
  return postApi('/hello', param)
    .then(async res => {
      await dispatch(goHello(res));
       return true;
})

Body:
By default, there really is no need to call return after dispatching an action. But if you'd like, you could use the getState() method to check that your action was processed before returning. getState() is the second argument of the redux-thunk function you are returning in your action-creator.

export const Hello = (param) => async (dispatch, getState) => {
   postApi("/hello", param)
     .then((res) => {
         await dispatch(goHello(res))
    })
     .catch((err) => {
         console.log(err.response.data)
    })

   //check if reducer was updated
    const value = getState().keyOfReducerInStore <-- returns the state of your reducer, you can follow this up with whatever value you want to check
    if(value){
        return true
    }
}


问:
HTTP Triggering Cloud Function with Cloud Scheduler
I have a problem with a job in the Cloud Scheduler for my cloud function. I created the job with next parameters:

Target: HTTP

URL: my trigger url for cloud function

HTTP method: POST

Body:

```<code>{
 "expertsender": {
  "apiKey": "ExprtSender API key",
  "apiAddress": "ExpertSender APIv2 address",
  "date": "YYYY-MM-DD",
  "entities": [
     {
        "entity": "Messages"
     },
     {
        "entity": "Activities",
        "types":[
           "Subscriptions"
        ]
     }
  ]
 },
 "bq": {
         "project_id": "YOUR GCP PROJECT",
         "dataset_id": "YOUR DATASET NAME",
         "location": "US"
       }
}
</code>```

The real values has been changed in this body.

When I run this job I got an error. The reason is caused by processing body from POST request.

However, when I take this body and use it as Triggering event in Testing I don't get any errors. So I think, that problem in body representation for my job but I havn't any idea how fix it. I'll be very happy for any idea.

答:
Disclaimer:
I have tried to solve the same issue using NodeJS and I'm able to get a solution

I understand that this is an old question. But I felt like its worth to answer this question as I have spent almost 2 hours figuring out the answer for this issue.

Scenario - 1: Trigger the Cloud Function via Cloud Scheduler

Function fails to read the message in request body.

Scenario - 2: Trigger the Cloud Function via Test tab in Cloud Function interface

Function call always executes fine with no errors.

What did I find?

When the GCF routine is executed via Cloud Scheduler, it sends the header content-type as application/octet-stream. This makes express js unable to parse the data in request body when Cloud scheduler POSTs the data.

But when the exact same request body is used to test the function via the Cloud Function interface, everything works fine because the Testing feature on the interface sends the header content-type as application/json and express js is able to read the request body and parses the data as a JSON object.

Solution

I had to manually parse the request body as JSON (explicitly using if condition based on the content-type header) to get hold of data in the request body.

```<code>/**
 * Responds to any HTTP request.
 *
 * @param {!express:Request} req HTTP request context.
 * @param {!express:Response} res HTTP response context.
 */
exports.helloWorld = (req, res) => {
  let message = req.query.message || req.body.message || 'Hello World!';

  console.log('Headers from request: ' + JSON.stringify(req.headers));

  let parsedBody;

  if(req.header('content-type') === 'application/json') {
    console.log('request header content-type is application/json and auto parsing the req body as json');
    parsedBody = req.body;
  } else {
    console.log('request header content-type is NOT application/json and MANUALLY parsing the req body as json');
    parsedBody = JSON.parse(req.body);
  }

  console.log('Message from parsed json body is:' + parsedBody.message);

  res.status(200).send(message);
};

</code>```

It is truly a feature issue which Google has to address and hopefully Google fixes it soon.

Cloud Scheduler - Content Type header issue

Body:
I have a problem with a job in the Cloud Scheduler for my cloud function. I created the job with next parameters:

Target: HTTP

URL: my trigger url for cloud function

HTTP method: POST

Body:

{
 "expertsender": {
  "apiKey": "ExprtSender API key",
  "apiAddress": "ExpertSender APIv2 address",
  "date": "YYYY-MM-DD",
  "entities": [
     {
        "entity": "Messages"
     },
     {
        "entity": "Activities",
        "types":[
           "Subscriptions"
        ]
     }
  ]
 },
 "bq": {
         "project_id": "YOUR GCP PROJECT",
         "dataset_id": "YOUR DATASET NAME",
         "location": "US"
       }
}

The real values has been changed in this body.

When I run this job I got an error. The reason is caused by processing body from POST request.

However, when I take this body and use it as Triggering event in Testing I don't get any errors. So I think, that problem in body representation for my job but I havn't any idea how fix it. I'll be very happy for any idea.

Body:
Disclaimer:
I have tried to solve the same issue using NodeJS and I'm able to get a solution

I understand that this is an old question. But I felt like its worth to answer this question as I have spent almost 2 hours figuring out the answer for this issue.

Scenario - 1: Trigger the Cloud Function via Cloud Scheduler

Function fails to read the message in request body.

Scenario - 2: Trigger the Cloud Function via Test tab in Cloud Function interface

Function call always executes fine with no errors.

What did I find?

When the GCF routine is executed via Cloud Scheduler, it sends the header content-type as application/octet-stream. This makes express js unable to parse the data in request body when Cloud scheduler POSTs the data.

But when the exact same request body is used to test the function via the Cloud Function interface, everything works fine because the Testing feature on the interface sends the header content-type as application/json and express js is able to read the request body and parses the data as a JSON object.

Solution

I had to manually parse the request body as JSON (explicitly using if condition based on the content-type header) to get hold of data in the request body.

/**
 * Responds to any HTTP request.
 *
 * @param {!express:Request} req HTTP request context.
 * @param {!express:Response} res HTTP response context.
 */
exports.helloWorld = (req, res) => {
  let message = req.query.message || req.body.message || 'Hello World!';

  console.log('Headers from request: ' + JSON.stringify(req.headers));

  let parsedBody;

  if(req.header('content-type') === 'application/json') {
    console.log('request header content-type is application/json and auto parsing the req body as json');
    parsedBody = req.body;
  } else {
    console.log('request header content-type is NOT application/json and MANUALLY parsing the req body as json');
    parsedBody = JSON.parse(req.body);
  }

  console.log('Message from parsed json body is:' + parsedBody.message);

  res.status(200).send(message);
};

It is truly a feature issue which Google has to address and hopefully Google fixes it soon.

Cloud Scheduler - Content Type header issue


问:
python 7z password with special characters
I'm trying to unzip a file with 7z.exe and the password contains special characters on it

EX. &)kra932(lk0¤23

By executing the following command:

```<code>subprocess.call(['7z.exe', 'x', '-y', '-ps^&)kratsaslkd932(lkasdf930¤23', 'file.zip'])
</code>```

7z.exe launches fine but it says the password is wrong.

This is a file I created and it is driving me nuts.

If I run the command on the windows command line it runs fine

```<code>7z.exe x -y -ps^&)kratsaslkd932(lkasdf930¤23 file.zip
</code>```

How can I make python escape the & character?

@Wim  the issue occurs & on the password, because when i execute

```<code>7z.exe x -y -ps^&)kratsaslkd932(lkasdf930¤23 file.zip
</code>```

it says invalid command ')kratsaslkd932(lkasdf930¤23'
im using python 2.76, cant upgrade to 3.x due to company tools that only run on 2.76

答:
Try to put double quotes between your password, otherwise the cmd parser would any parse special character as is instead of taking it as part of the password.

For example,
7z.exe x -y -ps^&)kratsaslkd932(lkasdf930¤23 file.zip won't work.

But 7z.exe x -y -p"s^&)kratsaslkd932(lkasdf930¤23" file.zip would definitely work.

Body:
I'm trying to unzip a file with 7z.exe and the password contains special characters on it

EX. &)kra932(lk0¤23

By executing the following command:

subprocess.call(['7z.exe', 'x', '-y', '-ps^&)kratsaslkd932(lkasdf930¤23', 'file.zip'])

7z.exe launches fine but it says the password is wrong.

This is a file I created and it is driving me nuts.

If I run the command on the windows command line it runs fine

7z.exe x -y -ps^&)kratsaslkd932(lkasdf930¤23 file.zip

How can I make python escape the & character?

@Wim  the issue occurs & on the password, because when i execute

7z.exe x -y -ps^&)kratsaslkd932(lkasdf930¤23 file.zip

it says invalid command ')kratsaslkd932(lkasdf930¤23'
im using python 2.76, cant upgrade to 3.x due to company tools that only run on 2.76


问:
Cannot access 'variable_name' before initialization
When using reactive variables by declaring them using the $: syntax, you get the following error.

Cannot access 'variable_name' before initialization

Here is the code:

App.svelte

Band Members

{#each bandmembers as member}

{member}

{/each}

Members with "A" in their names

{#each namesWithA as member}

{member}

{/each}

```
<p><strong>data.js</strong></p>
<pre class="lang-js prettyprint-override"><code>export const ledzep = ["Jimmy Page", "John Bonham", "Robert Plant", "John Paul Jones"]
export const redhotchilis = ["Anthony Kiedis", "Flea", "Chad Smith", "Josh Klinghoffer"]
</code>```

答:
When you assign variables using $: you cannot assign them as part of other variables declared using let, const, or var.

When you do assignments using $:, you can only use them in other variables assigned using $:. In the code posted above, you need to change the following lines:

```<code>let namesWithA = bandmembers.filter(d => {
            if (d.indexOf('a') > 0) {
                return true;
            }
        else {
            return false
        }
    })
</code>```

to the following:

```<code>$: namesWithA = bandmembers.filter(d => {
            if (d.indexOf('a') > 0) {
                return true;
            }
        else {
            return false
        }
    })
</code>```

It took me a while to figure this out and just wanted to share this with any other Svelte newbies that are starting out in this new technology.

Body:
When using reactive variables by declaring them using the $: syntax, you get the following error.

Cannot access 'variable_name' before initialization

Here is the code:

App.svelte

Band Members

{#each bandmembers as member}

{member}

{/each}

Members with "A" in their names

{#each namesWithA as member}

{member}

{/each}

data.js

export const ledzep = ["Jimmy Page", "John Bonham", "Robert Plant", "John Paul Jones"]
export const redhotchilis = ["Anthony Kiedis", "Flea", "Chad Smith", "Josh Klinghoffer"]

Body:
When you assign variables using $: you cannot assign them as part of other variables declared using let, const, or var.

When you do assignments using $:, you can only use them in other variables assigned using $:. In the code posted above, you need to change the following lines:

let namesWithA = bandmembers.filter(d => {
            if (d.indexOf('a') > 0) {
                return true;
            }
        else {
            return false
        }
    })

to the following:

$: namesWithA = bandmembers.filter(d => {
            if (d.indexOf('a') > 0) {
                return true;
            }
        else {
            return false
        }
    })

It took me a while to figure this out and just wanted to share this with any other Svelte newbies that are starting out in this new technology.


问:
How to do a one-time load for 4 billion records from MySQL to SQL Server
We have a need to do the initial data copy on a table that has 4+ billion records to target SQL Server (2014) from source MySQL (5.5).  The table in question is pretty wide with 55 columns, however none of them are LOB. I'm looking for options for copying this data in the most efficient way possible.

We've tried loading via Attunity Replicate (which has worked wonderfully for tables not this large) but if the initial data copy with Attunity Replicate fails then it starts over from scratch ... losing whatever time was spent copying the data.  With patching and the possibility of this table taking 3+ months to load Attunity wasn't the solution.

We've also tried smaller batch loads with a linked server.  This is working but doesn't seem efficient at all.

Once the data is copied we will be using Attunity Replicate to handle CDC.

答:
One of the most efficient way to load huge data is to read them by chunks.

I have answered many similar question for SQLite, Oracle, Db2 and MySQL. You can refer to one of them for to get more information on how to do that using SSIS:

Reading Huge volume of data from Sqlite to SQL Server fails at pre-execute (SQLite)

SSIS failing to save packages and reboots Visual Studio (Oracle)

Optimizing SSIS package for millions of rows with Order by / sort in SQL command and Merge Join (MySQL)

Getting top n to n rows from db2 (DB2)

On the other hand there are many other suggestions such as drop indexes in destination table and recreate them after insert, Create needed indexes on source table, use fast-load option to insert data ...


问:
Caesar Cipher - spaces and other characters
I have created a Caesar Cipher code below but I want the returned string to include spaces and other characters.  I've tried regex but this does not seem to solve the problem or maybe i'm not using it right, I'm not too sure.

Any help appreciated.  Thanks!

function caesarCipher(str, n) {
  let newStr = '';
  let alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('')
  let regex = /[a-z]/

  for (let i = 0; i < str.length; i++) {
    if (str[i].match(regex) === false) {
      newStr += str[i]
      continue;
    }
    let currentIndex = alphabet.indexOf(str[i]);
    let newIndex = currentIndex + n;
    newStr += alphabet[newIndex];
  }
  return newStr
}

console.log(caesarCipher('ebiil tloia!', 3)) //should return hello world! but returns hellocworldc```

答:
Firstly, you need to pass the shift (3) to the function. Secondly, since there are no spaces in alphabet, you need to add a test:

function caesarCipher(str, n) {
  let newStr = '';
  let alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('')
  let regex = /[a-z]/

  for (let i = 0; i < str.length; i++) {
    if (str[i].match(regex) === false) {
      newStr += str[i]
    }
    let currentIndex = alphabet.indexOf(str[i]);
    if (!(currentIndex + 1)) {
      newStr += " ";
    } else {
      let newIndex = currentIndex + n;
      newStr += alphabet[newIndex];
    }
  }
  return newStr
}

console.log(caesarCipher('ebiil tloia!', 3)) //should return hello world! but returns hellocworldc```


问:
Is DOMParser().parseFromString() worth using?
https://developer.mozilla.org/en-US/docs/Web/API/DOMParser#DOMParser_HTML_extension

It looks like the DOMParser uses innerHTML to add stringified elements to the DOM.  What's the advantage of using it?

I have compared the difference between using DOMParser().parseFromString() and using element.innerHTML below.  Am I overlooking something?

Using DOMParser

```<code>const main = document.querySelector('main');

const newNodeString = '<body><h2>I made it on the page</h2><p>What should I do now?</p><select name="whichAdventure"><option>Chill for a sec.</option><option>Explore all that this page has to offer...</option><option>Run while you still can!</option></select><p>Thanks for your advice!</p></body>';

// Works as expected
let newNode = new DOMParser().parseFromString(newNodeString, 'text/html');
let div = document.createElement('div');

console.log('%cArray.from: ', 'border-bottom: 1px solid yellow;font-weight:1000;');
Array.from(newNode.body.children).forEach((node, index, array) => {
    div.appendChild(node);
    console.log('length:', array.length, 'index: ', index, 'node: ', node);
})
main.appendChild(div);
</code>```

Using innerHTML

```<code>const main = document.querySelector('main');

const newNodeString = '<h2>I made it on the page</h2><p>What should I do now?</p><select name="whichAdventure"><option>Chill for a sec.</option><option>Explore all that this page has to offer...</option><option>Run while you still can!</option></select><p>Thanks for your advice!</p>';

// Works as expected
let div = document.createElement('div');
div.innerHTML = newNodeString;

main.appendChild(div);
</code>```

I expect that DOMParser().parseFromString() provides some additional functionality that I'm unaware of.

答:
Well, for one thing, DOMParser can parse XML files. It also validates that the XML is well formed and produces meaningful errors if not. More to the point, it is using the right tool for the right job.

I've used it in the past to take an uploaded XML file and produce HTML using a predefined XSLT style sheet, without getting a server involved.

Obviously, if all you're doing is appending the string to an existing DOM, and innerHTML (or outerHTML) works for you, continue using it.

Body:
https://developer.mozilla.org/en-US/docs/Web/API/DOMParser#DOMParser_HTML_extension

It looks like the DOMParser uses innerHTML to add stringified elements to the DOM.  What's the advantage of using it?

I have compared the difference between using DOMParser().parseFromString() and using element.innerHTML below.  Am I overlooking something?

Using DOMParser

const main = document.querySelector('main');

const newNodeString = '
I made it on the page

What should I do now?
<select name="whichAdventure"><option>Chill for a sec.</option><option>Explore all that this page has to offer...</option><option>Run while you still can!</option></select>
Thanks for your advice!
';

// Works as expected
let newNode = new DOMParser().parseFromString(newNodeString, 'text/html');
let div = document.createElement('div');

console.log('%cArray.from: ', 'border-bottom: 1px solid yellow;font-weight:1000;');
Array.from(newNode.body.children).forEach((node, index, array) => {
    div.appendChild(node);
    console.log('length:', array.length, 'index: ', index, 'node: ', node);
})
main.appendChild(div);

Using innerHTML

const main = document.querySelector('main');

const newNodeString = '
I made it on the page

What should I do now?
<select name="whichAdventure"><option>Chill for a sec.</option><option>Explore all that this page has to offer...</option><option>Run while you still can!</option></select>
Thanks for your advice!
';

// Works as expected
let div = document.createElement('div');
div.innerHTML = newNodeString;

main.appendChild(div);

I expect that DOMParser().parseFromString() provides some additional functionality that I'm unaware of.


问:
Can't connect to twilsoc
I am getting this bizarre twilsoc error when trying to connect to twilio through node and react. I cannot figure out how to fix this. This seems to be happening on the server side of my application. I have generated the token based on the instructions on the website.

```<code>index.js:1437 Error: Can't connect to twilsock
        at Upstream.send (upstream.js:245)
        at TwilsockClient.post (client.js:280)
        at network.js:176
        at Retrier.<anonymous> (network.js:114)
        at Retrier.emit (events.js:136)
        at Retrier.attempt (retrier.js:56)
        at retrier.js:111
</code>```

Here is on the front end

```<code>    componentDidMount() {
    fetch("http://localhost:3001/chat/token", {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded',
     'Access-Control-Allow-Origin': "*",
     'Access-Control-Allow-Headers': "*"
     },
      method: 'POST',
      body: `identity=${encodeURIComponent(this.props.username)}`
    })
      .then(res => res.json())
      .then(data => Chat.create(data.token))
      .then(this.setupChatClient)
      .catch(this.handleError);
  }
</code>```

here is the server

```<code>app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(pino);
app.use(cors());
const sendTokenResponse = (token, res) => {
  res.set('Content-Type', 'application/json');
  res.send(
    JSON.stringify({
      token: token.toJwt()
    })
  );
};

app.get('/api/greeting', (req, res) => {
  const name = req.query.name || 'World';
  res.setHeader('Content-Type', 'application/json');
  res.send(JSON.stringify({ greeting: `Hello ${name}!` }));
});

app.get('/chat/token', (req, res) => {
  const identity = req.query.identity;
  const token = chatToken(identity, config);
  sendTokenResponse(token, res);
});

app.post('/chat/token', (req, res) => {
  console.log('this is firing on the backend')
  const identity = req.query.identity;
  const token = new AccessToken('AC821b3924fcf9577a0eb017c4b21b----', "SK8c95cf6ba0e4a0ec5499d12ae4d----", "o4x7JC9xTEAsZC06SVsnfb2xZU9n----");
  const chatGrant = new ChatGrant({
  serviceSid:"ISdd3f2b55594f45038ac88d84b78e----" ,
});
  token.addGrant(chatGrant);
  token.identity = identity;
  sendTokenResponse(token, res);
});

app.get('/video/token', (req, res) => {
  const identity = req.query.identity;
  const room = req.query.room;
  const token = videoToken(identity, room, config);
  sendTokenResponse(token, res);
});

app.post('/video/token', (req, res) => {
  const identity = req.body.identity;
  const room = req.body.room;
  const token = videoToken(identity, room, config);
  sendTokenResponse(token, res);
});

app.listen(3001, () =>
  console.log('Express server is running on localhost:3001')
);
</code>```

答:
the latest versions of express are not using bodyparser.json any more, it's now a part of express, try using:

```<code> express(express.json())
</code>```

instead of

express(bodyParser.json())

Title: Can't connect to twilsoc

Body:
I am getting this bizarre twilsoc error when trying to connect to twilio through node and react. I cannot figure out how to fix this. This seems to be happening on the server side of my application. I have generated the token based on the instructions on the website.

index.js:1437 Error: Can't connect to twilsock
        at Upstream.send (upstream.js:245)
        at TwilsockClient.post (client.js:280)
        at network.js:176
        at Retrier.<anonymous> (network.js:114)
        at Retrier.emit (events.js:136)
        at Retrier.attempt (retrier.js:56)
        at retrier.js:111

Here is on the front end

    componentDidMount() {
    fetch("http://localhost:3001/chat/token", {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded',
     'Access-Control-Allow-Origin': "*",
     'Access-Control-Allow-Headers': "*"
     },
      method: 'POST',
      body: `identity=${encodeURIComponent(this.props.username)}`
    })
      .then(res => res.json())
      .then(data => Chat.create(data.token))
      .then(this.setupChatClient)
      .catch(this.handleError);
  }

here is the server

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(pino);
app.use(cors());
const sendTokenResponse = (token, res) => {
  res.set('Content-Type', 'application/json');
  res.send(
    JSON.stringify({
      token: token.toJwt()
    })
  );
};

app.get('/api/greeting', (req, res) => {
  const name = req.query.name || 'World';
  res.setHeader('Content-Type', 'application/json');
  res.send(JSON.stringify({ greeting: `Hello ${name}!` }));
});

app.get('/chat/token', (req, res) => {
  const identity = req.query.identity;
  const token = chatToken(identity, config);
  sendTokenResponse(token, res);
});

app.post('/chat/token', (req, res) => {
  console.log('this is firing on the backend')
  const identity = req.query.identity;
  const token = new AccessToken('AC821b3924fcf9577a0eb017c4b21b----', "SK8c95cf6ba0e4a0ec5499d12ae4d----", "o4x7JC9xTEAsZC06SVsnfb2xZU9n----");
  const chatGrant = new ChatGrant({
  serviceSid:"ISdd3f2b55594f45038ac88d84b78e----" ,
});
  token.addGrant(chatGrant);
  token.identity = identity;
  sendTokenResponse(token, res);
});

app.get('/video/token', (req, res) => {
  const identity = req.query.identity;
  const room = req.query.room;
  const token = videoToken(identity, room, config);
  sendTokenResponse(token, res);
});

app.post('/video/token', (req, res) => {
  const identity = req.body.identity;
  const room = req.body.room;
  const token = videoToken(identity, room, config);
  sendTokenResponse(token, res);
});

app.listen(3001, () =>
  console.log('Express server is running on localhost:3001')
);

Body:
the latest versions of express are not using bodyparser.json any more, it's now a part of express, try using:

 express(express.json())

instead of

express(bodyParser.json())


问:
Is OpenGL function loader needed?
On desktop OSes, OpenGL function loaders like GLEW, GLAD, etc. are used to load functions at runtime. But what about on Android? How are functions loaded? I've looked at a few apps and all of them seem to depend on EGL and GLES. But AFAIK EGL isn't a loading library, but an interface. Well, an interface to an interface as GLES is actually an interface.

This leads to another question: How come Android uses EGL when it is generally not used on desktops?

答:
Back when I used android a bit, you could either link to the GLES 2.0 library, or you could link to the GLES 3.0 library, so kinda as if they provide the function pointers for you. ish. If you used GLES3.0, but the phone you ran it on only supported 2.0, your app would not load. To work around this, I always linked to GLES 2.0, and wrote my own function loader using eglGetProcAddress to extract the GLES3.0 API if available. This is pretty much how function loaders on windows/linux work (using wglGetProcAddress or glxGetProcAddress).

GLES has always been a stripped down version of the full blown desktop GL. It has always targeted a smaller subset of the full blown API (removing all of the legacy cruft), which in turn simplifies the OpenGL driver code somewhat, which in turn should reduce memory usage and save a little bit of battery life. Basically it's just more suited to use on a low power system where battery life is a concern.

Title: Is OpenGL function loader needed?


答:
RegExp.test returns a boolean, String.match returns an array. This line:

```<code>if (str[i].match(regex) === false) {
</code>```

should be

```<code>if (regex.test(str[i]) === false) {
</code>```

This should catch any value that's not a lowercase letter (spaces, punctuation, etc) - If you want to encode uppercase too, add the i flag at the end of the regex: /[a-z]/i

Title: Caesar Cipher - spaces and other characters

Body:
I have created a Caesar Cipher code below but I want the returned string to include spaces and other characters.  I've tried regex but this does not seem to solve the problem or maybe i'm not using it right, I'm not too sure.

Any help appreciated.  Thanks!

function caesarCipher(str, n) {
  let newStr = '';
  let alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('')
  let regex = /[a-z]/

  for (let i = 0; i < str.length; i++) {
    if (str[i].match(regex) === false) {
      newStr += str[i]
      continue;
    }
    let currentIndex = alphabet.indexOf(str[i]);
    let newIndex = currentIndex + n;
    newStr += alphabet[newIndex];
  }
  return newStr
}

console.log(caesarCipher('ebiil tloia!', 3)) //should return hello world! but returns hellocworldc

Body:
RegExp.test returns a boolean, String.match returns an array. This line:

if (str[i].match(regex) === false) {

should be

if (regex.test(str[i]) === false) {

This should catch any value that's not a lowercase letter (spaces, punctuation, etc) - If you want to encode uppercase too, add the i flag at the end of the regex: /[a-z]/i


问:
cumulative sum by ID with lag
I want to create a cumulative sum by id. But, it should not sum the value that belongs to the row where is being calculated.

I've already tried with cumsum. However, I do not know how to add a statement which specifies to do not add the amount of the row where the sum is made. The result column I am looking for is the third column called: "sum".

For example, for id 1, the first row is sum=0, because should not add this row. But, for id 1 and row 2 sum=100 because the amount of id 1 previous to the row 2 was 100 and so on.

```<code>   id amount sum
1:  1    100   0
2:  1     20 100
3:  1    150 120
4:  2     60   0
5:  2    100  60
6:  1     30 270
7:  2     40 160
</code>```

This is what I've tried:

```<code>  df[,sum:=cumsum(amount),
      by ="id"]

  data: df <- data.table(id = c(1, 1, 1, 2, 2,1,2), amount = c(100, 20,
  150,60,100,30,40),sum=c(0,100,120,0,60,270,160) ,stringsAsFactors =
  FALSE)
</code>```

答:
You can do this without using lag:

```<code>> df %>%
      group_by(id) %>%
      mutate(sum = cumsum(amount) - amount)
# A tibble: 7 x 3
# Groups:   id [2]
     id amount   sum
  <dbl>  <dbl> <dbl>
#1    1    100     0
#2    1     20   100
#3    1    150   120
#4    2     60     0
#5    2    100    60
#6    1     30   270
#7    2     40   160
</code>```

Title: cumulative sum by ID with lag

Body:
I want to create a cumulative sum by id. But, it should not sum the value that belongs to the row where is being calculated.

I've already tried with cumsum. However, I do not know how to add a statement which specifies to do not add the amount of the row where the sum is made. The result column I am looking for is the third column called: "sum".

For example, for id 1, the first row is sum=0, because should not add this row. But, for id 1 and row 2 sum=100 because the amount of id 1 previous to the row 2 was 100 and so on.

   id amount sum
1:  1    100   0
2:  1     20 100
3:  1    150 120
4:  2     60   0
5:  2    100  60
6:  1     30 270
7:  2     40 160

This is what I've tried:

  df[,sum:=cumsum(amount),
      by ="id"]

  data: df <- data.table(id = c(1, 1, 1, 2, 2,1,2), amount = c(100, 20,
  150,60,100,30,40),sum=c(0,100,120,0,60,270,160) ,stringsAsFactors =
  FALSE)

Body:
You can do this without using lag:

> df %>%
      group_by(id) %>%
      mutate(sum = cumsum(amount) - amount)
# A tibble: 7 x 3
# Groups:   id [2]
     id amount   sum
  <dbl>  <dbl> <dbl>
#1    1    100     0
#2    1     20   100
#3    1    150   120
#4    2     60     0
#5    2    100    60
#6    1     30   270
#7    2     40   160


问:
Increase object quantity instead of creating a new object in array
First time working with a shopping cart component, I have my code structured like this..

```<code>let cartCount = document.getElementById("counter");
let isItemSelected = false;
let itemCount = 0;
let shoppingCart = [];
let selectedSize = "";
let displaySelectedSize = document.getElementById("selected");
let displayCart = document.getElementById("cart");

selectItem = () => {
  isItemSelected = true;
  selectedSize = event.srcElement.id;
  displaySelectedSize.innerHTML = `${selectedSize}`;
}

addItem = () => {
  if (isItemSelected === true) {

    const shopItem = {
      name: "Classic Tee",
      price: 75,
      size: `${selectedSize}`,
      quantity: 0
    }

    itemCount+= 1;
    cartCount.innerHTML = `( ${itemCount} )`;
    shopItem.quantity++
    shoppingCart.push(shopItem);
    console.log(shoppingCart);

    return itemSuccess();
  } else {
      return itemError();
  }
}
</code>```

What I basically need is for the shopItem.quantity to increase if I have multiple of the selected size.

At the moment I get this..

```<code>// Output
0: {name: "Classic Tee", price: 75, size: "small", quantity: 1}
1: {name: "Classic Tee", price: 75, size: "small", quantity: 1}

// Desired Output
0: {name: "Classic Tee", price: 75, size: "small", quantity: 2}
</code>```

I can see why my output is like that, it's creating a new object each time my addItem function is fired, but I would like to mutate my shopItem.quantity if there are duplicates...

How would I do that?

答:
You can give item time an identity attribute (I would not go by name, since it is possible you can have something with the same name and that would be bad) such as id and the you can search for it before adding something. For example, consider the following item:

```<code>const cartItem = {id: 1, name: "Classic Tee"}
</code>```

Then before adding the item, you could look for it in the cart:

```<code>const existingItem = shoppingCart.find((item) => {
  return cartItem.id === item.id;
});

if(existingItem) {
   existingItem.quantity++;
} else {
  // Push the item into the cart
  shoppingCart.push(cartItem);
}
</code>```

Body:
First time working with a shopping cart component, I have my code structured like this..

let cartCount = document.getElementById("counter");
let isItemSelected = false;
let itemCount = 0;
let shoppingCart = [];
let selectedSize = "";
let displaySelectedSize = document.getElementById("selected");
let displayCart = document.getElementById("cart");

selectItem = () => {
  isItemSelected = true;
  selectedSize = event.srcElement.id;
  displaySelectedSize.innerHTML = `${selectedSize}`;
}

addItem = () => {
  if (isItemSelected === true) {

    const shopItem = {
      name: "Classic Tee",
      price: 75,
      size: `${selectedSize}`,
      quantity: 0
    }

    itemCount+= 1;
    cartCount.innerHTML = `( ${itemCount} )`;
    shopItem.quantity++
    shoppingCart.push(shopItem);
    console.log(shoppingCart);

    return itemSuccess();
  } else {
      return itemError();
  }
}

What I basically need is for the shopItem.quantity to increase if I have multiple of the selected size.

At the moment I get this..

// Output
0: {name: "Classic Tee", price: 75, size: "small", quantity: 1}
1: {name: "Classic Tee", price: 75, size: "small", quantity: 1}

// Desired Output
0: {name: "Classic Tee", price: 75, size: "small", quantity: 2}

I can see why my output is like that, it's creating a new object each time my addItem function is fired, but I would like to mutate my shopItem.quantity if there are duplicates...

How would I do that?

Body:
You can give item time an identity attribute (I would not go by name, since it is possible you can have something with the same name and that would be bad) such as id and the you can search for it before adding something. For example, consider the following item:

const cartItem = {id: 1, name: "Classic Tee"}

Then before adding the item, you could look for it in the cart:

const existingItem = shoppingCart.find((item) => {
  return cartItem.id === item.id;
});

if(existingItem) {
   existingItem.quantity++;
} else {
  // Push the item into the cart
  shoppingCart.push(cartItem);
}


问:
Create a jQuery Countdown Timer which resets after intervals
I want to create a jQuery Countdown Timer, to which i'll pass a time, it will show counter to that time and then resets to count one hour and then resets to count next 23 hours and then resets to one hour loop continues.

I am taking a quiz on a certain date, quiz will open for one hour, then next quiz will start after 23 hours.

Can anyone help..?

答:
You can use this

HTML:

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

JS:

```<code>var fiveSeconds = new Date().getTime() + 5000;
$('#clock').countdown(fiveSeconds, {elapse: true})
.on('update.countdown', function(event) {
  var $this = $(this);
  if (event.elapsed) {
    $this.html(event.strftime('After end: <span>%H:%M:%S</span>'));
  } else {
    $this.html(event.strftime('To end: <span>%H:%M:%S</span>'));
  }
});
</code>```

Body:
You can use this

HTML:

<div id="clock"></div>

JS:

var fiveSeconds = new Date().getTime() + 5000;
$('#clock').countdown(fiveSeconds, {elapse: true})
.on('update.countdown', function(event) {
  var $this = $(this);
  if (event.elapsed) {
    $this.html(event.strftime('After end: <span>%H:%M:%S</span>'));
  } else {
    $this.html(event.strftime('To end: <span>%H:%M:%S</span>'));
  }
});


问:
How come my string function does not return anything?
Either the function does not return anything or it returns an empty string. I am trying to erase everything before next sequence after the -e text in the string. For example, test -e test/file/path should return test/file/path without the space after -e. However, when the function does not return anything or it returns an empty string. I cannot find anything wrong with my function please help!

```<code>#include <iostream>
using namespace std;

string fileparse(string str) {
    int i;

    for (i = 0; i < str.size(); i++)
        if (str[i] == '-')
            i += 2; //to account for the space after 'e'
    str.erase(str.begin(), str.begin()+i);
    return str;
}

int main()
{

    string str = "test -e test/file/path";
    string vars = fileparse(str);
    cout << vars << endl; //blank
    return 0;
}
</code>```

答:
```<code>if (str[i] == '-') {
     i += 3;
     break;
}
</code>```

It stops when being encountered '-' symbol. To get rid of i is increased by 1, and to get rid of letter e and one space by 2.

Body:
Either the function does not return anything or it returns an empty string. I am trying to erase everything before next sequence after the -e text in the string. For example, test -e test/file/path should return test/file/path without the space after -e. However, when the function does not return anything or it returns an empty string. I cannot find anything wrong with my function please help!

#include <iostream>
using namespace std;

string fileparse(string str) {
    int i;

    for (i = 0; i < str.size(); i++)
        if (str[i] == '-')
            i += 2; //to account for the space after 'e'
    str.erase(str.begin(), str.begin()+i);
    return str;
}

int main()
{

    string str = "test -e test/file/path";
    string vars = fileparse(str);
    cout << vars << endl; //blank
    return 0;
}

Body:
if (str[i] == '-') {
     i += 3;
     break;
}

It stops when being encountered '-' symbol. To get rid of i is increased by 1, and to get rid of letter e and one space by 2.


问:
Using Properties from ResourceBundle in ManagedProperty
I have a JSF Validator that I'm building that has properties in it that I would like to have loaded from a ResourceBundle.  However, I'm not quite sure how to work this, as it isn't loading properly.  Any ideas on how I can make this work?

I've tried using a @PostContruct to do it, but I'm getting the following error in Eclipse:

Access restriction: The type
  PostConstruct is not accessible due to
  restriction on required library
  /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/classes.jar

So, I'm not too sure what the best way to work this.  A sample of what I'm talking about is below...

The validator...

```<code>@FacesValidator("usernameValidator")
public class UserNameValidator implements Validator {

  @ManagedProperty(value="#{props_userNamePattern}")
  private String userNamePattern;

  @ManagedProperty(value="#{props_minUserNameLength}")
  private int minUserNameLength;

  @ManagedProperty(value="#{props_maxUserNameLength}")
  private int maxUserNameLength;

  public void validate(FacesContext context, UIComponent component, Object
        value) throws ValidatorException {
    //My validations here...
  }

  //Setters for the class properties

}
</code>```

faces-config.xml

```<code><resource-bundle>
    <base-name>settings</base-name>
</resource-bundle>
</code>```

settings.properties

```<code>props_userNamePattern = /^[a-z0-9_-]+$/
props_minUserNameLength = 3
props_maxUserNameLength = 30
</code>```

答:
Perhaps seam-faces might help for this situation?

http://docs.jboss.org/seam/3/faces/latest/reference/en-US/html/artifacts.html

http://docs.jboss.org/seam/3/faces/latest/reference/en-US/html/faces.messages.html

Body:
I have a JSF Validator that I'm building that has properties in it that I would like to have loaded from a ResourceBundle.  However, I'm not quite sure how to work this, as it isn't loading properly.  Any ideas on how I can make this work?

I've tried using a @PostContruct to do it, but I'm getting the following error in Eclipse:

Access restriction: The type
  PostConstruct is not accessible due to
  restriction on required library
  /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/classes.jar

So, I'm not too sure what the best way to work this.  A sample of what I'm talking about is below...

The validator...

@FacesValidator("usernameValidator")
public class UserNameValidator implements Validator {

  @ManagedProperty(value="#{props_userNamePattern}")
  private String userNamePattern;

  @ManagedProperty(value="#{props_minUserNameLength}")
  private int minUserNameLength;

  @ManagedProperty(value="#{props_maxUserNameLength}")
  private int maxUserNameLength;

  public void validate(FacesContext context, UIComponent component, Object
        value) throws ValidatorException {
    //My validations here...
  }

  //Setters for the class properties

}

faces-config.xml

<resource-bundle>
    <base-name>settings</base-name>
</resource-bundle>

settings.properties

props_userNamePattern = /^[a-z0-9_-]+$/
props_minUserNameLength = 3
props_maxUserNameLength = 30