问:
Reading raw data file dlm
I have problem reading in a raw data file. The problem is that some of inputs gets cut of because of the delimiter. Since one of the title has "\" in front of the real title, the Book_Title output is only "\". I was wondering if there is a way of ignoring those symbols.

Input:

```<code>0195153448;"Classical Mythology";"Mark P. O. Morford";"2002";"Oxford University Press"
085409878X;"\"Pie-powder\"; being dust from the law courts;John Alderson Foote";"1973";"EP Publishing"
</code>```

The code:

```<code>data rating.books;
infile "&path\BX-Books.csv" dlm=';' missover dsd firstobs=2;
input   ISBN: $12.
            Book_Title: $quote150.
            Book_Author: $quote60.
            Year_Of_Publication: $quote8.
            Publisher: $quote60.;
run;
</code>```

Output:

```<code>ISBN | Book-Title | Book-Author | Publisher | Publication-Year
0195153448 | Classical Mythology | Mark P. O. Morford | Oxford University Press | 2002
085409878X | \ | being dust from the law courts,"|  1973 | Missing value
</code>```

Desired output:

```<code>     ISBN | Book-Title | Book-Author | Publisher | Publication-Year
    0195153448 | Classical Mythology | Mark P. O. Morford | Oxford University Press | 2002
    085409878X | Pie-powder being dust from the law courts |John Alderson Foote | EP Publishing | 1973
</code>```

答:
You have to change a bit your code to put the missing column into a string $150. like that :

```<code>data work.books;
infile "h:\desktop\test.csv" dlm=';' missover dsd firstobs=1;
input   ISBN: $12.
            Book_Title: $150.
            Book_Author: $quote60.
            Year_Of_Publication: $quote8.
            Publisher: $quote60.;
run;
</code>```

Then, you have to clean the column from special characters " and \ with this macro function :

```<code>%macro cleaningColumn(col);
    compress(strip(&col),'\"',' ')
%mend cleaningColumn;
</code>```

You can include the macro function into a proc sql statement like this :

```<code>proc sql;
create table want as
    select
        ISBN,
        %cleaningColumn(Book_Title) as Book_Title,
        Book_Author,
        Year_Of_Publication,
        Publisher
    from books;
run;
</code>```

The column Book_Title will be like this :

```<code>Classical Mythology
Pie-powder
</code>```

Regards,

Title: Reading raw data file dlm

Body:
I have problem reading in a raw data file. The problem is that some of inputs gets cut of because of the delimiter. Since one of the title has "\" in front of the real title, the Book_Title output is only "\". I was wondering if there is a way of ignoring those symbols.

Input:

0195153448;"Classical Mythology";"Mark P. O. Morford";"2002";"Oxford University Press"
085409878X;"\"Pie-powder\"; being dust from the law courts;John Alderson Foote";"1973";"EP Publishing"

The code:

data rating.books;
infile "&path\BX-Books.csv" dlm=';' missover dsd firstobs=2;
input   ISBN: $12.
            Book_Title: $quote150.
            Book_Author: $quote60.
            Year_Of_Publication: $quote8.
            Publisher: $quote60.;
run;

Output:

ISBN | Book-Title | Book-Author | Publisher | Publication-Year
0195153448 | Classical Mythology | Mark P. O. Morford | Oxford University Press | 2002
085409878X | \ | being dust from the law courts,"|  1973 | Missing value

Desired output:

     ISBN | Book-Title | Book-Author | Publisher | Publication-Year
    0195153448 | Classical Mythology | Mark P. O. Morford | Oxford University Press | 2002
    085409878X | Pie-powder being dust from the law courts |John Alderson Foote | EP Publishing | 1973

Body:
You have to change a bit your code to put the missing column into a string $150. like that :

data work.books;
infile "h:\desktop\test.csv" dlm=';' missover dsd firstobs=1;
input   ISBN: $12.
            Book_Title: $150.
            Book_Author: $quote60.
            Year_Of_Publication: $quote8.
            Publisher: $quote60.;
run;

Then, you have to clean the column from special characters " and \ with this macro function :

%macro cleaningColumn(col);
    compress(strip(&col),'\"',' ')
%mend cleaningColumn;

You can include the macro function into a proc sql statement like this :

proc sql;
create table want as
    select
        ISBN,
        %cleaningColumn(Book_Title) as Book_Title,
        Book_Author,
        Year_Of_Publication,
        Publisher
    from books;
run;

The column Book_Title will be like this :

Classical Mythology
Pie-powder

Regards,


来源: stackexchange

问:
Add multiple labels in oxyplot chart without letting them overwrite the linear axis values
I'm trying to add labels for the x and y axes, but the label is actually overwriting the linearaxis values.

This is the picture

答:
Use the AxisTitleDistance attribute. Either in the XAML or in code.</p>

```<code>model.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom, AxisTitleDistance = 25});
model.Axes.Add(new LinearAxis { Position = AxisPosition.Left, AxisTitleDistance = 25});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Use the AxisTitleDistance attribute. Either in the XAML or in code.

model.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom, AxisTitleDistance = 25});
model.Axes.Add(new LinearAxis { Position = AxisPosition.Left, AxisTitleDistance = 25});


问:
Jhipster blank page
I started working on web services. Whenever I try to run existing project in Netbeans. Project builds successfully with result

```<code>Application 'Project Name' is running! Access URLs:
    Local:      http://localhost:8090
    External:   http://192.168.1.4:8090
    Profile(s):     [swagger, dev]
</code>```

When ever I go to browser and try to run this URL. I don't get response. I have no idea what's wrong. Please help me.

答:
These commands helped me

1) yarn
2) yarn webpack:build
3) ./mvnw

Title: Jhipster blank page

Body:
I started working on web services. Whenever I try to run existing project in Netbeans. Project builds successfully with result

Application 'Project Name' is running! Access URLs:
    Local:      http://localhost:8090
    External:   http://192.168.1.4:8090
    Profile(s):     [swagger, dev]

When ever I go to browser and try to run this URL. I don't get response. I have no idea what's wrong. Please help me.


问:
Retrieve sections from config.json in ASP.NET 5
Let's say I have a config.json like this:

```<code>{
  "CustomSection": {
    "A": 1,
    "B": 2
  }
}
</code>```

I know I can use an IConfiguration object to get specific settings, i.e., configuration.Get("CustomSection:A"), but can I grab the whole hierarchy (in any type - even a raw string would be fine)?  When I try configuration.Get("CustomSection"), I get a null result, so I think this isn't supported by default.

My use case is grabbing entire configuration dictionaries at once without having to grab each individual setting - some properties may not be known at compile time.

答:
For a detailed explanation, see
 https://dotnetcodr.com/2017/01/20/introduction-to-asp-net-core-part-3-the-configuration-file/

Below is an example from the site:

Config file has this:

```<code>"Languages": {
  ".NET": [ "C#", "VB.NET", "F#" ],
  "JVM": ["Java", "Scala", "Clojure"]
}
</code>```

Load this configuration as follows:

```<code>IConfigurationSection languagesSection = configRoot.GetSection("Languages");
IEnumerable<IConfigurationSection> languagesSectionMembers = languagesSection.GetChildren();
Dictionary<string, List<string>> platformLanguages = new Dictionary<string, List<string>>();
foreach (var platform in languagesSectionMembers)
{
    List<string> langs = (from p in platform.GetChildren() select p.Value).ToList();
    platformLanguages[platform.Key] = langs;
}
</code>```

Body:
Let's say I have a config.json like this:

{
  "CustomSection": {
    "A": 1,
    "B": 2
  }
}

I know I can use an IConfiguration object to get specific settings, i.e., configuration.Get("CustomSection:A"), but can I grab the whole hierarchy (in any type - even a raw string would be fine)?  When I try configuration.Get("CustomSection"), I get a null result, so I think this isn't supported by default.

My use case is grabbing entire configuration dictionaries at once without having to grab each individual setting - some properties may not be known at compile time.

Body:
For a detailed explanation, see
 https://dotnetcodr.com/2017/01/20/introduction-to-asp-net-core-part-3-the-configuration-file/

Below is an example from the site:

Config file has this:

"Languages": {
  ".NET": [ "C#", "VB.NET", "F#" ],
  "JVM": ["Java", "Scala", "Clojure"]
}

Load this configuration as follows:

IConfigurationSection languagesSection = configRoot.GetSection("Languages");
IEnumerable<IConfigurationSection> languagesSectionMembers = languagesSection.GetChildren();
Dictionary<string, List<string>> platformLanguages = new Dictionary<string, List<string>>();
foreach (var platform in languagesSectionMembers)
{
    List<string> langs = (from p in platform.GetChildren() select p.Value).ToList();
    platformLanguages[platform.Key] = langs;
}


问:
Spring boot: how to specify a main class located in the internal lib
I am packaging my spring boot application into a jar file using "spring-boot-maven-plugin" and I need to point to a mainClass which resides in my-internal-lib.jar.

```<code><build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <version>1.3.2.RELEASE</version>
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <mainClass>my.internal.lib.Main</mainClass>
            </configuration>
        </plugin>
    </plugins>
</build>
</code>```

Folder structure of generated jar is as follows:

```<code>-- com
   -- my
      -- spring
          -- boot
              RestRunner.java
              App.java

-- lib
    -- my-internal-lib.jar (my.internal.lib.Main.java)

-- META-INF
    -- maven
    -- MANIFEST.MF
-- org
application.properties
</code>```

And my code is something like this:

```<code>package my.internal.lib;
public class Main {
    public static void main(String[] args){
        new RestRunner().start(args);
    }
}

package com.my.spring.boot;
public class RestRunner{

    public boolean start(String[] args){
        SpringApplication.run(App.class, args);
    }
}

package com.my.spring.boot;
@SpringBootApplication(scanBasePackages = {"com.my.spring.boot"})
public class App {}
</code>```

And my MANIFEST.MF is as follows:

```<code>Manifest-Version: 1.0
Archiver-Version: Plexus Archiver
Built-By: ...
Start-Class: my.internal.lib.Main
Spring-Boot-Version: 1.3.2.RELEASE
Created-By: Apache Maven 3.3.9
Build-Jdk: 1.8.0_112
Main-Class: org.springframework.boot.loader.JarLauncher
</code>```

But I get this error while running the jar using command "java -cp myjar.jar my.internal.lib.Main":

```<code>java.lang.ClassNotFoundException: my.internal.lib.Main
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
</code>```

Is my internal jar in the classpath? if not, how to add it?

答:
The problem solved using "java -jar jarname".
Thanks to @Alexander.Furer</p>

Body:
I am packaging my spring boot application into a jar file using "spring-boot-maven-plugin" and I need to point to a mainClass which resides in my-internal-lib.jar.

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <version>1.3.2.RELEASE</version>
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <mainClass>my.internal.lib.Main</mainClass>
            </configuration>
        </plugin>
    </plugins>
</build>

Folder structure of generated jar is as follows:

-- com
   -- my
      -- spring
          -- boot
              RestRunner.java
              App.java

-- lib
    -- my-internal-lib.jar (my.internal.lib.Main.java)

-- META-INF
    -- maven
    -- MANIFEST.MF
-- org
application.properties

And my code is something like this:

package my.internal.lib;
public class Main {
    public static void main(String[] args){
        new RestRunner().start(args);
    }
}

package com.my.spring.boot;
public class RestRunner{

    public boolean start(String[] args){
        SpringApplication.run(App.class, args);
    }
}

package com.my.spring.boot;
@SpringBootApplication(scanBasePackages = {"com.my.spring.boot"})
public class App {}

And my MANIFEST.MF is as follows:

Manifest-Version: 1.0
Archiver-Version: Plexus Archiver
Built-By: ...
Start-Class: my.internal.lib.Main
Spring-Boot-Version: 1.3.2.RELEASE
Created-By: Apache Maven 3.3.9
Build-Jdk: 1.8.0_112
Main-Class: org.springframework.boot.loader.JarLauncher

But I get this error while running the jar using command "java -cp myjar.jar my.internal.lib.Main":

java.lang.ClassNotFoundException: my.internal.lib.Main
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

Is my internal jar in the classpath? if not, how to add it?


问:
Selenium/testNG: How to run your test based on class priority and not on your method priorily from the XML file
If have the following:

Class A
{
  Method M(priority = 2)
}

Class B
{
  Method M(priority = 1)
}
```

<p>Then <code>Class B</code> is going to be executed before <code>Class A</code>. How can I execute <code>Class A</code> first?</p>

<p>The XML file that I am using is:</p>

<pre class="lang-xml prettyprint-override"><code><classes>
  <class name="com.Users.Admin_ManageUsers_AR"/>
  <class name="com.Users.Admin_ManageUsers_AR"/>
</classes>
</code>```

答:
Use group-by-instances="true" inside test tag of the testng.xml

Define your xml like below:

```<code><test name="ManageUsersTest" group-by-instances="true">
    <classes>
        <class name="com.Users.Admin_ManageUsers_AR.ClassA" />
        <class name="com.Users.Admin_ManageUsers_AR.ClassB" />
    </classes>
</test>
</code>```

Body:
If have the following:

Class A
{
  Method M(priority = 2)
}

Class B
{
  Method M(priority = 1)
}

Then Class B is going to be executed before Class A. How can I execute Class A first?

The XML file that I am using is:

<classes>
  <class name="com.Users.Admin_ManageUsers_AR"/>
  <class name="com.Users.Admin_ManageUsers_AR"/>
</classes>

Body:
Use group-by-instances="true" inside test tag of the testng.xml

Define your xml like below:

<test name="ManageUsersTest" group-by-instances="true">
    <classes>
        <class name="com.Users.Admin_ManageUsers_AR.ClassA" />
        <class name="com.Users.Admin_ManageUsers_AR.ClassB" />
    </classes>
</test>


问:
Magento translate checkout firstname/lastname & prefix
How can i translate my magentos 1.6 checkout:
firstname / lastname and prefix of my magento shopper template in german?

thank you
kind regards

答:
Simply use the PHP method for translations:

Example:

```<code><?php echo $this->__('firstname'); ?>
</code>```

Body:
Simply use the PHP method for translations:

Example:

<?php echo $this->__('firstname'); ?>


问:
QtCreator [Qt 5.9.x ] QQmlApplicationEngine failed to load component
This was bugging me for a while, and I am just submitting this if someone else gets the same bug as well, and as far as I could see, it's not an uncommon issue.

If you ever move your Qt QML code to a different machine, and after you run it from a Qt Creator, you get anything like this:

QQmlApplicationEngine failed to load component
  qrc:/main.qml:14 Type ApplicationWindow unavailable
  [path-to-your-qt]qt5/5.9.3/gcc_64/qml/QtQuick/Controls.2/ApplicationWindow.qml:41 plugin cannot be loaded for module "QtQuick.Templates": Cannot load library >
  [path-to-your-qt]qt5/5.9.3/gcc_64/qml/QtQuick/Templates.2/libqtquicktemplates2plugin.so:
  [path-to-your-qt]qt5/5.9.3/gcc_64/qml/QtQuick/Templates.2/libqtquicktemplates2plugin.so: symbol _ZN15QQuickContainer17componentCompleteEv, version Qt_5_PRIVATE_API not defined in file libQt5QuickTemplates2.so.5 with link time reference)

答:
Try running Qt Creator executable directly instead of running the shell file , i.e. run:

[qt5-dir]Tools/QtCreator/bin/qtcreator
instead of
[qt5-dir]Tools/QtCreator/bin/qtcreator.sh

qtcreator.sh fiddles with LD_LIBRARY_PATH, and there it might start using your system Qt libraries, which are 95% older than the Qt you've just installed using your Qt Installer


问:
Google Measurment Protocol
The question is, next, gmp has the ability to pass payload, where the mandatory field is clientId. However, there is an additional UserId field. Sending requests for the Google Measurment Protocol is carried out from the server, and it is not possible to get the clientId to send a request for a number of factors. However, on the client side, it is possible to bind the clientId to the UserId (in the google tag manager). Hence the  question is why do I need to pass the clientId to the mandatory field, if I can pass userId and the analyst in theory should match this userId with the client. Actually, how to be in this case, ie whether the google analytics really associate userId <-> clientId and what to transfer instead of clientId in queries.</p>

答:
ClientID field is mandatory but you should consider two options:

Storing the cliendID since this value is available client side on the _ga cookie.

If that is not possible you will need to generate a random clientID and use it along with the UserID.

The first one is the ideal one since non of you metrics will be affected but sometimes it is just not possible to do it. The second one will match the the clientIDs under a single UserID but only under userID views.
The key in this field is to use NI (non interaction) on your hits send by measurement protocol.

Example:

I made a pageview manually (Measurement protocol bit with interaction) with a UID X and later i send a transaction with another ClientID but the same UID.
Normal view:

UserID view:

hope it helps!

Title: Google Measurment Protocol


问:
Erasing noise from fft chart
Do you know how to delete so much noise from the FFT?
Here is my code of FFT:

```<code>import numpy as np

fft1 = (Bx[51:-14])
fft2 = (By[1:-14])

# Loop for FFT data
for dataset in [fft1]:
    dataset = np.asarray(dataset)
    psd = np.abs(np.fft.fft(dataset))**2
    freq = np.fft.fftfreq(dataset.size, float(300)/dataset.size)
    plt.semilogy(freq[freq>0], psd[freq>0]/dataset.size**2, color='r')

for dataset2 in [fft2]:
    dataset2 = np.asarray(dataset2)
    psd2 = np.abs(np.fft.fft(dataset2))**2
    freq2 = np.fft.fftfreq(dataset2.size, float(300)/dataset2.size)
    plt.semilogy(freq2[freq2>0], psd2[freq2>0]/dataset2.size**2, color='b')
</code>```

What I get:

What I need:

Any ideas? Welch does not work, so as you can see, I don't want to smooth my chart, but erase so much noise to the level which is presented on the second picture.

This is what Welch do:

and a bit of code:

```<code>freqs, psd = scipy.signal.welch(dataset, fs=300, window='hamming')
</code>```

Updated Welch:

A bit of code:

```<code># Loop for FFT data
for dataset in [fft1]:
    dataset = np.asarray(dataset)
    freqs, psd = welch(dataset, fs=266336/300, window='hamming', nperseg=512)
    plt.semilogy(freqs, psd/dataset.size**2, color='r')

for dataset2 in [fft2]:
    dataset2 = np.asarray(dataset2)
    freqs2, psd2 = welch(dataset2, fs=266336/300, window='hamming', nperseg=512)
    plt.semilogy(freqs2, psd2/dataset2.size**2, color='b')
</code>```

As you can see Welch is well configurated, it shows 60 Hz electricity line, and harmonic modes. It is almost good, but it smoothed completely my plot. See graph two which is desired. Btw. y scale is wrong at Welch plot, but it is just a case of power data to the two.

I have changed to nperseg=8192 and it worked. Look at the results.

答:
Here is an example that shows how to use nperseg to control the frequency resolution vs. noise reduction tradeoff:

Setting nperseg to the length of the signal is more or less equivalent to using the FFT without any averaging.

Here is the code to generate this image:

```<code>import numpy as np
from scipy import signal
import matplotlib.pyplot as plt

plt.figure(figsize=[8, 12])

n = 2**21
fs = 887

# example data
x = np.random.randn(n)
x += np.sin(np.cumsum(0.42 + np.random.randn(n) * 0.01)) * 5
x = signal.lfilter([1, 0.5], 2, x)

plt.subplot(3, 2, 1)
plt.semilogy(np.abs(np.fft.fft(x)[:n//2])**2 / n**2, label='FFT')
plt.legend(loc='best')

for i, nperseg in enumerate([128, 512, 8192, 65536, n]):
    plt.subplot(3, 2, i+2)
    f, psd = signal.welch(x, fs=fs, window='hamming', nperseg=nperseg, noverlap=0)
    plt.semilogy(f, psd, label='nperseg={}'.format(nperseg))
    plt.legend(loc='best')

plt.show()
</code>```

Title: Erasing noise from fft chart

Body:
Do you know how to delete so much noise from the FFT?
Here is my code of FFT:

import numpy as np

fft1 = (Bx[51:-14])
fft2 = (By[1:-14])

# Loop for FFT data
for dataset in [fft1]:
    dataset = np.asarray(dataset)
    psd = np.abs(np.fft.fft(dataset))**2
    freq = np.fft.fftfreq(dataset.size, float(300)/dataset.size)
    plt.semilogy(freq[freq>0], psd[freq>0]/dataset.size**2, color='r')

for dataset2 in [fft2]:
    dataset2 = np.asarray(dataset2)
    psd2 = np.abs(np.fft.fft(dataset2))**2
    freq2 = np.fft.fftfreq(dataset2.size, float(300)/dataset2.size)
    plt.semilogy(freq2[freq2>0], psd2[freq2>0]/dataset2.size**2, color='b')

What I get:

What I need:

Any ideas? Welch does not work, so as you can see, I don't want to smooth my chart, but erase so much noise to the level which is presented on the second picture.

This is what Welch do:

and a bit of code:

freqs, psd = scipy.signal.welch(dataset, fs=300, window='hamming')

Updated Welch:

A bit of code:

# Loop for FFT data
for dataset in [fft1]:
    dataset = np.asarray(dataset)
    freqs, psd = welch(dataset, fs=266336/300, window='hamming', nperseg=512)
    plt.semilogy(freqs, psd/dataset.size**2, color='r')

for dataset2 in [fft2]:
    dataset2 = np.asarray(dataset2)
    freqs2, psd2 = welch(dataset2, fs=266336/300, window='hamming', nperseg=512)
    plt.semilogy(freqs2, psd2/dataset2.size**2, color='b')

As you can see Welch is well configurated, it shows 60 Hz electricity line, and harmonic modes. It is almost good, but it smoothed completely my plot. See graph two which is desired. Btw. y scale is wrong at Welch plot, but it is just a case of power data to the two.

I have changed to nperseg=8192 and it worked. Look at the results.

Body:
Here is an example that shows how to use nperseg to control the frequency resolution vs. noise reduction tradeoff:

Setting nperseg to the length of the signal is more or less equivalent to using the FFT without any averaging.

Here is the code to generate this image:

import numpy as np
from scipy import signal
import matplotlib.pyplot as plt

plt.figure(figsize=[8, 12])

n = 2**21
fs = 887

# example data
x = np.random.randn(n)
x += np.sin(np.cumsum(0.42 + np.random.randn(n) * 0.01)) * 5
x = signal.lfilter([1, 0.5], 2, x)

plt.subplot(3, 2, 1)
plt.semilogy(np.abs(np.fft.fft(x)[:n//2])**2 / n**2, label='FFT')
plt.legend(loc='best')

for i, nperseg in enumerate([128, 512, 8192, 65536, n]):
    plt.subplot(3, 2, i+2)
    f, psd = signal.welch(x, fs=fs, window='hamming', nperseg=nperseg, noverlap=0)
    plt.semilogy(f, psd, label='nperseg={}'.format(nperseg))
    plt.legend(loc='best')

plt.show()


问:
Node JS + AWS Promise Triggered Twice
```<code>AWS = require('aws-sdk');
AWS.config.region = 'eu-west-1';
ses = new AWS.SES();

var params = {};

return ses.sendEmail(params, function (err, data) {
    console.log('----->sending email')
}).promise().then((data) => {
    console.log('---->sending promise')
}).catch((err) => {
    console.log('----->am in error')
    console.log(err)
})
</code>```

Can someone help my above code promise is triggered twice.

I should get below

----->sending email

---->sending promise

But i got

----->sending email

---->sending promise

----->sending email

答:
It looks like you are providing both a callback function and using the promise approach. Effectively, this means that you have two different functions that execute when the request is done. Choose one of the following:

You can use the promise approach, with then and catch.

```<code>function send(params) {
    ses.sendEmail(params).promise().then((data) => {
        console.log('Email was sent')
    }).catch((err) => {
        console.log('There was an error')
    })
}
</code>```

You can use promise with async/await. Make sure you add the async keyword to your function header. Make sure your Node runtime supports async/await or that you code is transpiled to whatever Node version you are using.

```<code>async function send(params) {
    try {
        const data = await ses.sendEmail(params).promise();
        console.log('Email was sent')
    } catch(err) {
        console.log('There was an error')
    }
}
</code>```

Finally, you could use the callback approach:

```<code>function send(params) {
    ses.sendEmail(params, function(err, data) {
        if (err) {
            console.log('There was an error')
            return
        }
        console.log('Email was sent')
    })
}
</code>```

Title: Node JS + AWS Promise Triggered Twice

Body:
AWS = require('aws-sdk');
AWS.config.region = 'eu-west-1';
ses = new AWS.SES();

var params = {};

return ses.sendEmail(params, function (err, data) {
    console.log('----->sending email')
}).promise().then((data) => {
    console.log('---->sending promise')
}).catch((err) => {
    console.log('----->am in error')
    console.log(err)
})

Can someone help my above code promise is triggered twice.

I should get below

----->sending email

---->sending promise

But i got

----->sending email

---->sending promise

----->sending email

Body:
It looks like you are providing both a callback function and using the promise approach. Effectively, this means that you have two different functions that execute when the request is done. Choose one of the following:

You can use the promise approach, with then and catch.

function send(params) {
    ses.sendEmail(params).promise().then((data) => {
        console.log('Email was sent')
    }).catch((err) => {
        console.log('There was an error')
    })
}

You can use promise with async/await. Make sure you add the async keyword to your function header. Make sure your Node runtime supports async/await or that you code is transpiled to whatever Node version you are using.

async function send(params) {
    try {
        const data = await ses.sendEmail(params).promise();
        console.log('Email was sent')
    } catch(err) {
        console.log('There was an error')
    }
}

Finally, you could use the callback approach:

function send(params) {
    ses.sendEmail(params, function(err, data) {
        if (err) {
            console.log('There was an error')
            return
        }
        console.log('Email was sent')
    })
}

ContentLicense: CC BY-SA 4.0


问:
WCF service hangs when calling method, however method is working
Hello I'm having issue with my wcf service. I'm trying to call method which returns list of type object. I'm also using entity framework.

```<code>public IList<Product> GetAllProducts()
    {
        using (var db = new AuctionContext())
        {
            return db.Products.ToList();
        }
    }

    </service>
  <service name="AuctionSystem.WcfService.ProductService">
    <endpoint address="" binding="wsDualHttpBinding" contract="AuctionSystem.WcfService.Contracts.IProductService">
      <identity>
        <dns value="localhost" />
      </identity>
    </endpoint>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:9993/Design_Time_Addresses/AuctionSystem.WcfService/ProductService/" />
      </baseAddresses>
    </host>
  </service>
</code>```

And contract :

```<code> [OperationContract]
    IList<Product> GetAllProducts();
</code>```

The method itself is working, but when I try to invoke this method on my wcf service UI it got stuck at "invoking service" I'm using wsdualhttpbinding.

Any ideas please?

EDIT: I realized in Product object I have virtual List, why is this List causing wcf to hang?

答: For all wondering why It was caused because of circular dependency.</p>

Body:
Hello I'm having issue with my wcf service. I'm trying to call method which returns list of type object. I'm also using entity framework.

public IList<Product> GetAllProducts()
    {
        using (var db = new AuctionContext())
        {
            return db.Products.ToList();
        }
    }

    </service>
  <service name="AuctionSystem.WcfService.ProductService">
    <endpoint address="" binding="wsDualHttpBinding" contract="AuctionSystem.WcfService.Contracts.IProductService">
      <identity>
        <dns value="localhost" />
      </identity>
    </endpoint>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:9993/Design_Time_Addresses/AuctionSystem.WcfService/ProductService/" />
      </baseAddresses>
    </host>
  </service>

And contract :

 [OperationContract]
    IList<Product> GetAllProducts();

The method itself is working, but when I try to invoke this method on my wcf service UI it got stuck at "invoking service" I'm using wsdualhttpbinding.

Any ideas please?

EDIT: I realized in Product object I have virtual List, why is this List causing wcf to hang?


问:
Run web-Socket locally for debug
I’m using gorilla web socket and I want to run it locally , I mean with the following chrome client
or other recommended tool …when I run into debug mode I got error

I use

```<code>"github.com/gorilla/websocket"

var upgrader = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
}

upgrader.CheckOrigin = func(r *http.Request) bool { return true }

c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
    log.Print("upgrade:", err)
    return
}
</code>```

When I run the following url in chrome or web socket client I got error

websocket: not a websocket handshake: 'upgrade' token not found in 'Connection' header

```<code>localhost:8081/mypath
</code>```

and I want to run it

```<code>ws://localhost:8081/mypath
</code>```

and provide token for local simulation, how I can do it ?

To check it I use Simple WebSocket Client of chrome. any other client will be helpful

EDIT:

when I try it in the chrome console I got the following error:

VM42:164 Refused to connect to 'ws://localhost:8081/mypath' because it
  violates the following Content Security Policy directive: "connect-src
  'self' uploads.github.com status.github.com collector.githubapp.com
  api.github.com www.google-analytics.com github-cloud.s3.amazonaws.com
  github-production-repository-file-5c1aeb.s3.amazonaws.com
  github-production-upload-manifest-file-7fdce7.s3.amazonaws.com
  github-production-user-asset-6210df.s3.amazonaws.com
  wss://live.github.com

答:
Browsers do not use the WebSocket protocol when fetching a web page for display. Code is required to use a WebSocket endpoint from a browser.

The Gorilla package includes examples showing how to connect from a browser (the chat and command examples are good places to start).

You can can connect to a WebSocket endpoint using the browser console:

```<code>> ws = new WebSocket("ws://localhost:8080/mypath")
> ws.onmessage = function(ev) { console.log(ev.data) }
> ws.send("hello")
</code>```

Title: Run web-Socket locally for debug

Body:
I’m using gorilla web socket and I want to run it locally , I mean with the following chrome client
or other recommended tool …when I run into debug mode I got error

I use

"github.com/gorilla/websocket"

var upgrader = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
}

upgrader.CheckOrigin = func(r *http.Request) bool { return true }

c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
    log.Print("upgrade:", err)
    return
}

When I run the following url in chrome or web socket client I got error

websocket: not a websocket handshake: 'upgrade' token not found in 'Connection' header

localhost:8081/mypath

and I want to run it

ws://localhost:8081/mypath

and provide token for local simulation, how I can do it ?

To check it I use Simple WebSocket Client of chrome. any other client will be helpful

EDIT:

when I try it in the chrome console I got the following error:

VM42:164 Refused to connect to 'ws://localhost:8081/mypath' because it
  violates the following Content Security Policy directive: "connect-src
  'self' uploads.github.com status.github.com collector.githubapp.com
  api.github.com www.google-analytics.com github-cloud.s3.amazonaws.com
  github-production-repository-file-5c1aeb.s3.amazonaws.com
  github-production-upload-manifest-file-7fdce7.s3.amazonaws.com
  github-production-user-asset-6210df.s3.amazonaws.com
  wss://live.github.com

Body:
Browsers do not use the WebSocket protocol when fetching a web page for display. Code is required to use a WebSocket endpoint from a browser.

The Gorilla package includes examples showing how to connect from a browser (the chat and command examples are good places to start).

You can can connect to a WebSocket endpoint using the browser console:

> ws = new WebSocket("ws://localhost:8080/mypath")
> ws.onmessage = function(ev) { console.log(ev.data) }
> ws.send("hello")


问:
Overflow Warning VBA
I am getting Overflow Warning while running the below fragment of code:

```<code>For Each Row In Rng.Rows

    For Each cell In Row.Cells

        cell.Activate

        ActiveCell.Select

        If IsNumeric(ActiveCell) Then

            ActiveCell.Value = CInt(ActiveCell.Value)

        End If

        Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _
        Formula1:="=1"

        Selection.FormatConditions

        (Selection.FormatConditions.Count).SetFirstPriority

        With Selection.FormatConditions(1).Interior.ColorIndex = 20

        End With

        Selection.FormatConditions(1).StopIfTrue = False

    Next cell

Next Row
</code>```

cell and Row are both declared as Variant.

The code was written by someone else and the warning is not coming my system. The error is coming in few other systems.

Please let me know if there is a bug in the code or any other way to stop getting this message.

答:
The error occurs on this line:

```<code>ActiveCell.Value = CInt(ActiveCell.Value)
</code>```

CInt can only cope with values between -32,768 to 32,767.

Check your data types here to find out which one will fit your requirements better

Title: Overflow Warning VBA

Body:
I am getting Overflow Warning while running the below fragment of code:

For Each Row In Rng.Rows

    For Each cell In Row.Cells

        cell.Activate

        ActiveCell.Select

        If IsNumeric(ActiveCell) Then

            ActiveCell.Value = CInt(ActiveCell.Value)

        End If

        Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _
        Formula1:="=1"

        Selection.FormatConditions

        (Selection.FormatConditions.Count).SetFirstPriority

        With Selection.FormatConditions(1).Interior.ColorIndex = 20

        End With

        Selection.FormatConditions(1).StopIfTrue = False

    Next cell

Next Row

cell and Row are both declared as Variant.

The code was written by someone else and the warning is not coming my system. The error is coming in few other systems.

Please let me know if there is a bug in the code or any other way to stop getting this message.

Body:
The error occurs on this line:

ActiveCell.Value = CInt(ActiveCell.Value)

CInt can only cope with values between -32,768 to 32,767.

Check your data types here to find out which one will fit your requirements better


问:
Hiding and Showing keyboard with notificationCenter in swift
I can't get the keyboard to show and hide on my SignUpViewController.</p>

```<code>//Keyboard frame size
var keyboard = CGRect()

//Default function
override func viewDidLoad() {
    super.viewDidLoad()

    //scrollView frame size
    self.scrollView.frame = CGRect(x: 0, y: 0, width: self.scrollView.frame.size.width, height: self.scrollView.frame.size.height)
    scrollView.contentSize.height = self.view.frame.height
    scrollViewHeight = scrollView.frame.size.height

    //check notificvations if keyboard is shown or not
    let notificationCenter = NotificationCenter.default
    NotificationCenter.default.addObserver(self, selector: #selector(SignUpVC.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

    NotificationCenter.default.addObserver(self, selector: #selector(SignUpVC.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
</code>```

答: You have to set for example an uitextfield to become the first responder.</p>

Body:
I can't get the keyboard to show and hide on my SignUpViewController.

//Keyboard frame size
var keyboard = CGRect()

//Default function
override func viewDidLoad() {
    super.viewDidLoad()

    //scrollView frame size
    self.scrollView.frame = CGRect(x: 0, y: 0, width: self.scrollView.frame.size.width, height: self.scrollView.frame.size.height)
    scrollView.contentSize.height = self.view.frame.height
    scrollViewHeight = scrollView.frame.size.height

    //check notificvations if keyboard is shown or not
    let notificationCenter = NotificationCenter.default
    NotificationCenter.default.addObserver(self, selector: #selector(SignUpVC.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

    NotificationCenter.default.addObserver(self, selector: #selector(SignUpVC.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}


问:
Apply customized width to a prime-ng p-column in html template in angular
I want to apply a different width to each column of my columns using [style] as shown in the example, I tried [style]="{'width.px':'column.length + 10'}" but column.length isn't working on the template, below an example of my template

```<code><p-column *ngFor="let column of columns"
        [field]="column"
        [header]="label[column] ? label[column] : column"
        [style]="{'width.px':'column.length + 10'}"></p-column>
</code>```

thanks in advance.

答:
I found this solution which isn't perfect, but for me, it answers to the problem:

```<code>[style]="{'width.px': +(column.length)+20}"
</code>```

The '+' sign is there to convert value to a number (I tried putting Number(column) which didn't work here) - it is weird. I think this is happening, because column.length suppose to be a number, and I added 20 px for margin the text.

Body:
I want to apply a different width to each column of my columns using [style] as shown in the example, I tried [style]="{'width.px':'column.length + 10'}" but column.length isn't working on the template, below an example of my template

thanks in advance.

Body:
I found this solution which isn't perfect, but for me, it answers to the problem:

[style]="{'width.px': +(column.length)+20}"

The '+' sign is there to convert value to a number (I tried putting Number(column) which didn't work here) - it is weird. I think this is happening, because column.length suppose to be a number, and I added 20 px for margin the text.


问:
How can I convert a std::vector<float> to a float array?

Possible Duplicate:

  Getting array from std:vector

I've been reading the answers to this question and found them useful, but how can I do the same with a float type?

答:
In exactly the way econoclast demonstrated on the answer you quoted.</p>

```<code>std::vector<float> v;
v.push_back(1.2);
v.push_back(3.4);

// &v[0] is a pointer to the first element of the vector.

float* array_sort_of = &v[0];
for (size_t i = 0; i < 2; i++) {
    std::cout << array_sort_of[i] << " ";
}

// Output: 1.2 3.4
</code>```

ContentLicense: CC BY-SA 2.5

Body:
In exactly the way econoclast demonstrated on the answer you quoted.

std::vector<float> v;
v.push_back(1.2);
v.push_back(3.4);

// &v[0] is a pointer to the first element of the vector.

float* array_sort_of = &v[0];
for (size_t i = 0; i < 2; i++) {
    std::cout << array_sort_of[i] << " ";
}

// Output: 1.2 3.4


问:
Priority queue increase-key opeartion
Here is the pseudocode for increase-key operation assuming we are using Max-heaps

```<code>if key < a[i]
then return an error, because key is less than the current key
else
a[i] = key
while i > 1 and a[parent(i)] < a[i]
swap a[i] with a[parent(i)]
i <- parent(i)
</code>```

According to cormen algorithm book, i can't decrease the key, if i'm using max heaps, but what is stopping me from doing that? i know the if condition won't let me decrease the key.

But let's assume i want to decrease a certain value in a max-heap , after doing that i apply heapify operation, then i can decrease a key even if i'm using max-heaps. which guarantees the properties of max-heap

What is wrong with this assumption?

EDIT
 heapify function is similar to building a heap function from a given array. but instead of building the whole heap from ZERO, we can heapify it from a certain node.

答:
Generally in Max-Priority queue we would like to increase the priority of an element, in order to extract that first.

That is why in general Max-Priority queue API only has Increase-Key method / function and not Decrease-Key.

But you definitely can have a Decrease-Key method / function in your own implementation.

Title: Priority queue increase-key opeartion

Body:
Here is the pseudocode for increase-key operation assuming we are using Max-heaps

if key  1 and a[parent(i)] < a[i]
swap a[i] with a[parent(i)]
i <- parent(i)

According to cormen algorithm book, i can't decrease the key, if i'm using max heaps, but what is stopping me from doing that? i know the if condition won't let me decrease the key.

But let's assume i want to decrease a certain value in a max-heap , after doing that i apply heapify operation, then i can decrease a key even if i'm using max-heaps. which guarantees the properties of max-heap

What is wrong with this assumption?

EDIT
 heapify function is similar to building a heap function from a given array. but instead of building the whole heap from ZERO, we can heapify it from a certain node.


问:
Why argument conversion is not considered when calling a templated function?
I have a template class and a friend operator* function

```<code>StereoSmp<TE> operator* (const StereoSmp<TE>& a, TE b)
</code>```

I use it with TE=float but I need to multiply a StereoSmp<float> * double
I think that should be possibile because it should converts double to float automatically and works but I get the error:

```<code>no match for ‘operator*’ (operand types are ‘StereoSmp<float>’ and
    ‘__gnu_cxx::__alloc_traits<std::allocator<double> >::value_type {aka double}’)
deduced conflicting types for parameter ‘TE’ (‘float’ and ‘double’)
</code>```

Why it doesn't convert double to float automatically? And what can I do to allow the automatic conversion between types?

答:
Keep it simple, silly:

```<code>template<class U>
StereoSmp<TE> operator* (const StereoSmp<TE>& a, U b);
</code>```

or if it applies:

```<code>StereoSmp<TE> a {/* ... */};
double b = /* ... */;
auto c = a * static_cast<float>(b);
</code>```

Why it doesn't convert double to float automatically?

Because template deduction happens before possible conversions are taken into consideration. If you call a*b with a a StereoSmp<float> and b a double, template substitution will fail before a float to double conversion can be considered, and name lookup will continue, until failing short of candidates.

This process is called Template argument deduction.

Body:
I have a template class and a friend operator* function

StereoSmp<TE> operator* (const StereoSmp<TE>& a, TE b)

I use it with TE=float but I need to multiply a StereoSmp<float> * double
I think that should be possibile because it should converts double to float automatically and works but I get the error:

no match for ‘operator*’ (operand types are ‘StereoSmp<float>’ and
    ‘__gnu_cxx::__alloc_traits<std::allocator<double> >::value_type {aka double}’)
deduced conflicting types for parameter ‘TE’ (‘float’ and ‘double’)

Why it doesn't convert double to float automatically? And what can I do to allow the automatic conversion between types?

Body:
Keep it simple, silly:

template<class U>
StereoSmp<TE> operator* (const StereoSmp<TE>& a, U b);

or if it applies:

StereoSmp<TE> a {/* ... */};
double b = /* ... */;
auto c = a * static_cast<float>(b);

Why it doesn't convert double to float automatically?

Because template deduction happens before possible conversions are taken into consideration. If you call a*b with a a StereoSmp<float> and b a double, template substitution will fail before a float to double conversion can be considered, and name lookup will continue, until failing short of candidates.

This process is called Template argument deduction.


问:
Connect to database using dependency injection
I am trying to learn how to use dependency injection, but I have some trouble when it comes to my database. This is my process so far:

I have an MVC project where the controllers use different repositories from my classlibrary.
All repositories use the same database.

At first, I used SimpleInjector to register the Repositories Application_start method:

```<code>var container = new Container();
container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();
var client = new GraphClient(uri, username, password);
container.Register<IRepoA>(() => new RepoA(client);
container.Register<IRepoB>(() => new RepoB(client);
container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
container.Verify();

DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
</code>```

And in every method, I did like this:

```<code>  client.Connect();
  client.performSomeQuery();
  client.Dispose();
</code>```

This works, but it means that I am reconnecting to the database every single time I call a method.
To avoid this a moved the connect-call to here:

```<code>var container = new Container();
container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();
var client = new GraphClient(uri, username, password);
client.Connect();
container.Register<IRepoA>(() => new RepoA(client);
container.Register<IRepoB>(() => new RepoB(client);
container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
container.Verify();
</code>```

But then I never get my connection disposed.

I thought now is to register my databaseclient;

```<code>container.RegisterSingleton(() =>
{
    var client = new GraphClient(uri, username, password);
    client.Connect();
    return client;
});
</code>```

And then inject it like this:

```<code>container.Register<IRepoA>(() => new RepoA(container.GetInstance<GraphClient>()));
</code>```

Is this the correct way to do it?

Is it corretly understood that the connection will get disposed by the end of the containers lifetime?

I do get a "Implicitly captured closure: container" when I register the client.

答:
there is more than one way to do things ... so asking for THE correct way might get you on the wrong path sometimes ...

but here is what i'd do in your case ...

i would introduce a pattern called unit-of-work ... think of it as a business transaction

you open a unit of work and within its lifetime you perform various DB interactions, possibly all within one database transaction. All those interactions may spread across different repositories. if your whole batch of interactions is done without errors that would require a rollback, you declare the unit of work complete and leave its scope (scope as in a using(...) scope)

if there is an error you do not declare it complete before its lifetime ends ...

on the end of lifetime of your unit of work, you can either commit or roll back all underlaying db transactions (usually it's only one) depending on the fact if complete was declared or not

this unit of work object usually also holds my db connection object(s) and provides connections to repositories

again with dependency injection, you can have factory methods that provide different db connections based on the interface the repository requests during instantiation ...

usually the first repo that needs a connection causes the factory to create one and open it (optionally you can have different connections based on the used repos) while the second repo that asks for a connection gets a connection that has been created and opened before ...

the end of the unit of work (see IDisposable) also means the end of the connectionfactory ... end of connectionfactory means the end of open connections and repos ... since the later are instantiated insied of a using block, and based on the used resource, they should never leave said block

Body:
I am trying to learn how to use dependency injection, but I have some trouble when it comes to my database. This is my process so far:

I have an MVC project where the controllers use different repositories from my classlibrary.
All repositories use the same database.

At first, I used SimpleInjector to register the Repositories Application_start method:

var container = new Container();
container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();
var client = new GraphClient(uri, username, password);
container.Register<IRepoA>(() => new RepoA(client);
container.Register<IRepoB>(() => new RepoB(client);
container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
container.Verify();

DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));

And in every method, I did like this:

  client.Connect();
  client.performSomeQuery();
  client.Dispose();

This works, but it means that I am reconnecting to the database every single time I call a method.
To avoid this a moved the connect-call to here:

var container = new Container();
container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();
var client = new GraphClient(uri, username, password);
client.Connect();
container.Register<IRepoA>(() => new RepoA(client);
container.Register<IRepoB>(() => new RepoB(client);
container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
container.Verify();

But then I never get my connection disposed.

I thought now is to register my databaseclient;

container.RegisterSingleton(() =>
{
    var client = new GraphClient(uri, username, password);
    client.Connect();
    return client;
});

And then inject it like this:

container.Register<IRepoA>(() => new RepoA(container.GetInstance<GraphClient>()));

Is this the correct way to do it?

Is it corretly understood that the connection will get disposed by the end of the containers lifetime?

I do get a "Implicitly captured closure: container" when I register the client.


问:
How to replace a part of a string with zeroes?
I need to replace part of a string with zeroes. To be more specific third to sixth position should be zeroes.

Example:

I have 123456789

I need 120000789

Any help would be appreciated!

Thanks.

答:
The simplest way in Oracle is probably to just reconstruct the string:</p>

```<code>select substr(col, 1, 2) || '0000' || substr(col, 7)
</code>```

Body:
The simplest way in Oracle is probably to just reconstruct the string:

select substr(col, 1, 2) || '0000' || substr(col, 7)


问:
Algorithm to correct the floating point precision error in JavaScript
You can find a lot about Floating Point Precision Errors and how to avoid them in Javascript, for example "How to deal with floating point number precision in JavaScript?", who deal with the problem by just rounding the number to a fixed amount of decimal places.

My problem is slightly different, I get numbers from the backend (some with the rounding error) and want to display it without the error.

Of course I could just round the number to a set number of decimal places with value.toFixed(X). The problem is, that the numbers can range from 0.000000001 to 1000000000, so I can never know for sure, how many decimal places are valid.

(See this Fiddle for my unfruitful attempts)
Code :

```<code>var a = 0.3;
var b = 0.1;
var c = a - b; // is 0.19999999999999998, is supposed to be 0.2
// c.toFixed(2)  = 0.20
// c.toFixed(4)  = 0.2000
// c.toFixed(5)  = 0.200000

var d = 0.000003;
var e = 0.000002;
var f = d - e; // is 0.0000010000000000000002 is supposed to be 0.000001
// f.toFixed(2)  = 0.00
// f.toFixed(4)  = 0.0000
// f.toFixed(5)  = 0.000001

var g = 0.0003;
var h = 0.0005;
var i = g + h; // is 0.0007999999999999999, is supposed to be 0.0008
// i.toFixed(2)  = 0.00
// i.toFixed(4)  = 0.0008
// i.toFixed(5)  = 0.000800
</code>```

My Question is now, if there is any algorithm, that intelligently detects how many decimal places are reasonable and rounds the numbers accordingly?

答:
When a decimal numeral is rounded to binary floating-point, there is no way to know, just from the result, what the original number was or how many significant digits it had. Infinitely many decimal numerals will round to the same result.

However, the rounding error is bounded. If it is known that the original number had at most a certain number of digits, then only decimal numerals with that number of digits are candidates. If only one of those candidates differs from the binary value by less than the maximum rounding error, then that one must be the original number.

If I recall correctly (I do not use JavaScript regularly), JavaScript uses IEEE-754 64-bit binary. For this format, it is known that any 15-digit decimal numeral may be converted to this binary floating-point format and back without error. Thus, if the original input was a decimal numeral with at most 15 significant digits, and it was converted to 64-bit binary floating-point (and no other operations were performed on it that could have introduced additional error), and you format the binary floating-point value as a 15-digit decimal numeral, you will have the original number.

The resulting decimal numeral may have trailing zeroes. It is not possible to know (from the binary floating-point value alone) whether those were in the original numeral.

Body:
You can find a lot about Floating Point Precision Errors and how to avoid them in Javascript, for example "How to deal with floating point number precision in JavaScript?", who deal with the problem by just rounding the number to a fixed amount of decimal places.

My problem is slightly different, I get numbers from the backend (some with the rounding error) and want to display it without the error.

Of course I could just round the number to a set number of decimal places with value.toFixed(X). The problem is, that the numbers can range from 0.000000001 to 1000000000, so I can never know for sure, how many decimal places are valid.

(See this Fiddle for my unfruitful attempts)
Code :

var a = 0.3;
var b = 0.1;
var c = a - b; // is 0.19999999999999998, is supposed to be 0.2
// c.toFixed(2)  = 0.20
// c.toFixed(4)  = 0.2000
// c.toFixed(5)  = 0.200000

var d = 0.000003;
var e = 0.000002;
var f = d - e; // is 0.0000010000000000000002 is supposed to be 0.000001
// f.toFixed(2)  = 0.00
// f.toFixed(4)  = 0.0000
// f.toFixed(5)  = 0.000001

var g = 0.0003;
var h = 0.0005;
var i = g + h; // is 0.0007999999999999999, is supposed to be 0.0008
// i.toFixed(2)  = 0.00
// i.toFixed(4)  = 0.0008
// i.toFixed(5)  = 0.000800

My Question is now, if there is any algorithm, that intelligently detects how many decimal places are reasonable and rounds the numbers accordingly?


问:
r timezone warning on mac
I've been getting annoying time zone warnings when I run a script with POSIX commands to I decided to investigate. When I run the following commands on startup

```<code>Sys.time()
Sys.Date()
Sys.timezone()
</code>```

I get

```<code>> date()
[1] "Mon Nov 27 09:10:32 2017"
> Sys.time()
[1] "2017-11-27 16:10:51 GMT"
> Sys.Date()
[1] "2017-11-27"
> Sys.timezone()
[1] NA
>
</code>```

When I look under the Date & Time Zone tab in my mac settings, I see that the time zone is set correctly to Mountain Standard Time. Finally, when I first run some code that looks for time zone information I get the following warning message

```<code>Warning messages:
1: In as.POSIXlt.POSIXct(x, tz) :
  unknown timezone 'zone/tz/2017c.1.0/zoneinfo/America/Denver'
</code>```

As far as I can tell I don't have a path on my mac that looks like "zone/tz/..." so the question is how to get POSIX looking in the correct place(s) for timezone information.

答:
According to the new features list in R 3.4.3, released Nov 30 2017,

A workaround has been added for the changes in location of
      time-zone files in macOS 10.13 'High Sierra' and again in
      10.13.1, so the default time zone is deduced correctly from the
      system setting when R is configured with --with-internal-tzcode
      (the default on macOS).

MRO 3.4.3 will be available on 2018-01-10 for those using Microsoft's version of R.

Title: r timezone warning on mac

Body:
I've been getting annoying time zone warnings when I run a script with POSIX commands to I decided to investigate. When I run the following commands on startup

Sys.time()
Sys.Date()
Sys.timezone()

I get

> date()
[1] "Mon Nov 27 09:10:32 2017"
> Sys.time()
[1] "2017-11-27 16:10:51 GMT"
> Sys.Date()
[1] "2017-11-27"
> Sys.timezone()
[1] NA
>

When I look under the Date & Time Zone tab in my mac settings, I see that the time zone is set correctly to Mountain Standard Time. Finally, when I first run some code that looks for time zone information I get the following warning message

Warning messages:
1: In as.POSIXlt.POSIXct(x, tz) :
  unknown timezone 'zone/tz/2017c.1.0/zoneinfo/America/Denver'

As far as I can tell I don't have a path on my mac that looks like "zone/tz/..." so the question is how to get POSIX looking in the correct place(s) for timezone information.


问:
Figuring which design pattern to use?
In most radio devices, we can configure the wave which we want to explore and listen to stations using the demodulation mode compatible with this type.

There are at least two types AM and FM. We can model the radio device in this case as the following:

```<code>class RadioDevice {
    void demodulate (String m) {
        if(m.equals("FM")
            /* FM modelation */
        else if(m.equals("AM")
            /* AM modelation */
    }
}
</code>```

How can I apply the strategy pattern in this case?

答:
This is not a good use case for Strategy design pattern, its simple inheritance case. Strategy is used where the state of the object does not change but different algorithms apply at different times. e.g. Paypackage computation for different roles of employees (e.g. Temporary, Permanent etc.). Important point here is Temporary employee can become Permanent one day.

In the above case AM will never become FM in its life time. hence Strategy is not right pattern for it. These are (probably) different classes with common behavior (if present) can be shifted to base class. If they show a common contract with clients then even interface will do the task.

Title: Figuring which design pattern to use?

Body:
In most radio devices, we can configure the wave which we want to explore and listen to stations using the demodulation mode compatible with this type.

There are at least two types AM and FM. We can model the radio device in this case as the following:

class RadioDevice {
    void demodulate (String m) {
        if(m.equals("FM")
            /* FM modelation */
        else if(m.equals("AM")
            /* AM modelation */
    }
}

How can I apply the strategy pattern in this case?


问:
Is it possible to modify fields using a LINQ expression without using a SELECT?
I am using LINQ to populate a list of PhraseSource. Following this I am using a foreach to modify the list:

```<code>List<PhraseSource> phraseSources = App.DB.db1.Table<PhraseSource>().ToList();

List<PhraseSource> phraseSources2 = phraseSources
    .Where(p => categorySources.Any(c => c.Id == p.CategoryId)).ToList();

foreach (var item in phraseSources2)
{
    item.OneHash = Math.Abs(item.Id.GetHashCode() % 10);
    item.TwoHash = Math.Abs(item.Id.GetHashCode() % 100);
}
</code>```

My knowledge of LINQ is pretty limited and this was the code given to me.

Is there a way I could combine the foreach into the LINQ expression or must I use a foreach in this way to modify the data?  Note that I think I could do the with a SELECT but I am wondering if there is another way as PhraseSource has a lot of fields.

答:
LINQ is to query a datasource, not to modify it. It is strongly recommended to not abuse LINQ to modify it. In this case you have a list so you could use List.ForEach:

```<code>phraseSources2.ForEach(item => {
    item.OneHash = Math.Abs(item.Id.GetHashCode() % 10);
    item.TwoHash = Math.Abs(item.Id.GetHashCode() % 100);
});
</code>```

Although i don't see the benefit over foreach.

For what it's worth, you can write an extension which allows that with any sequence:

```<code>public static void ForEachDo<T>(this IEnumerable<T> seq, Action<T> doWithEveryItem, Action doIfEmpty = null)
{
    bool isEmpty = true;
    foreach (T item in seq)
    {
        isEmpty = false;
        doWithEveryItem(item);
    }
    if (isEmpty && doIfEmpty != null)
        doIfEmpty();
}
</code>```

Now you could use it even if it's not a list:

```<code>var phraseSources2 = phraseSources.Where(p => categorySources.Any(c => c.Id == p.CategoryId));
phraseSources2.ForEachDo(item=> {
    item.OneHash = Math.Abs(item.Id.GetHashCode() % 10);
    item.TwoHash = Math.Abs(item.Id.GetHashCode() % 100);
})
</code>```

But again, foreach is the perfect tool for this job.

Body:
I am using LINQ to populate a list of PhraseSource. Following this I am using a foreach to modify the list:

List<PhraseSource> phraseSources = App.DB.db1.Table<PhraseSource>().ToList();

List<PhraseSource> phraseSources2 = phraseSources
    .Where(p => categorySources.Any(c => c.Id == p.CategoryId)).ToList();

foreach (var item in phraseSources2)
{
    item.OneHash = Math.Abs(item.Id.GetHashCode() % 10);
    item.TwoHash = Math.Abs(item.Id.GetHashCode() % 100);
}

My knowledge of LINQ is pretty limited and this was the code given to me.

Is there a way I could combine the foreach into the LINQ expression or must I use a foreach in this way to modify the data?  Note that I think I could do the with a SELECT but I am wondering if there is another way as PhraseSource has a lot of fields.

Body:
LINQ is to query a datasource, not to modify it. It is strongly recommended to not abuse LINQ to modify it. In this case you have a list so you could use List.ForEach:

phraseSources2.ForEach(item => {
    item.OneHash = Math.Abs(item.Id.GetHashCode() % 10);
    item.TwoHash = Math.Abs(item.Id.GetHashCode() % 100);
});

Although i don't see the benefit over foreach.

For what it's worth, you can write an extension which allows that with any sequence:

public static void ForEachDo<T>(this IEnumerable<T> seq, Action<T> doWithEveryItem, Action doIfEmpty = null)
{
    bool isEmpty = true;
    foreach (T item in seq)
    {
        isEmpty = false;
        doWithEveryItem(item);
    }
    if (isEmpty && doIfEmpty != null)
        doIfEmpty();
}

Now you could use it even if it's not a list:

var phraseSources2 = phraseSources.Where(p => categorySources.Any(c => c.Id == p.CategoryId));
phraseSources2.ForEachDo(item=> {
    item.OneHash = Math.Abs(item.Id.GetHashCode() % 10);
    item.TwoHash = Math.Abs(item.Id.GetHashCode() % 100);
})

But again, foreach is the perfect tool for this job.


问:
Creating a scheduled reboot task every Saturday of the week
I have no issues setting up a scheduled task every week (Saturday) at 3pm, however there is a requirement that if the last day of the month falls on a Saturday, the reboot has to be rolled over to Sunday at 3pm.

This is the part I am unsure of, as task scheduler doesn't appear to have an exclude option, so wondering what my options are?

答:
Here is the same concept that Matsnow provided but done as a batch file.  Powershell has lots of object oriented functions builtin so the batch file is a bit more code.</p>

```<code>@Echo off

REM Get Date and Time
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set yyyy=%dt:~0,4%
set mm=%dt:~4,2%
set dd=%dt:~6,2%

REM Get Last Day of month
call :DaysOfMonth %yyyy% %mm%

IF "%lastday%"=="%dd%" (
    shutdown /r /t 86400
) else (
    shutdown /r /t 0
)
GOTO :EOF

:DaysOfMonth Year Month
setlocal DisableDelayedExpansion
set /a "yy = %~1, mm = 100%~2 %% 100"
set /a "n = 30 + !(((mm & 9) + 6) %% 7) + !(mm ^ 2) * (!(yy %% 4) - !(yy %% 100) + !(yy %% 400) - 2)"
endlocal &set lastday=%n%
GOTO :EOF
</code>```

Body:
Here is the same concept that Matsnow provided but done as a batch file.  Powershell has lots of object oriented functions builtin so the batch file is a bit more code.

@Echo off

REM Get Date and Time
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set yyyy=%dt:~0,4%
set mm=%dt:~4,2%
set dd=%dt:~6,2%

REM Get Last Day of month
call :DaysOfMonth %yyyy% %mm%

IF "%lastday%"=="%dd%" (
    shutdown /r /t 86400
) else (
    shutdown /r /t 0
)
GOTO :EOF

:DaysOfMonth Year Month
setlocal DisableDelayedExpansion
set /a "yy = %~1, mm = 100%~2 %% 100"
set /a "n = 30 + !(((mm & 9) + 6) %% 7) + !(mm ^ 2) * (!(yy %% 4) - !(yy %% 100) + !(yy %% 400) - 2)"
endlocal &set lastday=%n%
GOTO :EOF


问:
xcode storyboard mirroring effect
Am using Xcode 9.1 and my Xcode error while dragging objects from object panel in storyboard its mirroring automatically as shown in picture .need help in solving this ! </p>

答:
Very odd. At first I thought it was simply rendering for a RtL locale but I don't imagine the chrome around the rendered view should be mirrored as well. Out of curiosity are you testing a Right-to-Left locale? If so, does this persist when that preference is disabled?

Otherwise I'd try cleaning the project, restarting Xcode, and removing your .xcuserdatad file, in that order.

Title: xcode storyboard mirroring effect


问:
Optimal solution for: All possible acyclic paths in a graph problem
I am dealing with undirected graph. I need to find all possible acyclic paths within a graph:

```<code>with G(V,E)
find all subsets of V that are acyclic paths
</code>```

I am using either python scipy or matlab - whichever would be appropriate.
Is there any clever solution for this?

I'm trying to achieve it with a breadth-first search (see wiki)

I also have this toolbox in matlab: http://www.mathworks.com/matlabcentral/fileexchange/4266-grtheory-graph-theory-toolbox but it seems there's no straightforward solution for my problem.

PS. The problem practically is stated as: Transit Network Design Problem: Find such a transport network that minimizes cost of passangers and operators (i.e. optimal subway network for urban area)

Thanks in advance
Rafal

答: Do you need only the shortest paths between all pairs of vertices, or really all paths?

Body:
I am dealing with undirected graph. I need to find all possible acyclic paths within a graph:

with G(V,E)
find all subsets of V that are acyclic paths

I am using either python scipy or matlab - whichever would be appropriate.
Is there any clever solution for this?

I'm trying to achieve it with a breadth-first search (see wiki)

I also have this toolbox in matlab: http://www.mathworks.com/matlabcentral/fileexchange/4266-grtheory-graph-theory-toolbox but it seems there's no straightforward solution for my problem.

PS. The problem practically is stated as: Transit Network Design Problem: Find such a transport network that minimizes cost of passangers and operators (i.e. optimal subway network for urban area)

Thanks in advance
Rafal


问:
get status and edit query limit in Java Client for Google Maps Services
I want geocode some addresses using Java Client for Google Maps Services
My code:

```<code>private static GeoApiContext context = new GeoApiContext.Builder()
                .apiKey(API_KEY)
               .queryRateLimit(50)
                .build();
private static String geocode(String address) throws InterruptedException, ApiException, IOException, JSONException {
        GeocodingResult[] results =  GeocodingApi.geocode(context,
                address).await();
        String latLong = "";
        if(results != null) {
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            latLong = gson.toJson(results[0].geometry);
            String latitude = "";
            String longitude = "";
            JSONObject jsonObject = new JSONObject(latLong);
            JSONObject location = jsonObject.getJSONObject("location");
            latitude = location.getString("lat");
            longitude = location.getString("lng");

            latLong = latitude + "," + longitude;
        }
        return  latLong;
    }
</code>```

I have two problems:

I want get status if i try geocode invalid address since now if i try it i get java.lang.ArrayIndexOutOfBoundsException: length=0; index=0, so i want check status of geocode to avoid this exception.
For exaple I get this exeption for this request:

{
"results" : [],
"status" : "ZERO_RESULTS"
}

I want geocode faster but when i even set queryRateLimit(15000) it run the same slow as before.

So:

How get status of geocoding addres or avoid ArrayIndexOutOfBoundsException.

How can I geocode addresses faster?

答:
I couldn't find method to check the status in JavaDoc of this library, but you can avoid an exception if you also check that an array of results is not empty. Something like if(results != null && results.length > 0) {...} should work for you.

```<code>private static GeoApiContext context = new GeoApiContext.Builder()
           .apiKey(API_KEY)
           .queryRateLimit(50)
           .build();
private static String geocode(String address) throws InterruptedException, ApiException, IOException, JSONException {
    GeocodingResult[] results =  GeocodingApi.geocode(context,
            address).await();
    String latLong = "";
    if(results != null && results.length > 0) {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        latLong = gson.toJson(results[0].geometry);
        String latitude = "";
        String longitude = "";
        JSONObject jsonObject = new JSONObject(latLong);
        JSONObject location = jsonObject.getJSONObject("location");
        latitude = location.getString("lat");
        longitude = location.getString("lng");

        latLong = latitude + "," + longitude;
    }
    return  latLong;
}
</code>```

The Maps API Standard plan is limited to 50 QPS, you cannot set more. If you need a higher quota you have to purchase a Premium plan with additional QPS.

https://developers.google.com/maps/documentation/geocoding/usage-limits

UPDATE

I have figured out how to get status using the Java Client library. Please note that method await() of GeocodingApiRequest can throw ApiException.

https://googlemaps.github.io/google-maps-services-java/v0.9.1/javadoc/com/google/maps/errors/ApiException.html

ApiException has subclases for each possible status (e.g. OverQueryLimitException, ZeroResultsException, UnknownErrorException, etc.)

You can rewrite you code as the following in order to get status

```<code>String status;
try {
    GeocodingResult[] results =  GeocodingApi.geocode(context,
            address).await();
    status = "OK";
} catch(InvalidRequestException e) {
    status = "INVALID_REQUEST";
} catch(NotFoundException e) {
    status = "NOT_FOUND";
} catch(OverDailyLimitException e) {
    status = "OVER_DAILY_LIMIT";
} catch(OverQueryLimitException e) {
    status = "OVER_QUERY_LIMIT";
} catch(RequestDeniedException | AccessNotConfiguredException e) {
    status = "REQUEST_DENIED";
} catch(ZeroResultsException e) {
    status = "ZERO_RESULTS";
} catch(UnknownErrorException e) {
    status = "UNKNOWN_ERROR";
}
</code>```

I hope this answer is useful!

Body:
I want geocode some addresses using Java Client for Google Maps Services
My code:

private static GeoApiContext context = new GeoApiContext.Builder()
                .apiKey(API_KEY)
               .queryRateLimit(50)
                .build();
private static String geocode(String address) throws InterruptedException, ApiException, IOException, JSONException {
        GeocodingResult[] results =  GeocodingApi.geocode(context,
                address).await();
        String latLong = "";
        if(results != null) {
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            latLong = gson.toJson(results[0].geometry);
            String latitude = "";
            String longitude = "";
            JSONObject jsonObject = new JSONObject(latLong);
            JSONObject location = jsonObject.getJSONObject("location");
            latitude = location.getString("lat");
            longitude = location.getString("lng");

            latLong = latitude + "," + longitude;
        }
        return  latLong;
    }

I have two problems:

I want get status if i try geocode invalid address since now if i try it i get java.lang.ArrayIndexOutOfBoundsException: length=0; index=0, so i want check status of geocode to avoid this exception.
For exaple I get this exeption for this request:

{
"results" : [],
"status" : "ZERO_RESULTS"
}

I want geocode faster but when i even set queryRateLimit(15000) it run the same slow as before.

So:

How get status of geocoding addres or avoid ArrayIndexOutOfBoundsException.

How can I geocode addresses faster?

Body:
I couldn't find method to check the status in JavaDoc of this library, but you can avoid an exception if you also check that an array of results is not empty. Something like if(results != null && results.length > 0) {...} should work for you.

private static GeoApiContext context = new GeoApiContext.Builder()
           .apiKey(API_KEY)
           .queryRateLimit(50)
           .build();
private static String geocode(String address) throws InterruptedException, ApiException, IOException, JSONException {
    GeocodingResult[] results =  GeocodingApi.geocode(context,
            address).await();
    String latLong = "";
    if(results != null && results.length > 0) {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        latLong = gson.toJson(results[0].geometry);
        String latitude = "";
        String longitude = "";
        JSONObject jsonObject = new JSONObject(latLong);
        JSONObject location = jsonObject.getJSONObject("location");
        latitude = location.getString("lat");
        longitude = location.getString("lng");

        latLong = latitude + "," + longitude;
    }
    return  latLong;
}

The Maps API Standard plan is limited to 50 QPS, you cannot set more. If you need a higher quota you have to purchase a Premium plan with additional QPS.

https://developers.google.com/maps/documentation/geocoding/usage-limits

UPDATE

I have figured out how to get status using the Java Client library. Please note that method await() of GeocodingApiRequest can throw ApiException.

https://googlemaps.github.io/google-maps-services-java/v0.9.1/javadoc/com/google/maps/errors/ApiException.html

ApiException has subclases for each possible status (e.g. OverQueryLimitException, ZeroResultsException, UnknownErrorException, etc.)

You can rewrite you code as the following in order to get status

String status;
try {
    GeocodingResult[] results =  GeocodingApi.geocode(context,
            address).await();
    status = "OK";
} catch(InvalidRequestException e) {
    status = "INVALID_REQUEST";
} catch(NotFoundException e) {
    status = "NOT_FOUND";
} catch(OverDailyLimitException e) {
    status = "OVER_DAILY_LIMIT";
} catch(OverQueryLimitException e) {
    status = "OVER_QUERY_LIMIT";
} catch(RequestDeniedException | AccessNotConfiguredException e) {
    status = "REQUEST_DENIED";
} catch(ZeroResultsException e) {
    status = "ZERO_RESULTS";
} catch(UnknownErrorException e) {
    status = "UNKNOWN_ERROR";
}

I hope this answer is useful!


问:
After upgrade to macOS Sierra Apache can't do start/stop/restart

After upgrade to macOS Sierra Apache can't do start/stop/restart.

Errors:

```<code>AH00557: httpd: apr_sockaddr_info_get() failed for MacBook-Pro-N.local
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1. Set the 'ServerName' directive globally to suppress this message
</code>```

I tried reinstall apache24 using home-brew. But it didn't fix my problem.
Also I configured httpd.conf, uncommented ServerName localhost. But it didn't help anyway.

Please, help.

答:
Another solution is to change ServerName to localhost.

So first you need to find the location of your httpd.conf Apache configuration file by:

```<code>apachectl -t -D DUMP_INCLUDES
</code>```

then edit it and uncomment or change the line with ServerName (make sure it has the valid server name or it exists in your /etc/hosts file). E.g.

```<code>ServerName localhost
</code>```

Body:
After upgrade to macOS Sierra Apache can't do start/stop/restart.

Errors:

AH00557: httpd: apr_sockaddr_info_get() failed for MacBook-Pro-N.local
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1. Set the 'ServerName' directive globally to suppress this message

I tried reinstall apache24 using home-brew. But it didn't fix my problem.
Also I configured httpd.conf, uncommented ServerName localhost. But it didn't help anyway.

Please, help.

Body:
Another solution is to change ServerName to localhost.

So first you need to find the location of your httpd.conf Apache configuration file by:

apachectl -t -D DUMP_INCLUDES

then edit it and uncomment or change the line with ServerName (make sure it has the valid server name or it exists in your /etc/hosts file). E.g.

ServerName localhost


问:
Cordova file transfer plugin "doesn't support this project's cordova-android version"
I'm having some issues when try to add file transfer plugin to my project, it shows me:

Plugin doesn't support this project's cordova-android version. cordova-android: 6.1.2, failed version requirement: >=6.3.0

And after that I can't build my Android app, just in case, I'm using Cordova 6.2.0 But I tried to use 6.5.0 but the same happens. How can I add properly this plugin?

Thank you all.

答:
Can you try running this command</p>

```<code>ionic cordova platform update android
</code>```

Body:
Can you try running this command

ionic cordova platform update android


问:
Can't use youtube plugin in CDN CKEditor
I want to add youtube plugin in CDN CKEditor, I follow the steps from the doc below

How do I set a plugin on CKEditor when is used from the CDN?

Before adding youtube plugins, textarea looks fine

But after adding youtube plugins, it shows nothing.

My code look like this:

```<code><script src="//cdn.ckeditor.com/4.7.3/full/ckeditor.js"></script>
....
....
<div class="form-group">
   <label class="control-label" for="article_content">Content：</label>
   <textarea class="form-control" type="text" name="article_content"></textarea>
</div>
....
....
....
 <script>
    CKEDITOR.plugins.addExternal( 'youtube', '../public/ckeditor/plugins/youtube/', 'plugin.js' );
    CKEDITOR.replace( 'article_content', {
       extraPlugins: 'youtube'
    });
 </script>
</code>```

Hope someone can give me some advises to fix this problem,

Thanks

答:
If you open a browser console, you'll find the following:

Error: [CKEDITOR.resourceManager.load] Resource name "youtube" was not
  found at
  "https://cdn.ckeditor.com/4.7.3/full/../public/ckeditor/plugins/youtube/plugin.js?t=H8DA".

It appears that with relative paths, CKEditor searches for the plugin inside the CDN. So, instead use absolute paths and CKEditor will search inside your web server, for example if public is inside web server root folder, use:

CKEDITOR.plugins.addExternal( 'youtube', '/public/ckeditor/plugins/youtube/', 'plugin.js' );

Body:
I want to add youtube plugin in CDN CKEditor, I follow the steps from the doc below

How do I set a plugin on CKEditor when is used from the CDN?

Before adding youtube plugins, textarea looks fine

But after adding youtube plugins, it shows nothing.

My code look like this:

....
....

   Content：
   <textarea class="form-control" type="text" name="article_content"></textarea>

....
....
....

Hope someone can give me some advises to fix this problem,

Thanks


问:
How do I base64 encode (decode) in C?
I have binary data in an unsigned char variable.
I need to convert them to PEM base64 in c.
I looked in openssl library but i could not find any function.
Does any body have any idea?</p>

OwnerDisplayName: Granit

Title: How do I base64 encode (decode) in C?

Body:
I wrote one for use with C++, it's very fast, works with streams, free, and open source:

https://tmplusplus.svn.sourceforge.net/svnroot/tmplusplus/trunk/src/

Feel free to use it if it fits your purpose.

Edit: Added code inline by request.

The performance boost is acieved by using a lookup table for encoding and decoding. _UINT8 is an unsigned char on most OS's.

/** Static Base64 character encoding lookup table */
const char CBase64::encodeCharacterTable[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

/** Static Base64 character decoding lookup table */
const char CBase64::decodeCharacterTable[256] = {
    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
    ,-1,62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21
    ,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1,
    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
    ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
    -1,-1,-1};

/*!
\brief Encodes binary data to base 64 character data
\param in The data to encode
\param out The encoded data as characters
*/
void CBase64::Encode(std::istream &in, std::ostringstream &out)
{
    char buff1[3];
    char buff2[4];
    _UINT8 i=0, j;
    while(in.readsome(&buff1[i++], 1))
        if (i==3)
        {
            out << encodeCharacterTable[(buff1[0] & 0xfc) >> 2];
            out << encodeCharacterTable[((buff1[0] & 0x03) << 4) + ((buff1[1] & 0xf0) >> 4)];
            out << encodeCharacterTable[((buff1[1] & 0x0f) << 2) + ((buff1[2] & 0xc0) >> 6)];
            out << encodeCharacterTable[buff1[2] & 0x3f];
            i=0;
        }

    if (--i)
    {
        for(j=i;j<3;j++) buff1[j] = '\0';

        buff2[0] = (buff1[0] & 0xfc) >> 2;
        buff2[1] = ((buff1[0] & 0x03) << 4) + ((buff1[1] & 0xf0) >> 4);
        buff2[2] = ((buff1[1] & 0x0f) << 2) + ((buff1[2] & 0xc0) >> 6);
        buff2[3] = buff1[2] & 0x3f;

        for (j=0;j<(i+1);j++) out << encodeCharacterTable[buff2[j]];

        while(i++<3) out << '=';
    }

}

/*!
\brief Decodes base 64 character data to binary data
\param in The character data to decode
\param out The decoded data
*/
void CBase64::Decode(std::istringstream &in, std::ostream &out)
{
    char buff1[4];
    char buff2[4];
    _UINT8 i=0, j;

    while(in.readsome(&buff2[i], 1) && buff2[i] != '=')
    {
        if (++i==4)
        {
            for (i=0;i!=4;i++)
                buff2[i] = decodeCharacterTable[buff2[i]];

            out << (char)((buff2[0] << 2) + ((buff2[1] & 0x30) >> 4));
            out << (char)(((buff2[1] & 0xf) << 4) + ((buff2[2] & 0x3c) >> 2));
            out << (char)(((buff2[2] & 0x3) << 6) + buff2[3]);

            i=0;
        }
    }

    if (i)
    {
        for (j=i;j<4;j++) buff2[j] = '\0';
        for (j=0;j<4;j++) buff2[j] = decodeCharacterTable[buff2[j]];

        buff1[0] = (buff2[0] << 2) + ((buff2[1] & 0x30) >> 4);
        buff1[1] = ((buff2[1] & 0xf) << 4) + ((buff2[2] & 0x3c) >> 2);
        buff1[2] = ((buff2[2] & 0x3) << 6) + buff2[3];

        for (j=0;j<(i-1); j++) out << (char)buff1[j];
    }
}


问:
xxx.replace() not working properly
At the moment I'm getting code from this api - I'm trying to show list of vehicles in a user friendly way, aka the 'classname', and I've got that running right with the code below:

```<code>var vehicleList = data.vehicles.map(v => v.classname);
var content = vehicleList.join(", ");
document.getElementById("vehicle").textContent = content;
</code>```

However, I want to replace the names of the vehicles with more understandable ones, for example the API might say "B_Quadbike_01" when I really want it to just say "Quadbike" in my html. I've tried doing that with the code below:

```<code>content.replace(/B_Quadbike_01/ig, "Quadbike");
</code>```

However it's just not working - am I doing it right? You can see what I mean with the vehicle list over here how it just looks like a complete mess.

答:
replace not working on the object it returns the result

You should copy it like this:

```<code>content = content.replace(/B_Quadbike_01/gi, "Quadbike");
</code>```

For more information

Title: xxx.replace() not working properly

Body:
At the moment I'm getting code from this api - I'm trying to show list of vehicles in a user friendly way, aka the 'classname', and I've got that running right with the code below:

var vehicleList = data.vehicles.map(v => v.classname);
var content = vehicleList.join(", ");
document.getElementById("vehicle").textContent = content;

However, I want to replace the names of the vehicles with more understandable ones, for example the API might say "B_Quadbike_01" when I really want it to just say "Quadbike" in my html. I've tried doing that with the code below:

content.replace(/B_Quadbike_01/ig, "Quadbike");

However it's just not working - am I doing it right? You can see what I mean with the vehicle list over here how it just looks like a complete mess.

Body:
replace not working on the object it returns the result

You should copy it like this:

content = content.replace(/B_Quadbike_01/gi, "Quadbike");

For more information


问:
Handle CodeIgniter remapping with parameters
I have the following code I added to a MY_Controller that is being extended by all my controllers:

```<code>public function _remap($method, $params = array())
    {//exit($this->router->fetch_class());
        if (array_search($method, $this->private_methods) !== false && !$this->logged_in)
        {
            $this->session->set_flashdata('message', array(
                                                        'message'   =>  'You must login to access the requested area',
                                                        'error'     =>  1
                                                        )
                                        );
            redirect('/');
        }
        else if (method_exists($this, $method))
        {
            $this->$method($params);
        }
        else
        {
            redirect('/');
        }

    }
</code>```

The issue being created is that the call $this->$method($params) is condensing the params in to an Array. So a method such as the following breaks:

```<code>function some_method($param1, $param2, $param3)
</code>```

Is there a way to break this array back into individual items for functions like this?

答:
I have tried this and it worked for me

```<code>public function _remap($method,$params = array())
  {
    if (method_exists($this, $method)) {

      if($method == 'delete_photo' || $method == 'delete_video'){

        call_user_func_array(array($this,$method), $params);
        }

      else{
        $this->$method();
        }
      }
      else {
      $this->index($method);
    }
  }
</code>```

Now you just have to replace "delete_photo" & "delete_video" with your methods names that contains parameters, and of course you can add as much methods as you want.

Body:
I have the following code I added to a MY_Controller that is being extended by all my controllers:

public function _remap($method, $params = array())
    {//exit($this->router->fetch_class());
        if (array_search($method, $this->private_methods) !== false && !$this->logged_in)
        {
            $this->session->set_flashdata('message', array(
                                                        'message'   =>  'You must login to access the requested area',
                                                        'error'     =>  1
                                                        )
                                        );
            redirect('/');
        }
        else if (method_exists($this, $method))
        {
            $this->$method($params);
        }
        else
        {
            redirect('/');
        }

    }

The issue being created is that the call $this->$method($params) is condensing the params in to an Array. So a method such as the following breaks:

function some_method($param1, $param2, $param3)

Is there a way to break this array back into individual items for functions like this?

Body:
I have tried this and it worked for me

public function _remap($method,$params = array())
  {
    if (method_exists($this, $method)) {

      if($method == 'delete_photo' || $method == 'delete_video'){

        call_user_func_array(array($this,$method), $params);
        }

      else{
        $this->$method();
        }
      }
      else {
      $this->index($method);
    }
  }

Now you just have to replace "delete_photo" & "delete_video" with your methods names that contains parameters, and of course you can add as much methods as you want.