问:
cannot send emails with Oracle 11g APEX5
Trying to resolve an issue with sending emails using Oracle APEX5 11g. I've set up the administration settings as per Oracle instructions:

SMTP Host Address - Defines the server address of the SMTP server. By default on installation, this is set to localhost. If you are using another server as an SMTP relay, change this parameter to that server's address.

SMTP Host Port - Defines the port the SMTP server listens to for mail requests. The default setting is 25.

SMTP Authentication Username - If you enter a username, Oracle Application Express authenticates against it when sending emails. Prior to Oracle Database 11g Release 2 (11.2.0.2), only the SMTP authentication scheme "LOGIN" is supported. On newer database versions, all authentication schemes of UTL_SMTP are supported.

SMTP Authentication Password - If you enter a password, Oracle Application Express authenticates against it when sending emails. Prior to Oracle Database 11g Release 2, Release 11.2.0.2, only the SMTP authentication scheme "LOGIN" is supported. On newer database versions, all authentication schemes of UTL_SMTP are supported.

Use SSL/TLS - Beginning with Oracle Database 11g Release 2 (11.2.0.2), Oracle Application Express supports secure SMTP connections. Options include:

Yes - A secure connection with SSL/TLS is made before SMTP communication.

After connection is established - Oracle Application Express sends the SMTP command STARTTLS immediately after the connection is opened.

No - A non-secure connection is opened.

Default Email From Address - Defines the from address for tasks that generate email, such as approving a provision request or resetting a password.

I have also run the 'Granting Connect Privileges' script in sqlplus as sysdba as per Oracle instruction for pre 12c:

```<code>DECLARE
  ACL_PATH  VARCHAR2(4000);
BEGIN
  -- Look for the ACL currently assigned to '*' and give APEX_050000
  -- the "connect" privilege if APEX_050000 does not have the privilege yet.

  SELECT ACL INTO ACL_PATH FROM DBA_NETWORK_ACLS
   WHERE HOST = '*' AND LOWER_PORT IS NULL AND UPPER_PORT IS NULL;

  IF DBMS_NETWORK_ACL_ADMIN.CHECK_PRIVILEGE(ACL_PATH, 'APEX_050000',
     'connect') IS NULL THEN
      DBMS_NETWORK_ACL_ADMIN.ADD_PRIVILEGE(ACL_PATH,
     'APEX_050000', TRUE, 'connect');
  END IF;

EXCEPTION
  -- When no ACL has been assigned to '*'.
  WHEN NO_DATA_FOUND THEN
  DBMS_NETWORK_ACL_ADMIN.CREATE_ACL('power_users.xml',
    'ACL that lets power users to connect to everywhere',
    'APEX_050000', TRUE, 'connect');
  DBMS_NETWORK_ACL_ADMIN.ASSIGN_ACL('power_users.xml','*');
END;
/
COMMIT;
</code>```

Is there more that I need to configure within the application in terms of adding any package, procedure etc..??

Whenever I try to use the APEX send EMail procedure or run standard APEX_MAIL.SEND PL/SQL Code I just cannot get my application to send an email from my SMTP server (either Gmail or BT Internet) I have never tried to set up email from my own PC using a localhost environment as I am doing now, only done it before from a work environment which is all configured. Any advice much appreciated.

答:
Firstly create the ACL and assign it to your user APEX_050000.

Second point, you need to ensure that the connection is using SSL Certificate, and if it is, you have to create a wallet and install the appropiate certificate (.crt) to send emails from external smtp. Here you will find the details:

https://oracle-base.com/articles/misc/oracle-application-express-apex-ldap-authentication

Body:
Trying to resolve an issue with sending emails using Oracle APEX5 11g. I've set up the administration settings as per Oracle instructions:

SMTP Host Address - Defines the server address of the SMTP server. By default on installation, this is set to localhost. If you are using another server as an SMTP relay, change this parameter to that server's address.

SMTP Host Port - Defines the port the SMTP server listens to for mail requests. The default setting is 25.

SMTP Authentication Username - If you enter a username, Oracle Application Express authenticates against it when sending emails. Prior to Oracle Database 11g Release 2 (11.2.0.2), only the SMTP authentication scheme "LOGIN" is supported. On newer database versions, all authentication schemes of UTL_SMTP are supported.

SMTP Authentication Password - If you enter a password, Oracle Application Express authenticates against it when sending emails. Prior to Oracle Database 11g Release 2, Release 11.2.0.2, only the SMTP authentication scheme "LOGIN" is supported. On newer database versions, all authentication schemes of UTL_SMTP are supported.

Use SSL/TLS - Beginning with Oracle Database 11g Release 2 (11.2.0.2), Oracle Application Express supports secure SMTP connections. Options include:

Yes - A secure connection with SSL/TLS is made before SMTP communication.

After connection is established - Oracle Application Express sends the SMTP command STARTTLS immediately after the connection is opened.

No - A non-secure connection is opened.

Default Email From Address - Defines the from address for tasks that generate email, such as approving a provision request or resetting a password.

I have also run the 'Granting Connect Privileges' script in sqlplus as sysdba as per Oracle instruction for pre 12c:

DECLARE
  ACL_PATH  VARCHAR2(4000);
BEGIN
  -- Look for the ACL currently assigned to '*' and give APEX_050000
  -- the "connect" privilege if APEX_050000 does not have the privilege yet.

  SELECT ACL INTO ACL_PATH FROM DBA_NETWORK_ACLS
   WHERE HOST = '*' AND LOWER_PORT IS NULL AND UPPER_PORT IS NULL;

  IF DBMS_NETWORK_ACL_ADMIN.CHECK_PRIVILEGE(ACL_PATH, 'APEX_050000',
     'connect') IS NULL THEN
      DBMS_NETWORK_ACL_ADMIN.ADD_PRIVILEGE(ACL_PATH,
     'APEX_050000', TRUE, 'connect');
  END IF;

EXCEPTION
  -- When no ACL has been assigned to '*'.
  WHEN NO_DATA_FOUND THEN
  DBMS_NETWORK_ACL_ADMIN.CREATE_ACL('power_users.xml',
    'ACL that lets power users to connect to everywhere',
    'APEX_050000', TRUE, 'connect');
  DBMS_NETWORK_ACL_ADMIN.ASSIGN_ACL('power_users.xml','*');
END;
/
COMMIT;

Is there more that I need to configure within the application in terms of adding any package, procedure etc..??

Whenever I try to use the APEX send EMail procedure or run standard APEX_MAIL.SEND PL/SQL Code I just cannot get my application to send an email from my SMTP server (either Gmail or BT Internet) I have never tried to set up email from my own PC using a localhost environment as I am doing now, only done it before from a work environment which is all configured. Any advice much appreciated.


来源: stackexchange

问:
Visualize embedding in tensorboard
I used tensorflow script word2vec_basic.py and I saved the model with tf.summary :
    saver = tf.train.Saver()
    save_path = saver.save(sess, "./w2v/model.ckpt")

I visualize the embedding with tensorboard succesfully but I get indexes of words in the vector

How can I get the words in the embedding instead of indexes in the vocabulary

答:
I used this answer:
linking-tensorboard-embedding-metadata-to-checkpoint

the problem was I tried o call tensorboard with logdir : "./w2v/model.ckpt"
I should called it only with "w2v/"

ContentLicense: CC BY-SA 3.0

Title: Visualize embedding in tensorboard


问:
How to implement "class versioning" (using different version of the same class)
Here is the problem : our main class (say : Contract) change every year. Some properties are added, other are removed. We don't know how it will look next year. It may change a lot or not at all.

On the other hand, we now (new requirement...) have to keep an historic of every contracts. Each time the user update a contract, the whole object must be stored in a backup (e.g. - serialized in a table).

Of course, we must be able to read it back... One option (brutal) is to have a new Contract class every year (Contract2008, Contract2009, ...).

But it would be very cumbersome (and ugly) since a lot of classes depend on Contract - in facts, we would have to create a bunch of new classes every year.

Ever have this kind of problem ? Any suggestion ?

Thanks in advance !

(We're using C# 2.0.)

ADDED : Thank for your answers. We're now asking ourself how we could use a dictionary / an XML file to implement versioning without breaking all the code. Dictionary seems very sexy in this context :o)

答:
Quite likely you don't have to implement properties as C# properties. You could actually store properties in some kind of dictionary and use Get and Set methods to read them/enumerate them. In that case, you can use the same class every year.

If the properties really have to be properties, then I'd recommend building a new assembly with the class every year, and loading the assembly dynamically. You can then use reflection to see what properties are supported by each Contract object. To make your life easier, I'd suggest you have an interface for properties that do not change, and to make it simpler to identify the Contract class in the assembly.

OwnerDisplayName: Sylvain Rodrigue

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Sylvain Rodrigue

OwnerDisplayName: Danut Enachioiu


问:
How can i deploy kubernetes for trial purpose? (sandbox kind of environment)
Links suggested i use minikube to install kubernetes. However i am confused if i should install this on my ubuntu host machine or on the vm provisioned with virtual box running on this host machine.
I want to know the pre-requisites for the install and how to go about it.
I am a newbie to kubernetes and pretty confused on how to go about it.</p>

答:
You can try Kubernetes right away with Minikube. It will take just a few minutes to see Kubernetes running on your laptop or desktop. I tried it on my laptop with Ubuntu 16.04. I put it here https://gitlab.com/abushoeb/kubernetes/ but for your convenience, you can just follow the following steps:

How to install Kubernetes

You need to install 3 components

Virtualbox https://tecadmin.net/install-oracle-virtualbox-on-ubuntu/

Kubectl https://kubernetes.io/docs/tasks/tools/install-kubectl/

Minikube https://github.com/kubernetes/minikube/releases https://github.com/kubernetes/minikube

Install Virtual Box

$ sudo nano /etc/apt/sources.list (add followin line to your sources.list if you haven't already)
deb http://download.virtualbox.org/virtualbox/debian xenial contrib
$ wget -q https://www.virtualbox.org/download/oracle_vbox_2016.asc -O- | sudo apt-key add -
$ wget -q https://www.virtualbox.org/download/oracle_vbox.asc -O- | sudo apt-key add -
$ sudo apt-get update
$ sudo apt-get install virtualbox-5.1

Install Kubectl

$ curl -LO https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl
$ chmod +x ./kubectl
$ sudo mv ./kubectl /usr/local/bin/kubectl

Install Minikube

$ curl -Lo minikube https://storage.googleapis.com/minikube/releases/v0.20.0/minikube-linux-amd64
$ chmod +x minikube
$ sudo mv minikube /usr/local/bin/

Minikube Commands

start k8 cluster $ minikube start
or start specific version of k8 $ minikube start --kubernetes-version="v1.5.2"
or start with a flag enabled $ minikube start --kubernetes-version="v1.5.3" --extra-config kubelet.EnableCustomMetrics=true
enable any addon e.g. heapster $ minikube addons enable heapster
see all k8 versions $ minikube get-k8s-versions
see minikube status $ minikube status
access k8 dashboard $ minikube dashboard (this will open your browser)
stop minikube $ minikube stop

Reference

https://kubernetes.io/docs/getting-started-guides/minikube/

https://github.com/kubernetes/minikube/releases

https://rominirani.com/tutorial-getting-started-with-kubernetes-on-your-windows-laptop-with-minikube-3269b54a226


问:
webGL is not working in Chromium, but it is in Firefox
I have installed Chromium Version 31.0.1650.63 on CentOS release 6.5.

I also have firefox 24.6.0 installed

when I visit a web page in chromium that needs webGL, it says

```<code>Uncaught RuntimeError: The browser supports WebGL, but initialization failed.
</code>```

I have checked the about:flags page the 'disable WebGL' attribute is NOT enabled

I visted

```<code>http://get.webgl.org/
</code>```

Which said: Hmm. While your browser seems to support WebGL, it is disabled or unavailable. If possible, please ensure that you are running the latest drivers for your video card.

Visiting that same sight in firefox gave me the nice spinning cube 'success' page.

I visited

```<code>chrome://gpu/
</code>```

and it said

```<code>WebGL: Unavailable. Hardware acceleration unavailable
WebGL multisampling: Unavailable. Hardware acceleration unavailable
</code>```

Which I find hard to square with the same video card providing webgl support in firefox just fine.

Is this truly a video card driver issue or should I look elsewhere?

答: I had this issue after switching from the proprietary Nvidia to the nouveau drivers, a change which does not seem to have been picked up in the chromium GPU config of my profile. The fix is running chromium-browser --single-process once to reset the GPU configuration.

Body:
I have installed Chromium Version 31.0.1650.63 on CentOS release 6.5.

I also have firefox 24.6.0 installed

when I visit a web page in chromium that needs webGL, it says

Uncaught RuntimeError: The browser supports WebGL, but initialization failed.

I have checked the about:flags page the 'disable WebGL' attribute is NOT enabled

I visted

http://get.webgl.org/

Which said: Hmm. While your browser seems to support WebGL, it is disabled or unavailable. If possible, please ensure that you are running the latest drivers for your video card.

Visiting that same sight in firefox gave me the nice spinning cube 'success' page.

I visited

chrome://gpu/

and it said

WebGL: Unavailable. Hardware acceleration unavailable
WebGL multisampling: Unavailable. Hardware acceleration unavailable

Which I find hard to square with the same video card providing webgl support in firefox just fine.

Is this truly a video card driver issue or should I look elsewhere?


问:
NodeJS require() is generating errors
I'm using

```<code>WebStorm 2017.1.4
Build #WS-171.4694.29, built on June 7, 2017
JRE: 1.8.0_112-release-736-b21 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 8.1 6.3
</code>```

This line:

```<code>var args = require('minimist'){process.argv.slice(2)};
</code>```

Generates such errors:

```<code>SyntaxError: Unexpected token {
    at createScript (vm.js:74:10)
    at Object.runInThisContext (vm.js:116:10)
    at Module._compile (module.js:533:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Module.require (module.js:513:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous>
(C:\Users\AltairSonOfDarkness\WebstormProjects\MMO\server.js:5:1)
</code>```

I do know what the line is supposed to do, but i'm fairly new to node.js, so I have little idea what's happening, and even less on how to fix this.

I'd appreciate help.

答:
You have wrong syntax (this is not allowed in JavaScript), for how to use specific npm module please look on module documentation page on npm page here it will be this address: https://www.npmjs.com/package/minimist.

For your use case please use this syntax.

```<code>var argv = require('minimist')(process.argv.slice(2));
console.dir(argv);
</code>```

Title: NodeJS require() is generating errors

Body:
I'm using

WebStorm 2017.1.4
Build #WS-171.4694.29, built on June 7, 2017
JRE: 1.8.0_112-release-736-b21 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 8.1 6.3

This line:

var args = require('minimist'){process.argv.slice(2)};

Generates such errors:

SyntaxError: Unexpected token {
    at createScript (vm.js:74:10)
    at Object.runInThisContext (vm.js:116:10)
    at Module._compile (module.js:533:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Module.require (module.js:513:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous>
(C:\Users\AltairSonOfDarkness\WebstormProjects\MMO\server.js:5:1)

I do know what the line is supposed to do, but i'm fairly new to node.js, so I have little idea what's happening, and even less on how to fix this.

I'd appreciate help.

Body:
You have wrong syntax (this is not allowed in JavaScript), for how to use specific npm module please look on module documentation page on npm page here it will be this address: https://www.npmjs.com/package/minimist.

For your use case please use this syntax.

var argv = require('minimist')(process.argv.slice(2));
console.dir(argv);


问:
duplicated column name when using join with Zend_Db_table
I have two tables. Both of them have a column named 'title'. When I use the following code snippet to join two tables, I can't access one of the title column.

```<code>    $select = $this->select(Zend_Db_Table::SELECT_WITH_FROM_PART);
    $select->setIntegrityCheck(false);
    $select->join("service","service.id = lecture.service_id");
    return $select;
</code>```

is there a way to access both columns?

答:
You need to rename one of the columns so it doesn't conflict with the other. If you pass an array as the optional 3rd argument to join(), you can specify which columns to retrieve from the joined table. If one or more of the entries in the array is hashed, then the hash key will be used as the property name. With the code below, you can refer to the title column of the service table as "service_title" in your query results. If you want other columns from the service table, add them to the array, with or without hashes as desired.</p>

```<code>$select = $this->select(Zend_Db_Table::SELECT_WITH_FROM_PART);
$select->setIntegrityCheck(false);
$select->join("service", "service.id = lecture.service_id",
              array("service_title" => "service.title");
return $select;
</code>```

Body:
I have two tables. Both of them have a column named 'title'. When I use the following code snippet to join two tables, I can't access one of the title column.

    $select = $this->select(Zend_Db_Table::SELECT_WITH_FROM_PART);
    $select->setIntegrityCheck(false);
    $select->join("service","service.id = lecture.service_id");
    return $select;

is there a way to access both columns?

Body:
You need to rename one of the columns so it doesn't conflict with the other. If you pass an array as the optional 3rd argument to join(), you can specify which columns to retrieve from the joined table. If one or more of the entries in the array is hashed, then the hash key will be used as the property name. With the code below, you can refer to the title column of the service table as "service_title" in your query results. If you want other columns from the service table, add them to the array, with or without hashes as desired.

$select = $this->select(Zend_Db_Table::SELECT_WITH_FROM_PART);
$select->setIntegrityCheck(false);
$select->join("service", "service.id = lecture.service_id",
              array("service_title" => "service.title");
return $select;


问:
list index out of range error while reading csv file in python
I have this code where I am reading a csv file, using NamedTemporaryFile to change the contents of the csv file.

```<code>def update_localcsv():

    ping = ["Yes","No"]
    filename = 'file1.csv'
    tempfile = NamedTemporaryFile(mode= 'w',delete=False)

    with open(filename, 'rt') as csvFile, tempfile:
        reader = csv.reader(csvFile, delimiter=',', quotechar='"')
        writer = csv.writer(tempfile, delimiter=',', quotechar='"')

        for row in reader:

            print(row)
            row[0] = random.choice(ping)

            curr_time = datetime.datetime.time(datetime.datetime.now()).strftime('%I:%M %p')
            row[1] = str(curr_time)
            print('current time: '+str(curr_time))
            print("New ping status = " + str(row))
            writer.writerow(row)

    shutil.move(tempfile.name, filename)
</code>```

When I run this code I can see print(row) printing ['Yes', '04:23 PM'] but then it throws IndexError: list assignment index out of range error at row[0] = random.choice(ping).

This is the current content in my csv file:

```
Yes,04:23 PM

```

Why is this error coming?

NOTE: When I do print(type(row)) I get <class 'list'>. I also see an empty row getting printed:

```<code>['Yes', '04:23 PM']
current time: 05:03 PM
New ping status = ['Yes', '05:03 PM']
[]
</code>```

答:
I was able to reproduce the error you are seeing by adding a newline at the end of my CSV file. I have taken the liberty of editing your question accordingly.

There are a few simple solutions. The most obvious would be to remove the trailing newline at the end of the file.

An more robust would be to skip any empty rows, or rows that do not have the two columns you require. You would still probably want to pass them through to the output writer, so you could do this (print statements omitted):

```<code>if len(row) == 2:
    row[0] = random.choice(ping)
    curr_time = datetime.datetime.time(datetime.datetime.now()).strftime('%I:%M %p')
    row[1] = str(curr_time)
writer.writerow(row)
</code>```

If you want to remove empty lines, you can add a separate case for that:

```<code>if row:
    writer.writerow(row)
</code>```

Since empty arrays are falsy, they will not be passed through.

Body:
I have this code where I am reading a csv file, using NamedTemporaryFile to change the contents of the csv file.

def update_localcsv():

    ping = ["Yes","No"]
    filename = 'file1.csv'
    tempfile = NamedTemporaryFile(mode= 'w',delete=False)

    with open(filename, 'rt') as csvFile, tempfile:
        reader = csv.reader(csvFile, delimiter=',', quotechar='"')
        writer = csv.writer(tempfile, delimiter=',', quotechar='"')

        for row in reader:

            print(row)
            row[0] = random.choice(ping)

            curr_time = datetime.datetime.time(datetime.datetime.now()).strftime('%I:%M %p')
            row[1] = str(curr_time)
            print('current time: '+str(curr_time))
            print("New ping status = " + str(row))
            writer.writerow(row)

    shutil.move(tempfile.name, filename)

When I run this code I can see print(row) printing ['Yes', '04:23 PM'] but then it throws IndexError: list assignment index out of range error at row[0] = random.choice(ping).

This is the current content in my csv file:

Yes,04:23 PM

Why is this error coming?

NOTE: When I do print(type(row)) I get <class 'list'>. I also see an empty row getting printed:

['Yes', '04:23 PM']
current time: 05:03 PM
New ping status = ['Yes', '05:03 PM']
[]

Body:
I was able to reproduce the error you are seeing by adding a newline at the end of my CSV file. I have taken the liberty of editing your question accordingly.

There are a few simple solutions. The most obvious would be to remove the trailing newline at the end of the file.

An more robust would be to skip any empty rows, or rows that do not have the two columns you require. You would still probably want to pass them through to the output writer, so you could do this (print statements omitted):

if len(row) == 2:
    row[0] = random.choice(ping)
    curr_time = datetime.datetime.time(datetime.datetime.now()).strftime('%I:%M %p')
    row[1] = str(curr_time)
writer.writerow(row)

If you want to remove empty lines, you can add a separate case for that:

if row:
    writer.writerow(row)

Since empty arrays are falsy, they will not be passed through.


问:
Sort three numbers in array from least to greatest
I have to create a function that takes 3 numbers. The function should return an array containing the numbers from least to greatest. So far I have this.I know it isn't correct but it's a start.I'm not using native functions as well. Can anyone give me some tips? Appreciate any help.</p>

```<code>   function leastToGreatest (num) {
        var array = [];
        var num1 = 0;
        var num2 = 0;
        var num3 = 0;
        for (var i = 0; i < num.length; i++) {
           if(num[i] < num[i] && num[i] < num[i]) {
                  num[i] = num1;
                  array.push(num1);
           }
           else if(num[i] > num[i] && num[i] < num[i]) {
             num[i] = num2;
             array.push(num2);
           }
           else if(num[i] > num[i] && num[i] > num[i])
             num[i] = num3;
             array.push(num3);
           }
           return array;
     }
     leastToGreatest(2,1,3);
</code>```

答:
If you just want an array with numbers arranged from least to greatest, you can use the sort() method with the following parameter:

```<code>array.sort(function(a,b){return(a-b)});
</code>```

var array = [12,7,18,1];
array.sort(function(a,b){return (a-b)});
console.log(array); //Array should be arranged from least to greatest```

Body:
I have to create a function that takes 3 numbers. The function should return an array containing the numbers from least to greatest. So far I have this.I know it isn't correct but it's a start.I'm not using native functions as well. Can anyone give me some tips? Appreciate any help.

   function leastToGreatest (num) {
        var array = [];
        var num1 = 0;
        var num2 = 0;
        var num3 = 0;
        for (var i = 0; i < num.length; i++) {
           if(num[i] < num[i] && num[i] < num[i]) {
                  num[i] = num1;
                  array.push(num1);
           }
           else if(num[i] > num[i] && num[i] < num[i]) {
             num[i] = num2;
             array.push(num2);
           }
           else if(num[i] > num[i] && num[i] > num[i])
             num[i] = num3;
             array.push(num3);
           }
           return array;
     }
     leastToGreatest(2,1,3);

Body:
If you just want an array with numbers arranged from least to greatest, you can use the sort() method with the following parameter:

array.sort(function(a,b){return(a-b)});

var array = [12,7,18,1];
array.sort(function(a,b){return (a-b)});
console.log(array); //Array should be arranged from least to greatest


问:
Is custom property documentation in tsx files possible?
Similar to how the ide helps with descriptions when i document a function like so.

```<code>/**
 * My Test fn
 * @param a - some description here
 */
function Test(a) {}
</code>```

I would like the ide to show a description in the following scenario but I cannot get it to say anything except "(JSX Attribute) test: boolean"

```<code>interface TestProps {
    /** Some comment here */
    test: boolean;
}
class TestComp extends React.Component<TestProps, any> {
    render() {
        return <span>{this.props.test}</span>
    }
}

const test = (props) => (
    <div><TestComp test={true} /></div>
)
</code>```

Is there any way to get it to show the description when helping out with the test property?

Examples:

Notice the bottom image has -some description here and top doesn't

答:
This has been fixed with TypeScript 2.4 and VSCode 1.14:

VSCode 1.14 ships with TS 2.4 included. You can make sure TS 2.4 is active by checking the TS version in the lower right corner of the VSCode status bar

You can also use a newer version of TS in an older version of VSCode by following these instructions

Please let us know if you run into any other issues with this

Body:
Similar to how the ide helps with descriptions when i document a function like so.

/**
 * My Test fn
 * @param a - some description here
 */
function Test(a) {}

I would like the ide to show a description in the following scenario but I cannot get it to say anything except "(JSX Attribute) test: boolean"

interface TestProps {
    /** Some comment here */
    test: boolean;
}
class TestComp extends React.Component<TestProps, any> {
    render() {
        return {this.props.test}
    }
}

const test = (props) => (

<TestComp test={true} />

)

Is there any way to get it to show the description when helping out with the test property?

Examples:

Notice the bottom image has -some description here and top doesn't


问:
oracle sql: how do i sum different data points in a select statment?
i'm trying to return a sum which is the total of multiple rows of data that are returned. i'm trying to return data that shows an employee, account, and department. i want the sum of salary paid by those three data points. i also want a sum just by employee to show how their salary was distributed. an example is below. any help would be appreciated.

example

答:
Building upon what McGothlin has already posted:</p>

```<code>SELECT employee
  , account
  , dept
  , salary
  , SUM (salary) OVER (PARTITION BY employee) AS "total salary by employee"
  , ROUND(salary / SUM (salary) OVER (PARTITION BY employee) * 100) || '%' AS "salary distribution"
FROM mytable
</code>```

Body:
Building upon what McGothlin has already posted:

SELECT employee
  , account
  , dept
  , salary
  , SUM (salary) OVER (PARTITION BY employee) AS "total salary by employee"
  , ROUND(salary / SUM (salary) OVER (PARTITION BY employee) * 100) || '%' AS "salary distribution"
FROM mytable


问:
Mouseover my title in xaml
Hi all i'm new to this xaml code so excuse me if.i ask some stupid question.
I have a title call conference with hyperlink that take you to conference paye and inside that conference page i have link and table in it.. All I want to so is to create à tooltip that will show the link and some info when the mouse is over it</p>

答:
Most elements in XAML have a ToolTip that you can set in XAML. Tool tips are automatically shown when the mouse hovers of the lement. You didn't specify what type of element your title is, but for this example I will use a Label.

To specify a ToolTip, set up your element like this:

```<code><Label>
     <Label.ToolTip>
         <!-- put the elements you want in the tool tip in here -->
     </Label.ToolTip>
</Label>
</code>```

Hope this helps put you on the right track

Title: Mouseover my title in xaml

Body:
Most elements in XAML have a ToolTip that you can set in XAML. Tool tips are automatically shown when the mouse hovers of the lement. You didn't specify what type of element your title is, but for this example I will use a Label.

To specify a ToolTip, set up your element like this:

<Label>
     <Label.ToolTip>
         <!-- put the elements you want in the tool tip in here -->
     </Label.ToolTip>
</Label>

Hope this helps put you on the right track


问:
[Amazon](500310) Invalid operation: syntax error at or near "S" RedShift Error
I and my team are currently experiencing this problem when we are executing, our Lambda function to insert our json data into Redshift from Amazon S3. We continue to get this error

```<code>java.sql.SQLException: [Amazon](500310) Invalid operation: syntax error at or near "S"
</code>```

This is our code we are executing to run the query, which is being built into a String Builder.

```<code>sql.append("Insert into comparison values ('" + d_timestamp + "','" + d_category + "','" + d_modification_method
+ "','" + d_match + "','" + d_operator_name + "','"
+ d_operator_email + "','" + d_datpoint + "','" + d_datapointcontent + "');");
</code>```

It seems that all the other SQL commands are fine, before we encounter this. Have no idea where this error is and what it is for. Would appreciate any help

答:
Most likely you are hitting data that is escaping out of the single quotes.
Don't create sql statements by appending strings, you'll run into this problem, you'll be open to SQL Injection attacks, and a handful of other issues I'm too lazy to look up right now :p

You're best off constructing a PreparedStatement: https://www.mkyong.com/jdbc/jdbc-preparestatement-example-insert-a-record/

Your anecdote of the day:  Use PreparedStatements 100% of the time, all the time.

Body:
I and my team are currently experiencing this problem when we are executing, our Lambda function to insert our json data into Redshift from Amazon S3. We continue to get this error

java.sql.SQLException: [Amazon](500310) Invalid operation: syntax error at or near "S"

This is our code we are executing to run the query, which is being built into a String Builder.

sql.append("Insert into comparison values ('" + d_timestamp + "','" + d_category + "','" + d_modification_method
+ "','" + d_match + "','" + d_operator_name + "','"
+ d_operator_email + "','" + d_datpoint + "','" + d_datapointcontent + "');");

It seems that all the other SQL commands are fine, before we encounter this. Have no idea where this error is and what it is for. Would appreciate any help


问:
Google maps places api and express error Can't set headers after they are sent
I am trying to use google maps places api to build a simple web application. For now am just inserting the data gotten from the api into my mongodb database.

The google maps places npm module @google/maps has a places method for returning data based on longitude and latitude. What i am trying to achieve is this

When a request is made to the api route it should check the database and return some data.

if the database is empty is should query the google maps places api for the data, insert it into the database and then perform a find request from the database.  here is my [code][1], the error is this :

Error: Can't set headers after they are sent.
        at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:357:11)
        at ServerResponse.header (C:\Express\pizza\node_modules\express\lib\response.js:730:10)
        at ServerResponse.send (C:\Express\pizza\node_modules\express\lib\response.js:170:12)
        at ServerResponse.json (C:\Express\pizza\node_modules\express\lib\response.js:256:15)
        at sendJsonResponse (C:\Express\pizza\app_api\controllers\locations.js:9:9)
        at C:\Express\pizza\app_api\controllers\locations.js:73:39
        at Query.<anonymous> (C:\Express\pizza\node_modules\mongoose\lib\model.js:3800:16)
        at C:\Express\pizza\node_modules\kareem\index.js:277:21
        at C:\Express\pizza\node_modules\kareem\index.js:131:16
        at _combinedTickCallback (internal/process/next_tick.js:73:7)
        at process._tickCallback (internal/process/next_tick.js:104:9)

if there is a better approach to solve my problem I am open to suggestions

var mongoose = require('mongoose');
var Location = require('../models/locations');
var googleMapsClient = require('@google/maps').createClient({
    key: process.env.MAP_API_KEY
});

var sendJsonResponse = function(res, status, content) {
    res.status(status);
    res.json(content);
};
//function to filter data returned from api
var buildLocations = function(results) {
    results === Array;
    var newList = [];
    var j = 3;
    for (var i = 0; i < j; i++) {
        if (results[i].photos) {

            newList.push({
                place_id: results[i].place_id,
                name: results[i].name,
                rating: results[i].rating,
                address: results[i].formatted_address,
                photos: results[i].photos,
                location: results[i].geometry.location
            })
        }
    }
    return newList
}

//function to save data to database from api
var saveToDbFromApi = function(locations,req,res,callback){
    for(var i=0; i<locations.length; i++){
        Location.create({
            name: locations[i].name
        },function(err,locations){
            if(err){
               console.log(err);
            }
            else{
             callback(req,res);
            }
        })
    }
}

module.exports.locationList = function(req, res) {
    Location.find({}, function(err, locations) {
        if (err) {
            console.log(err);
            sendJsonResponse(res, 400, err);
        }
        if (!locations.length) {
            googleMapsClient.places({
                location: [5.526679, -0.48085],
                radius: 50000,
                type: 'restaurant'
            }, function(err, response){
                if(err){
                    sendJsonResponse(res,400,err);
                }
                else{
                    var locations = buildLocations(response.json.results);
                    saveToDbFromApi(locations,req,res,function(req,res){
                        Location.find({},function(err,locations){
                            if(err){
                             console.log(err)
                            }
                            else{
       //this line brings up the 'cant set headers after they are sent error'
                             return   sendJsonResponse(res,200,locations);
                            }
                        })
                    });
                }
            })

        } else {
            sendJsonResponse(res, 200, locations);
        }
    })

}```

答:
The problem is coming from the saveToDbFromApi function. You are iterating through a list called locations adding each location into the database; however, after each location is added, you are running the callback(req,res);. You only want to run the callback once after ALL of the locations are saved to the database.

Here is what you have.

```<code>//function to save data to database from api
var saveToDbFromApi = function(locations,req,res,callback){
    for(var i=0; i<locations.length; i++){
        Location.create({
            name: locations[i].name
        },function(err,locations){
            if(err){
               console.log(err);
            }
            else{
               // this runs the callback on each iteration
               // you need to run the callback once
               callback(req,res);

            }
        })
    }
}
</code>```

Here is what I recommend.

```<code>//function to save data to database from api
var saveToDbFromApi = function(locations,req,res,callback){

    // you might want to validate the locations is an array and has a length
    // for now we will skip of this to show you a solution

    // use a self calling recursive function
    (function saveLocation(i){

        Location.create({
            name: locations[i].name
        }, function(err,locations){

            // throw errors if any
            if(err){
                return console.error(err);
            }

            // check if we have another location to save
            // if we do, use the recursive function to save the next one
            // if not run the callback
            if(i<locations.length){
                saveLocation(i+1);
            } else{
                callback(req,res);
            }

        });

    })(0);

}
</code>```

Body:
The problem is coming from the saveToDbFromApi function. You are iterating through a list called locations adding each location into the database; however, after each location is added, you are running the callback(req,res);. You only want to run the callback once after ALL of the locations are saved to the database.

Here is what you have.

//function to save data to database from api
var saveToDbFromApi = function(locations,req,res,callback){
    for(var i=0; i<locations.length; i++){
        Location.create({
            name: locations[i].name
        },function(err,locations){
            if(err){
               console.log(err);
            }
            else{
               // this runs the callback on each iteration
               // you need to run the callback once
               callback(req,res);

            }
        })
    }
}

Here is what I recommend.

//function to save data to database from api
var saveToDbFromApi = function(locations,req,res,callback){

    // you might want to validate the locations is an array and has a length
    // for now we will skip of this to show you a solution

    // use a self calling recursive function
    (function saveLocation(i){

        Location.create({
            name: locations[i].name
        }, function(err,locations){

            // throw errors if any
            if(err){
                return console.error(err);
            }

            // check if we have another location to save
            // if we do, use the recursive function to save the next one
            // if not run the callback
            if(i<locations.length){
                saveLocation(i+1);
            } else{
                callback(req,res);
            }

        });

    })(0);

}


问:
bash http proxy username password
How to make bash http proxy work if there is @ in password string.

export http_proxy='http://jdoe:P@ssw0rd@proxyserver:8080'.

I am getting curl: (5) Couldn't resolve proxy 'ssword@proxyserver' for the next curl command. Please advise.

答:
You need to URL-encode special characters. @ is %40

```<code>export http_proxy='http://jdoe:P%40ssw0rd@proxyserver:8080'
</code>```

Title: bash http proxy username password

Body:
You need to URL-encode special characters. @ is %40

export http_proxy='http://jdoe:P%40ssw0rd@proxyserver:8080'


问:
Accumulo Tablet Server doesn't utilize all available resources on host machine
I have an Accumulo 1.8.1 cluster made by 12 bare metal servers.

Cluster Configuration:

Each server has 256GB of Ram and 2 x 10 cores CPU.

2 machines are used as masters (running HDFS NameNodes, Accumulo Master and Monitor). The other 10 machines has 12 Disks of 1 TB (11 used by HDFS DataNode process) and are running Accumulo TServer processes. All the machines are connected via a 10Gb network and 3 of them are running ZooKeeper.

Experiment:

I am running heavy ingestion test on this cluster but I have never been able to reach more than 20% CPU usage on each Tablet Server. I am running an ingestion process (using batch writers) on each data node. The table is pre-split in order to have 4 tablets per tablet server. Monitoring the network I have seen that data is received/sent from each node with a peak rate of about 120MB/s / 100MB/s while the aggregated disk write throughput on each tablet servers is around 120MB/s.

Accumulo Configuration:

```<code>"table.file.replication": "2",
"table.compaction.minor.logs.threshold": "10",
"table.durability": "flush",
"table.file.max": "30",
"table.compaction.major.ratio": "9",
"table.split.threshold": "1G"

while the tablet server configuration is:
"tserver.wal.blocksize": "2G",
"tserver.walog.max.size": "8G",
"tserver.memory.maps.max": "32G",
"tserver.compaction.minor.concurrent.max": "50",
"tserver.compaction.major.concurrent.max": "8",
"tserver.total.mutation.queue.max": "50M",
"tserver.wal.replication": "2",
"tserver.compaction.major.thread.files.open.max": "15"

the tablet server heap has been set to 32GB
</code>```

Accumulo performance overview:

Question:

As you can see I have a lot of valleys in which the ingestion rate reaches 0.
What would be a good procedure to identify the bottleneck which causes the 0 ingestion rate periods?
Thanks.

答:
Make sure that you are using the Accumulo native maps.

Increase tserver.total.mutation.queue.max, I'd try 100M to 200M.

Try using snappy compression (or none) instead of the default of gz.

Make sure that accumulo.metadata and accumulo.root tables have a table.durability value of "flush" (I think you are already doing this). See https://accumulo.apache.org/blog/2016/11/02/durability-performance.html for an explanation of how to do this and why it matters.

Try sharing your client code too. You can try to increase the number of BatchWriter threads and further pre-split the table.

Verify that you have set the minor compaction log threshold, WAL max size, and native maps max size as per https://accumulo.apache.org/1.8/accumulo_user_manual.html#_native_maps_configuration

Body:
I have an Accumulo 1.8.1 cluster made by 12 bare metal servers.

Cluster Configuration:

Each server has 256GB of Ram and 2 x 10 cores CPU.

2 machines are used as masters (running HDFS NameNodes, Accumulo Master and Monitor). The other 10 machines has 12 Disks of 1 TB (11 used by HDFS DataNode process) and are running Accumulo TServer processes. All the machines are connected via a 10Gb network and 3 of them are running ZooKeeper.

Experiment:

I am running heavy ingestion test on this cluster but I have never been able to reach more than 20% CPU usage on each Tablet Server. I am running an ingestion process (using batch writers) on each data node. The table is pre-split in order to have 4 tablets per tablet server. Monitoring the network I have seen that data is received/sent from each node with a peak rate of about 120MB/s / 100MB/s while the aggregated disk write throughput on each tablet servers is around 120MB/s.

Accumulo Configuration:

"table.file.replication": "2",
"table.compaction.minor.logs.threshold": "10",
"table.durability": "flush",
"table.file.max": "30",
"table.compaction.major.ratio": "9",
"table.split.threshold": "1G"

while the tablet server configuration is:
"tserver.wal.blocksize": "2G",
"tserver.walog.max.size": "8G",
"tserver.memory.maps.max": "32G",
"tserver.compaction.minor.concurrent.max": "50",
"tserver.compaction.major.concurrent.max": "8",
"tserver.total.mutation.queue.max": "50M",
"tserver.wal.replication": "2",
"tserver.compaction.major.thread.files.open.max": "15"

the tablet server heap has been set to 32GB

Accumulo performance overview:

Question:

As you can see I have a lot of valleys in which the ingestion rate reaches 0.
What would be a good procedure to identify the bottleneck which causes the 0 ingestion rate periods?
Thanks.


问:
How do I filter the dates of the current week from a general date list in Javascript or Typescript?
I have an array that contains multiple Dates and, from this array, I want to return an array that contains only the Dates that belong to the current week. How can I do this?</p>

答:
The only hard part about this is finding the time frame of the week. To do that you could do:

function getWeekDates() {

  let now = new Date();
  let dayOfWeek = now.getDay(); //0-6
  let numDay = now.getDate();

  let start = new Date(now); //copy
  start.setDate(numDay - dayOfWeek);
  start.setHours(0, 0, 0, 0);

  let end = new Date(now); //copy
  end.setDate(numDay + (7 - dayOfWeek));
  end.setHours(0, 0, 0, 0);

  return [start, end];
}

let [start, end] = getWeekDates();

console.log(start.toLocaleString(), end.toLocaleString());```
</div>
</div>
</p>

<p>Now, to filter them:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function filterDatesByCurrentWeek(dates){
   let [start, end] = getWeekDates();
   return dates.filter(d => +d >= +start && +d < +end);
}</code>```

This is assuming your dates are date objects. If they are not, you'll need a way to parse them and get the date object.

Body:
The only hard part about this is finding the time frame of the week. To do that you could do:

function getWeekDates() {

  let now = new Date();
  let dayOfWeek = now.getDay(); //0-6
  let numDay = now.getDate();

  let start = new Date(now); //copy
  start.setDate(numDay - dayOfWeek);
  start.setHours(0, 0, 0, 0);

  let end = new Date(now); //copy
  end.setDate(numDay + (7 - dayOfWeek));
  end.setHours(0, 0, 0, 0);

  return [start, end];
}

let [start, end] = getWeekDates();

console.log(start.toLocaleString(), end.toLocaleString());

Now, to filter them:

function filterDatesByCurrentWeek(dates){
   let [start, end] = getWeekDates();
   return dates.filter(d => +d >= +start && +d < +end);
}

This is assuming your dates are date objects. If they are not, you'll need a way to parse them and get the date object.


问:
How to Set default-character-set to utf8 by mysql 5.58 in mac os 10.6.5
I copy my.cnf to etc folder and [client] [mysqld] set ault-character-set = utf8 but server not start ,In mac os 10.6.5 ,How to Set ddefault-character-set to utf8 by mysql 5.58 ?</p>

答:
```
[client]
default-character-set=charset_name```

source : http://dev.mysql.com/doc/refman/5.0/en/charset-configuration.html

more on charset configuration - http://dev.mysql.com/doc/refman/5.0/en/mysql-command-options.html#option_mysql_default-character-set

Body:
[client]
default-character-set=charset_name

source : http://dev.mysql.com/doc/refman/5.0/en/charset-configuration.html

more on charset configuration - http://dev.mysql.com/doc/refman/5.0/en/mysql-command-options.html#option_mysql_default-character-set


问:
Cannot Pub or Sub on AWS IoT using MQTT over Websockets
I can successfully connect to AWS IoT using MQTT over Websockets. But when publishing or subscribing, the connection is terminated. I figure it must be a policy/permissions-based issue with AWS, but I am confident that I have the correct permissions.
Here is my setup:

I have a lambda function which creates a signed url using STS assumeRole (permissions in policy will be tighter but I have allowed access to all iot functions on all resources for testing):

```<code>const config = require('./config');
const crypto = require('crypto');
const v4 = require('aws-signature-v4');
const async = require('async');
const util = require('util');
const AWS = require('aws-sdk');

exports.handler = function (event, context) {

var fail = function (err) {
    console.error(err);
    context.fail('Oops, something went wrong with your request');
};

const iot = new AWS.Iot();
const sts = new AWS.STS({region: 'eu-west-1'});
var params = {
    DurationSeconds: 3600,
    ExternalId: Date.now().toString(),
    Policy: JSON.stringify(
        {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Action": [
                        "iot:*",
                    ],
                    "Resource": [
                        "*"
                    ]
                }
            ]
        }
    ),
    RoleArn: "arn:aws:iam::ACC_ID:role/iot_websocket_url_role",
    RoleSessionName: 'expo-' + Date.now()
};

sts.assumeRole(params, function(err, stsData) {
    if (err) {
        fail(err);
        return;
    }
    console.log(stsData);

    const AWS_IOT_ENDPOINT_HOST = 'MYENDPOINT.iot.eu-west-1.amazonaws.com';

    var url = v4.createPresignedURL(
        'GET',
        AWS_IOT_ENDPOINT_HOST,
        '/mqtt',
        'iotdata',
        crypto.createHash('sha256').update('', 'utf8').digest('hex'),
        {
            key: stsData.Credentials.AccessKeyId,
            secret: stsData.Credentials.SecretAccessKey,
            protocol: 'wss',
            expires: 3600,
            region: 'eu-west-1'
        }
    );
    url += '&X-Amz-Security-Token=' + encodeURIComponent(stsData.Credentials.SessionToken);
    console.log(url);

    context.succeed({url: url});

});
</code>```

};

The RoleArn provided here has the following policy:

```<code>{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "Stmt1488299712000",
        "Effect": "Allow",
        "Action": [
            "iot:*"
        ],
        "Resource": [
            "*"
        ]
    }
]
</code>```

}

I am using mqtt-elements in a Polymer project for my frontend code.
I have validated that this works correctly by using Mosquitto message broker and Pub/Sub works fine with it.

I have enabled debugging on AWS IoT into CloudWatch. Here is the log:

```<code>2017-03-24 15:58:07.027 TRACEID:REDACTED PRINCIPALID:REDACTED/REDACTED [INFO] EVENT:MQTT Client Connect MESSAGE:Connect Status: SUCCESS

2017-03-24 15:58:07.027 TRACEID:REDACTED PRINCIPALID:REDACTED [INFO] EVENT:MQTT Client Connect MESSAGE: IpAddress: REDACTED SourcePort: 41430

2017-03-24 15:58:07.059 TRACEID:REDACTED PRINCIPALID:REDACTED [INFO] EVENT:MQTTClient Subscribe TOPICNAME:doorLatch MESSAGE:Subscribe Status: AUTHORIZATION_ERROR

2017-03-24 15:58:07.059 TRACEID:REDACTED PRINCIPALID:REDACTED [INFO] EVENT:MQTTClient Subscribe MESSAGE: IpAddress: REDACTED SourcePort: 41430

2017-03-24 15:58:07.068 TRACEID:REDACTED PRINCIPALID:REDACTED [INFO] EVENT:MQTTClient Subscribe TOPICNAME:doorLatch MESSAGE:Subscribe Status: AUTHORIZATION_ERROR

2017-03-24 15:58:07.068 TRACEID:REDACTED PRINCIPALID:REDACTED [INFO] EVENT:MQTTClient Subscribe MESSAGE: IpAddress: REDACTED SourcePort: 41430

2017-03-24 15:58:07.069 TRACEID:REDACTED PRINCIPALID:REDACTED [INFO] EVENT:MQTT Client Disconnect MESSAGE:Disconnect Status: SUCCESS

2017-03-24 15:58:07.069 TRACEID:REDACTED PRINCIPALID:REDACTED [INFO] EVENT:MQTT Client Disconnect MESSAGE: IpAddress: REDACTED SourcePort: 41430
</code>```

So it's clear that the issue is one of Authorization. But the policies in my role + the assumeRole function are clearly very permissive and should enable Pub&Sub of messages to AWS IoT.

I'd appreciate any information on this matter.

Edit: I have also raised this issue on AWS Forums.

答: It is not possible to use STS for an IoT connection. The only way to use MQTT over websockets is to use a Cognito authenticated identity.</p>

Body:
I can successfully connect to AWS IoT using MQTT over Websockets. But when publishing or subscribing, the connection is terminated. I figure it must be a policy/permissions-based issue with AWS, but I am confident that I have the correct permissions.
Here is my setup:

I have a lambda function which creates a signed url using STS assumeRole (permissions in policy will be tighter but I have allowed access to all iot functions on all resources for testing):

const config = require('./config');
const crypto = require('crypto');
const v4 = require('aws-signature-v4');
const async = require('async');
const util = require('util');
const AWS = require('aws-sdk');

exports.handler = function (event, context) {

var fail = function (err) {
    console.error(err);
    context.fail('Oops, something went wrong with your request');
};

const iot = new AWS.Iot();
const sts = new AWS.STS({region: 'eu-west-1'});
var params = {
    DurationSeconds: 3600,
    ExternalId: Date.now().toString(),
    Policy: JSON.stringify(
        {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Action": [
                        "iot:*",
                    ],
                    "Resource": [
                        "*"
                    ]
                }
            ]
        }
    ),
    RoleArn: "arn:aws:iam::ACC_ID:role/iot_websocket_url_role",
    RoleSessionName: 'expo-' + Date.now()
};

sts.assumeRole(params, function(err, stsData) {
    if (err) {
        fail(err);
        return;
    }
    console.log(stsData);

    const AWS_IOT_ENDPOINT_HOST = 'MYENDPOINT.iot.eu-west-1.amazonaws.com';

    var url = v4.createPresignedURL(
        'GET',
        AWS_IOT_ENDPOINT_HOST,
        '/mqtt',
        'iotdata',
        crypto.createHash('sha256').update('', 'utf8').digest('hex'),
        {
            key: stsData.Credentials.AccessKeyId,
            secret: stsData.Credentials.SecretAccessKey,
            protocol: 'wss',
            expires: 3600,
            region: 'eu-west-1'
        }
    );
    url += '&X-Amz-Security-Token=' + encodeURIComponent(stsData.Credentials.SessionToken);
    console.log(url);

    context.succeed({url: url});

});

};

The RoleArn provided here has the following policy:

{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "Stmt1488299712000",
        "Effect": "Allow",
        "Action": [
            "iot:*"
        ],
        "Resource": [
            "*"
        ]
    }
]

}

I am using mqtt-elements in a Polymer project for my frontend code.
I have validated that this works correctly by using Mosquitto message broker and Pub/Sub works fine with it.

I have enabled debugging on AWS IoT into CloudWatch. Here is the log:

2017-03-24 15:58:07.027 TRACEID:REDACTED PRINCIPALID:REDACTED/REDACTED [INFO] EVENT:MQTT Client Connect MESSAGE:Connect Status: SUCCESS

2017-03-24 15:58:07.027 TRACEID:REDACTED PRINCIPALID:REDACTED [INFO] EVENT:MQTT Client Connect MESSAGE: IpAddress: REDACTED SourcePort: 41430

2017-03-24 15:58:07.059 TRACEID:REDACTED PRINCIPALID:REDACTED [INFO] EVENT:MQTTClient Subscribe TOPICNAME:doorLatch MESSAGE:Subscribe Status: AUTHORIZATION_ERROR

2017-03-24 15:58:07.059 TRACEID:REDACTED PRINCIPALID:REDACTED [INFO] EVENT:MQTTClient Subscribe MESSAGE: IpAddress: REDACTED SourcePort: 41430

2017-03-24 15:58:07.068 TRACEID:REDACTED PRINCIPALID:REDACTED [INFO] EVENT:MQTTClient Subscribe TOPICNAME:doorLatch MESSAGE:Subscribe Status: AUTHORIZATION_ERROR

2017-03-24 15:58:07.068 TRACEID:REDACTED PRINCIPALID:REDACTED [INFO] EVENT:MQTTClient Subscribe MESSAGE: IpAddress: REDACTED SourcePort: 41430

2017-03-24 15:58:07.069 TRACEID:REDACTED PRINCIPALID:REDACTED [INFO] EVENT:MQTT Client Disconnect MESSAGE:Disconnect Status: SUCCESS

2017-03-24 15:58:07.069 TRACEID:REDACTED PRINCIPALID:REDACTED [INFO] EVENT:MQTT Client Disconnect MESSAGE: IpAddress: REDACTED SourcePort: 41430

So it's clear that the issue is one of Authorization. But the policies in my role + the assumeRole function are clearly very permissive and should enable Pub&Sub of messages to AWS IoT.

I'd appreciate any information on this matter.

Edit: I have also raised this issue on AWS Forums.


问:
Partial indexes in mongodb / mongoose
In the sparse index documentation I found note about mongodb 3.2 partial indexes

Changed in version 3.2: Starting in MongoDB 3.2, MongoDB provides the
  option to create partial indexes. Partial indexes offer a superset of
  the functionality of sparse indexes. If you are using MongoDB 3.2 or
  later, partial indexes should be preferred over sparse indexes.

Partial indexes are very helpfull and I want to use them in my project. Is it possible use them with mongoose?

答:
Now it's possible natively with Mongoose +4.6.1</p>

```<code>Book.index({user: 1, author: 1, complete: 1}, {unique: true, partialFilterExpression: {complete: true}});
</code>```

Title: Partial indexes in mongodb / mongoose

Body:
Now it's possible natively with Mongoose +4.6.1

Book.index({user: 1, author: 1, complete: 1}, {unique: true, partialFilterExpression: {complete: true}});


问:
Slow prediction: Scikit Gaussian Process classification
Following is the code to evaluate to train a Gaussian Process (GP) and use to classify the images from MNIST dataset.

```<code>import numpy as np

from sklearn.metrics.classification import accuracy_score, log_loss
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF
from sklearn import datasets
from sklearn.datasets import fetch_mldata

import random

SAMPLE_SIZE = 2000

def build_and_optimize(hp_space):
    build_train()
    return

def build_train(hp_space):
    l_scale = hp_space['l_scale']
    bias = hp_space['bias']
    gp_fix = GaussianProcessClassifier(kernel=bias * RBF(length_scale=l_scale), optimizer=None, multi_class='one_vs_rest')

    X_train, X_test, y_train, y_test = prepare_data()

    gp_fix.fit(X_train, y_train)

    print("Log Marginal Likelihood (initial): %.3f"
        % gp_fix.log_marginal_likelihood(gp_fix.kernel_.theta))

    y_ = gp_fix.predict(X_test[0:500])
    print(y_)
    print(y_test[0:500])
    print("Accuracy: %.3f (initial)"
        % (accuracy_score(y_test[0:500], y_)))

    return

def prepare_data():
    mnist = fetch_mldata('MNIST original', data_home='./')
    mnist.keys()

    images = mnist.data
    targets = mnist.target

    X_data = images/255.0
    Y = targets
   shuf = random.sample(range(len(X_data)), SAMPLE_SIZE)

    X_train = []
    for x in shuf: X_train.append(X_data[x])

    y_train = []
    for x in shuf: y_train.append(Y[x])

    c_shuf = set(range(len(X_data))) - set(shuf)

    X_test = []
    for x in c_shuf: X_test.append(X_data[x])

    y_test = []
    for x in c_shuf: y_test.append(Y[x])

    return X_train, X_test, y_train, y_test

if __name__ == "__main__":
    hp_space = {}
    hp_space['l_scale'] = 1.0
    hp_space['bias'] = 1.0

    build_train(hp_space)
</code>```

It seems the training of the model takes decent amount of time. However, the prediction takes ages. Any pointers as what could be the reason?

答:
You could speed up the process by addind n_jobs = -1 as follows:

```<code>gp_fix = GaussianProcessClassifier(kernel=bias * RBF(length_scale=l_scale), optimizer=None, multi_class='one_vs_rest', n_jobs = -1)
</code>```

This way from the documentation:

The number of jobs to use for the computation. If -1 all CPUs are used. If 1 is given, no parallel computing code is used at all, which is useful for debugging. For n_jobs below -1, (n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one are used.

Source: here

Body:
Following is the code to evaluate to train a Gaussian Process (GP) and use to classify the images from MNIST dataset.

import numpy as np

from sklearn.metrics.classification import accuracy_score, log_loss
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF
from sklearn import datasets
from sklearn.datasets import fetch_mldata

import random

SAMPLE_SIZE = 2000

def build_and_optimize(hp_space):
    build_train()
    return

def build_train(hp_space):
    l_scale = hp_space['l_scale']
    bias = hp_space['bias']
    gp_fix = GaussianProcessClassifier(kernel=bias * RBF(length_scale=l_scale), optimizer=None, multi_class='one_vs_rest')

    X_train, X_test, y_train, y_test = prepare_data()

    gp_fix.fit(X_train, y_train)

    print("Log Marginal Likelihood (initial): %.3f"
        % gp_fix.log_marginal_likelihood(gp_fix.kernel_.theta))

    y_ = gp_fix.predict(X_test[0:500])
    print(y_)
    print(y_test[0:500])
    print("Accuracy: %.3f (initial)"
        % (accuracy_score(y_test[0:500], y_)))

    return

def prepare_data():
    mnist = fetch_mldata('MNIST original', data_home='./')
    mnist.keys()

    images = mnist.data
    targets = mnist.target

    X_data = images/255.0
    Y = targets
   shuf = random.sample(range(len(X_data)), SAMPLE_SIZE)

    X_train = []
    for x in shuf: X_train.append(X_data[x])

    y_train = []
    for x in shuf: y_train.append(Y[x])

    c_shuf = set(range(len(X_data))) - set(shuf)

    X_test = []
    for x in c_shuf: X_test.append(X_data[x])

    y_test = []
    for x in c_shuf: y_test.append(Y[x])

    return X_train, X_test, y_train, y_test

if __name__ == "__main__":
    hp_space = {}
    hp_space['l_scale'] = 1.0
    hp_space['bias'] = 1.0

    build_train(hp_space)

It seems the training of the model takes decent amount of time. However, the prediction takes ages. Any pointers as what could be the reason?

Body:
You could speed up the process by addind n_jobs = -1 as follows:

gp_fix = GaussianProcessClassifier(kernel=bias * RBF(length_scale=l_scale), optimizer=None, multi_class='one_vs_rest', n_jobs = -1)

This way from the documentation:

The number of jobs to use for the computation. If -1 all CPUs are used. If 1 is given, no parallel computing code is used at all, which is useful for debugging. For n_jobs below -1, (n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one are used.

Source: here


问:
PdfAWriter is not working for itextsharp 5.5 dll
I am trying to set pdf/A-3B using PdfAWriter in c#. But it showing error. Can Any one help me?

I am getting error during declaration of PdfAWriter.
PdfAWriter writer = PdfAWriter.GetInstance(document, ms, PdfAConformanceLevel.PDF_A_1A);

I attached the screen short of the error.

答:
You need the following DLL: itextsharp.pdfa.dll.

That DLL can be found in the following ZIP file: itextsharp-dll-pdfa.zip

This ZIP file can be downloaded here: itextsharp-all-5.5.11.zip

Make sure that all the DLLs you are using are of the same version. Don't use the 5.5.11 version of the PDF/A DLL with an older version of iText core.


问:
Bukkit: How to get a Players distance to the edge of a circle?
If I have a location within a world selected, and have a "safe zone" around that location that say extends 500 blocks (creating a circle) (this means a player can be within 500 blocks of that location and be "safe"). how can I find the distance from the players location to the nearest safe area? Or what in this case would be the nearest edge of that circle?</p>

答:
To find the distance of a player to a given safe zone you simply need to find their distance to the center of the safe zone and then subtract the radius. This is because the shortest vector to the edge of the circle will be normal to the boundary and therefore parallel to a radius passing through the center of the circle.

Given the (x,y) coordinates of the center of a safe zone, (x1,y1) and the coordinates of the player, (x2,y2), you can calculate the distance to the center of the safe zone like this:

```<code>double distance = Math.sqrt(Math.pow(x1-x2,2) + Math.pow(y1-y2,2));
</code>```

To compare which safe zone you are closest to you could wait to subtract the radius length to prevent wasted calculations.

Sorting through a list of safe zones may look something like this:

```<code>public double distanceToNearestSafeZone(Player player, List<SafeZone> safeZones) {
     double distance;
     double minimumDistance = Double.POSITIVE_INFINITY;
     for(SafeZone safeZone:safeZones) {
          distance = Math.sqrt(Math.pow(player.x-safeZone.x,2) + Math.pow(player.y-safeZone.y,2));
          if(minimumDistance > distance) {
               minimumDistance = distance;
          }
     }
     return minimumDistance - SafeZone.radius;
}
</code>```

In this example the player object has a two public double fields x and y holding the players position. The SafeZone objects have similar fields. SafeZone also has a public static double radius field.

I hope this helps!

Body:
To find the distance of a player to a given safe zone you simply need to find their distance to the center of the safe zone and then subtract the radius. This is because the shortest vector to the edge of the circle will be normal to the boundary and therefore parallel to a radius passing through the center of the circle.

Given the (x,y) coordinates of the center of a safe zone, (x1,y1) and the coordinates of the player, (x2,y2), you can calculate the distance to the center of the safe zone like this:

double distance = Math.sqrt(Math.pow(x1-x2,2) + Math.pow(y1-y2,2));

To compare which safe zone you are closest to you could wait to subtract the radius length to prevent wasted calculations.

Sorting through a list of safe zones may look something like this:

public double distanceToNearestSafeZone(Player player, List<SafeZone> safeZones) {
     double distance;
     double minimumDistance = Double.POSITIVE_INFINITY;
     for(SafeZone safeZone:safeZones) {
          distance = Math.sqrt(Math.pow(player.x-safeZone.x,2) + Math.pow(player.y-safeZone.y,2));
          if(minimumDistance > distance) {
               minimumDistance = distance;
          }
     }
     return minimumDistance - SafeZone.radius;
}

In this example the player object has a two public double fields x and y holding the players position. The SafeZone objects have similar fields. SafeZone also has a public static double radius field.

I hope this helps!


问:
duplicate entries on datagridview
I'd like to find duplicated entries one of the columns on datagridview. After that I need to send an email to users for arrange collection for those duplicated numbers. It doesnt matter how many duplicated numbers we have on column so i dont want to count them, i just need to know all those duplicated numbers itself on column.. I have sorted e-mail already, but i couldnt figure out how i can easily find duplicated entries.

attached a screen shot here, for example on this screen shot i already have four 0's on column, it needs to tell me that " I have duplicated 0 on sending_location" .

Datagridview taking information from MS Access Datasource.

I am using visual studio.

Many thanks!
Charlie

答: If the datagridview is bound to a datasource, is it not easy to find out at the query level or during the databinding event.</p>

Title: duplicate entries on datagridview


问:
Better ways to identify objects not getting garbage collected?

In a nutshell

I have a program that is gradually using more and more memory over time. I am using jmap and jhat to try and diagnose it but am still not quite there.

Background

The program is a long-running server backed by an hbase datastore providing a thrift service to a bunch of other stuff. However, after running for a few days, it will eventually hit the allocated heap limit, and thrash back and forth with nearly all time spent in garbage collection. It would seem references are getting kept to a lot of data somewhere

What I've done so far

After fiddling about with jstat and jconsole some I ended up taking heapdumps with jmap of the running process, and run it through jhat, and the numbers simple don't add up to anywhere near the memory utilisation

jmap -F -dump:live,format=b,file=heap.dump 12765

jmap -F -dump:format=b,file=heap.all 12765

Some stuff off the top of the histogram

```<code>Class   Instance Count  Total Size
class [B     7493    228042570
class java.util.HashMap$Entry    2833152     79328256
class [Ljava.util.HashMap$Entry;     541     33647856
class [Ljava.lang.Object;    303698  29106440
class java.lang.Long     2851889     22815112
class org.apache.hadoop.hbase.KeyValue   303593  13358092
class org.apache.hadoop.hbase.client.Result  303592  9714944
class [I     14074   9146580
class java.util.LinkedList$Entry     303841  7292184
class [Lorg.apache.hadoop.hbase.KeyValue;    303592  7286208
class org.apache.hadoop.hbase.io.ImmutableBytesWritable  305097  4881552
class java.util.ArrayList    302633  4842128
class [Lorg.apache.hadoop.hbase.client.Result;   297     2433488
class [C     5391    320190
</code>```

While the totals here don't add up to it, at the point that heap dump was taken the process was using over 1gb of memory.

The immediate apparent culprit seems like I'm leaving HBase Result and KeyValue entries all over the place. Trying to trace up the references, I eventually hit

```<code>Object at 0x2aab091e46d0

instance of org.apache.hadoop.hbase.ipc.HBaseClient$Call@0x2aab091e46d0 (53 bytes)

Class:

class org.apache.hadoop.hbase.ipc.HBaseClient$Call
Instance data members:

done (Z) : true
error (L) : <null>
id (I) : 57316
param (L) : org.apache.hadoop.hbase.ipc.HBaseRPC$Invocation@0x2aab091e4678 (48 bytes)
this$0 (L) : org.apache.hadoop.hbase.ipc.HBaseClient@0x2aaabfb78f30 (86 bytes)
value (L) : org.apache.hadoop.hbase.io.HbaseObjectWritable@0x2aab092e31c0 (40 bytes)
References to this object:

Other Queries

Reference Chains from Rootset
Exclude weak refs
Include weak refs
Objects reachable from here
</code>```

Help needed:

There seems to be no references to this final HBaseCLient$Call object(or any of the others like it, each which hold a thousand or so keyvalues with all their internal data). Shouldn't it be getting GCed? Am I just misunderstanding how the gc works or the extent to which jhat will verify references? If so what further can I do to track down my "missing" memory? What other steps can I take to track this down?

答:
Check this Java Memory Monitoring article
Link

This May help you to over come your issue
http://java.sun.com/developer/technicalArticles/J2SE/monitoring/

Body:
In a nutshell

I have a program that is gradually using more and more memory over time. I am using jmap and jhat to try and diagnose it but am still not quite there.

Background

The program is a long-running server backed by an hbase datastore providing a thrift service to a bunch of other stuff. However, after running for a few days, it will eventually hit the allocated heap limit, and thrash back and forth with nearly all time spent in garbage collection. It would seem references are getting kept to a lot of data somewhere

What I've done so far

After fiddling about with jstat and jconsole some I ended up taking heapdumps with jmap of the running process, and run it through jhat, and the numbers simple don't add up to anywhere near the memory utilisation

jmap -F -dump:live,format=b,file=heap.dump 12765

jmap -F -dump:format=b,file=heap.all 12765

Some stuff off the top of the histogram

Class   Instance Count  Total Size
class [B     7493    228042570
class java.util.HashMap$Entry    2833152     79328256
class [Ljava.util.HashMap$Entry;     541     33647856
class [Ljava.lang.Object;    303698  29106440
class java.lang.Long     2851889     22815112
class org.apache.hadoop.hbase.KeyValue   303593  13358092
class org.apache.hadoop.hbase.client.Result  303592  9714944
class [I     14074   9146580
class java.util.LinkedList$Entry     303841  7292184
class [Lorg.apache.hadoop.hbase.KeyValue;    303592  7286208
class org.apache.hadoop.hbase.io.ImmutableBytesWritable  305097  4881552
class java.util.ArrayList    302633  4842128
class [Lorg.apache.hadoop.hbase.client.Result;   297     2433488
class [C     5391    320190

While the totals here don't add up to it, at the point that heap dump was taken the process was using over 1gb of memory.

The immediate apparent culprit seems like I'm leaving HBase Result and KeyValue entries all over the place. Trying to trace up the references, I eventually hit

Object at 0x2aab091e46d0

instance of org.apache.hadoop.hbase.ipc.HBaseClient$Call@0x2aab091e46d0 (53 bytes)

Class:

class org.apache.hadoop.hbase.ipc.HBaseClient$Call
Instance data members:

done (Z) : true
error (L) : <null>
id (I) : 57316
param (L) : org.apache.hadoop.hbase.ipc.HBaseRPC$Invocation@0x2aab091e4678 (48 bytes)
this$0 (L) : org.apache.hadoop.hbase.ipc.HBaseClient@0x2aaabfb78f30 (86 bytes)
value (L) : org.apache.hadoop.hbase.io.HbaseObjectWritable@0x2aab092e31c0 (40 bytes)
References to this object:

Other Queries

Reference Chains from Rootset
Exclude weak refs
Include weak refs
Objects reachable from here

Help needed:

There seems to be no references to this final HBaseCLient$Call object(or any of the others like it, each which hold a thousand or so keyvalues with all their internal data). Shouldn't it be getting GCed? Am I just misunderstanding how the gc works or the extent to which jhat will verify references? If so what further can I do to track down my "missing" memory? What other steps can I take to track this down?


问:
What does "unhashable type: 'list'" error mean?
```<code>//database Postgresql

logging_level_ENUM = ['critical', 'error', 'warning', 'info', 'debug']

loglevel = db.Column(postgresql.ENUM(logging_level_ENUM,
                     name='log_level_to_ENUM'),
                     default=logging_level_ENUM[3])
//python module

if i in logging_level_ENUM:
    print i
</code>```

This gives me an error "unhashable type: 'list'". What does that mean and how can I fix that?

答:
Basically, when you create a dictionnary in python (which is most probably happening in your call to the ENUM function), the keys need to be hashable, which often means the collection needs to be immutable (which means they should not be able to be modified).

Here is a more detailed explanation of why this is the case : https://wiki.python.org/moin/DictionaryKeys

As the previous answer states, you probably need to use a hashable collection such as a tuple to solve the problem in your example code.

Body:
//database Postgresql

logging_level_ENUM = ['critical', 'error', 'warning', 'info', 'debug']

loglevel = db.Column(postgresql.ENUM(logging_level_ENUM,
                     name='log_level_to_ENUM'),
                     default=logging_level_ENUM[3])
//python module

if i in logging_level_ENUM:
    print i

This gives me an error "unhashable type: 'list'". What does that mean and how can I fix that?


问:
Add attachment by url to Outlook mail
The context

There is a button on the homepage of each document set in a document library on a SharePoint Online environment. When the button is clicked, an Outlook window opens with the title and body set and all the files in the document set should be added as the attachments.

The code

Here's the code I have so far:

```<code>var olApp = new ActiveXObject("Outlook.Application");
var olNs = olApp.GetNameSpace("MAPI");
var olItem = olApp.CreateItem(0);

var signature = olItem.HTMLBody;
signature.Importance = 2;

olItem.To = "";
olItem.Cc = "";
olItem.Bcc = "";
olItem.Subject = "Pre filled title";
olItem.HTMLBody =
        "<span style='font-size:11pt;'>" +
        "<p>Pre filled body</p>" +
        "</span>";
olItem.HTMLBody += signature;

olItem.Display();
olItem.GetInspector.WindowState = 2;

var docUrl = "https://path_to_site/Dossiers/13245_kort titel/New Microsoft Word Document.docx";
olItem.Attachments.Add(docUrl);
</code>```

The Problem

When I run this code, an Outlook window opens with everything set correctly. But on the line where the attachment is added I get following very vague error message:

SCRIPT8: The operation failed.

I thought it could be the spaces in the url so I replaced them:

```<code>docUrl = docUrl.replace(/ /g, "%20");
</code>```

Also didn't work (same error) and providing all parameters like this also didn't work:

```<code>olItem.Attachments.Add(docUrl, 1, 1, "NewDocument");
</code>```

Passing a path to a local file (e.g. C:/folder/file.txt) or a publicly available url to an image does work. So my guess is it has something to do with permissions or security. Does anybody know how to solve this?

PS: I know using an ActiveX control is not the ideal way of working (browser limitations, security considerations, ...) but the situation is what it is and not in my power to change.

答: You cannot pass a url to MailItem.Attachments.Add in OOM (it does work in Redemption - I am its author - for RDOMail.Attachments.Add). Outlook Object Model only allows a fully qualified path to a local file or a pointer to another item (such as MailItem).

ContentLicense: CC BY-SA 4.0

Title: Add attachment by url to Outlook mail

Body:
The context

There is a button on the homepage of each document set in a document library on a SharePoint Online environment. When the button is clicked, an Outlook window opens with the title and body set and all the files in the document set should be added as the attachments.

The code

Here's the code I have so far:

var olApp = new ActiveXObject("Outlook.Application");
var olNs = olApp.GetNameSpace("MAPI");
var olItem = olApp.CreateItem(0);

var signature = olItem.HTMLBody;
signature.Importance = 2;

olItem.To = "";
olItem.Cc = "";
olItem.Bcc = "";
olItem.Subject = "Pre filled title";
olItem.HTMLBody =
        "" +
        "
Pre filled body
" +
        "";
olItem.HTMLBody += signature;

olItem.Display();
olItem.GetInspector.WindowState = 2;

var docUrl = "https://path_to_site/Dossiers/13245_kort titel/New Microsoft Word Document.docx";
olItem.Attachments.Add(docUrl);

The Problem

When I run this code, an Outlook window opens with everything set correctly. But on the line where the attachment is added I get following very vague error message:

SCRIPT8: The operation failed.

I thought it could be the spaces in the url so I replaced them:

docUrl = docUrl.replace(/ /g, "%20");

Also didn't work (same error) and providing all parameters like this also didn't work:

olItem.Attachments.Add(docUrl, 1, 1, "NewDocument");

Passing a path to a local file (e.g. C:/folder/file.txt) or a publicly available url to an image does work. So my guess is it has something to do with permissions or security. Does anybody know how to solve this?

PS: I know using an ActiveX control is not the ideal way of working (browser limitations, security considerations, ...) but the situation is what it is and not in my power to change.


问:
Oracle Debugging won't work SQL developer 4.2.0.17
I have debugging privs and compiled my packages and package bodies for debug. When I try to launch the debugger, I get the following.  </p>

```<code>Executing PL/SQL: ALTER SESSION SET PLSQL_DEBUG=TRUE
Executing PL/SQL: CALL DBMS_DEBUG_JDWP.CONNECT_TCP( 'XX.XX.XX.XXX', 'YYYYY' )
ORA-30683: failure establishing connection to debugger
ORA-12535: TNS:operation timed out
ORA-06512: at "SYS.DBMS_DEBUG_JDWP", line 68
ORA-06512: at line 1
Process exited.
Disconnecting from the database ZZZ
</code>```

<p>I tried setting DatabaseDebuggerDisableJDWP=true in my ide.properites file (all of them), and it didn't help.  </p>

答:
It looks like I put DatabaseDebuggerDisableJDWP=true too far down in ide.properties file.<br>
When put DatabaseDebuggerDisableJDWP=true  on the first line, it worked.  I also had to make the changes and go in and out of Sql developer several times before the changes stuck.  </p>

Body:
I have debugging privs and compiled my packages and package bodies for debug. When I try to launch the debugger, I get the following.

Executing PL/SQL: ALTER SESSION SET PLSQL_DEBUG=TRUE
Executing PL/SQL: CALL DBMS_DEBUG_JDWP.CONNECT_TCP( 'XX.XX.XX.XXX', 'YYYYY' )
ORA-30683: failure establishing connection to debugger
ORA-12535: TNS:operation timed out
ORA-06512: at "SYS.DBMS_DEBUG_JDWP", line 68
ORA-06512: at line 1
Process exited.
Disconnecting from the database ZZZ

I tried setting DatabaseDebuggerDisableJDWP=true in my ide.properites file (all of them), and it didn't help.

Body:
It looks like I put DatabaseDebuggerDisableJDWP=true too far down in ide.properties file.

When put DatabaseDebuggerDisableJDWP=true  on the first line, it worked.  I also had to make the changes and go in and out of Sql developer several times before the changes stuck.


问:
Send a json with a multiline string instead of \n
I have a string with \n as a join result:

```<code>my_var = ['name','phone','age'].join("\n")
</code>```

I will send this string in the body of a post as a Json:

```<code>def body
  { "str": my_var }
end
</code>```

I want to send the var in multiple lines instead of sending the \n like this:

```<code>"name\nphone\nage"
</code>```

EDIT:
I am sending this string joined with \n to another dev team as a json in the body of my post request to their uri. But they don't want to receive a string with \n and replace or translate there. They want to recieve in multiple lines.

答:
That's the expected format of the JSON. You should not be including a new line in the values, but using the '\n' character.

```<code>json = { text: ['name','phone','age'].join("\n") }.to_json
puts JSON.parse( json )['text']
</code>```

you can see the parse is parsing it correctly.

```<code>pry(main)> puts JSON.parse( json )['text']
name
phone
age
=> nil
</code>```

Body:
I have a string with \n as a join result:

my_var = ['name','phone','age'].join("\n")

I will send this string in the body of a post as a Json:

def body
  { "str": my_var }
end

I want to send the var in multiple lines instead of sending the \n like this:

"name\nphone\nage"

EDIT:
I am sending this string joined with \n to another dev team as a json in the body of my post request to their uri. But they don't want to receive a string with \n and replace or translate there. They want to recieve in multiple lines.

Body:
That's the expected format of the JSON. You should not be including a new line in the values, but using the '\n' character.

json = { text: ['name','phone','age'].join("\n") }.to_json
puts JSON.parse( json )['text']

you can see the parse is parsing it correctly.

pry(main)> puts JSON.parse( json )['text']
name
phone
age
=> nil


问:
Optimising a sentence search across multiple documents
I am having issues optimising a search I created in PHP, this search is for one time use, so flexibility is not that important.

I have a array of sentences, like:

```<code>$arr = [
   'potato',
   'hi my name is Ivan'
    ..
];
</code>```

The array contains about 1k sentences.

And I have a hard disk with 200 GB of files.

I need to search all of the files and see if any of these sentences are inside the files, and if so, to print out the path, a checksum, etc in a specific format.

The issue I am facing is search time, when doing something like this, which seems inefficient:

```<code>$objections = [];
foreach ($files as $file) {

    if (!in_array($file->getExtension(), $allowedExt))
        continue;

    $txt = file_get_contents($file);

    foreach ($words as $word) {
        if (stripos($txt, $word) !== false ||
            stripos($file->getFilename(), $word) !== false
            ) {
            $file->c_md5 = getCMD5($file);
            $objections[] = $file;
        }
    }
}
</code>```

The search it self is taking ages 1h+, and I am on a new MacBook with the latest i7. With PHP memory etc maxed.

It is not relevant which word is matched in the array of words, so I was wondering if there is some more clever way to perform the search instead of looping the words inside the file loop. Would a very long REGEX string with OR's be faster?

Or is there some third way which is a lot fast.

答:
A Regex will save you little or nothing.

You can break out of the loop on a hit.

```<code>Foreach{
    If(hit){
        Break;
    }
}
</code>```

Which would save searching for the rest. So if you hit on the second iteration you'll no longer have to do another 998 iterations of that document.

The problem you are always going to have is the opening of a document, that without a doubt is where most of your performance will be lost.

If this is an operation you need to perform more than once, it's probably worth considering indexing all of your files into a database designed for full text search ElasticSearch for example. Within your database you could then simply retain a reference to the physical file for whatever the next operation is.
The initial loading and indexing of all these files will admittedly take some big resources and time. However once complete your searches will be really fast.

Body:
I am having issues optimising a search I created in PHP, this search is for one time use, so flexibility is not that important.

I have a array of sentences, like:

$arr = [
   'potato',
   'hi my name is Ivan'
    ..
];

The array contains about 1k sentences.

And I have a hard disk with 200 GB of files.

I need to search all of the files and see if any of these sentences are inside the files, and if so, to print out the path, a checksum, etc in a specific format.

The issue I am facing is search time, when doing something like this, which seems inefficient:

$objections = [];
foreach ($files as $file) {

    if (!in_array($file->getExtension(), $allowedExt))
        continue;

    $txt = file_get_contents($file);

    foreach ($words as $word) {
        if (stripos($txt, $word) !== false ||
            stripos($file->getFilename(), $word) !== false
            ) {
            $file->c_md5 = getCMD5($file);
            $objections[] = $file;
        }
    }
}

The search it self is taking ages 1h+, and I am on a new MacBook with the latest i7. With PHP memory etc maxed.

It is not relevant which word is matched in the array of words, so I was wondering if there is some more clever way to perform the search instead of looping the words inside the file loop. Would a very long REGEX string with OR's be faster?

Or is there some third way which is a lot fast.

Body:
A Regex will save you little or nothing.

You can break out of the loop on a hit.

Foreach{
    If(hit){
        Break;
    }
}

Which would save searching for the rest. So if you hit on the second iteration you'll no longer have to do another 998 iterations of that document.

The problem you are always going to have is the opening of a document, that without a doubt is where most of your performance will be lost.

If this is an operation you need to perform more than once, it's probably worth considering indexing all of your files into a database designed for full text search ElasticSearch for example. Within your database you could then simply retain a reference to the physical file for whatever the next operation is.
The initial loading and indexing of all these files will admittedly take some big resources and time. However once complete your searches will be really fast.


问:
Connection to SQL Server Works Sometimes
An ADO.Net application is only sometimes able to connect to another server on the local network.  It seems random whether a given connection attempt succeeds or fails.  The connection is using a connection string in the form:

Server=THESERVER\TheInstance;Database=TheDatabase;User Id=TheUser; Password=ThePassword;

the error returned is:

Connection Timeout Expired.  The timeout period elapsed while attempting to consume the pre-login handshake acknowledgement.

  This could be because the pre-login handshake failed or the server was unable to respond back in time.

  The duration spent while attempting to connect to this server was - [Pre-Login] initialization=42030; handshake=0;

The .NET application is a small test app that executes the following code:

```<code>using (SqlConnection conn = new SqlConnection(cs))
using (SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM TheTable", conn))
{
    conn.Open();
    int rowCount = (int)cmd.ExecuteScalar();
}
</code>```

TheTable is small, just 78 rows.

However, on the same machine where the .NET application receives this error, I am able to connect to THESERVER using SSMS and the User Id/Password named in the connection string.

Why might the connection fail from an ADO.Net app, but succeed with identical credentials from SSMS?

答: Solved this problem by blocking/ blacklisting IP address that were trying to brute force user accounts. Check your SQL access logs for large numbers of failed login attempts (usually for the 'sa' account). </p>

Body:
An ADO.Net application is only sometimes able to connect to another server on the local network.  It seems random whether a given connection attempt succeeds or fails.  The connection is using a connection string in the form:

Server=THESERVER\TheInstance;Database=TheDatabase;User Id=TheUser; Password=ThePassword;

the error returned is:

Connection Timeout Expired.  The timeout period elapsed while attempting to consume the pre-login handshake acknowledgement.

  This could be because the pre-login handshake failed or the server was unable to respond back in time.

  The duration spent while attempting to connect to this server was - [Pre-Login] initialization=42030; handshake=0;

The .NET application is a small test app that executes the following code:

using (SqlConnection conn = new SqlConnection(cs))
using (SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM TheTable", conn))
{
    conn.Open();
    int rowCount = (int)cmd.ExecuteScalar();
}

TheTable is small, just 78 rows.

However, on the same machine where the .NET application receives this error, I am able to connect to THESERVER using SSMS and the User Id/Password named in the connection string.

Why might the connection fail from an ADO.Net app, but succeed with identical credentials from SSMS?


问:
EXCEL - Comparing a date to a column of date ranges and then, if within the range, comparing to a row cell
I am having trouble getting a working formula for this without using VBA (I can use VBA if needed but have no experience with it). So what I am attempting to do is take a given date, see if it is within a list if date ranges, and if it is within a certain date range, it should compare to a cell within the same row that it matches to the date range. If it doesn't, it should continue to search until it finds another date range match or exhausts the list and returns a value of false.

So far I have tried something along the lines of If(NumbertoMatch(VLOOKUP(AND(Date>Date1,Date<Date2),Table,NumbertoMatch,False),TRUE,FALSE)

Edit #2 Adding an image of what the cells would compare to.

Edit #3 Adding a rule that the formula should account for.

enter image description here

Thanks in advance!

答:
Consider this screenshot:

The formula in J2 is

```<code>=IF(SUMPRODUCT((G2>=$C$2:$C$15)*(G2<=$D$2:$D$15)),MATCH(1,(G2>=$C$2:$C$15)*(G2<=$D$2:$D$15),0)+1,"")
</code>```

This is an array formula and must be confirmed with Ctrl + Shift + Enter.

The formula in I2 uses that row number and compares the identifier in that row with the value in H2. If there is no match, that comparison will throw an error, so the IfError catches that and turns it into a FALSE.

```<code>=IFERROR(INDEX(A:A,J2)=H2,FALSE)
</code>```

Do not use whole columns in the array formula, as that will slow things down.

With formulas you will only ever find the FIRST occurrence of a match, so returning several row numbers for multiple matches will not be possible.

Edit: Explanation of the MATCH function.

```<code>MATCH(1,(G2>=$C$2:$C$15)*(G2<=$D$2:$D$15),0)
</code>```

When entered as an array function, the following will happen:

(G2>=$C$2:$C$15) will resolve to an array of True or False values, one for each cell

(G2<=$D$2:$D$15) will resolve to an array of True or False values, one for each row

these two arrays are multiplied one row at a time. If a TRUE is multiplied with a TRUE, the result is a 1. All other combinations will be 0.

That is the range that will be inspected for a matching 1. The position of the first 1 will be returned

Since the data starts in row 2 and I want the absolute row number, I have to add a 1 to the result from Match. Match returns a 12 because the date is matched to the 12th row of the data, which is row 13 in the spreadsheet.

You can see these steps play out with the Evaluate Formula tool on the Formulas ribbon.

Another edit:

This formula will only return TRUE if the date in column G falls in the time range AND the identifier in column H is the same as in column A:

```<code>=IFERROR(INDEX(A:A,IF(SUMPRODUCT((G2>=$C$2:$C$15)*(G2<=$D$2:$D$15)),MATCH(1,(G2>=$C$2:$C$15)*(G2<=$D$2:$D$15)*(H2=$A$2:$A$15),0)+1,""))=H2,FALSE)
</code>```

Again, confirm with Ctrl + Shift + Enter. Also if there are multiple matches, only the first match will trigger the TRUE.

Or if you want just the row number

```<code>=MATCH(1,(G2>=$C$2:$C$16)*(G2<=$D$2:$D$16)*(H2=$A$2:$A$16),0)+1
</code>```

Body:
Consider this screenshot:

The formula in J2 is

=IF(SUMPRODUCT((G2>=$C$2:$C$15)*(G2<=$D$2:$D$15)),MATCH(1,(G2>=$C$2:$C$15)*(G2<=$D$2:$D$15),0)+1,"")

This is an array formula and must be confirmed with Ctrl + Shift + Enter.

The formula in I2 uses that row number and compares the identifier in that row with the value in H2. If there is no match, that comparison will throw an error, so the IfError catches that and turns it into a FALSE.

=IFERROR(INDEX(A:A,J2)=H2,FALSE)

Do not use whole columns in the array formula, as that will slow things down.

With formulas you will only ever find the FIRST occurrence of a match, so returning several row numbers for multiple matches will not be possible.

Edit: Explanation of the MATCH function.

MATCH(1,(G2>=$C$2:$C$15)*(G2<=$D$2:$D$15),0)

When entered as an array function, the following will happen:

(G2>=$C$2:$C$15) will resolve to an array of True or False values, one for each cell

(G2<=$D$2:$D$15) will resolve to an array of True or False values, one for each row

these two arrays are multiplied one row at a time. If a TRUE is multiplied with a TRUE, the result is a 1. All other combinations will be 0.

That is the range that will be inspected for a matching 1. The position of the first 1 will be returned

Since the data starts in row 2 and I want the absolute row number, I have to add a 1 to the result from Match. Match returns a 12 because the date is matched to the 12th row of the data, which is row 13 in the spreadsheet.

You can see these steps play out with the Evaluate Formula tool on the Formulas ribbon.

Another edit:

This formula will only return TRUE if the date in column G falls in the time range AND the identifier in column H is the same as in column A:

=IFERROR(INDEX(A:A,IF(SUMPRODUCT((G2>=$C$2:$C$15)*(G2<=$D$2:$D$15)),MATCH(1,(G2>=$C$2:$C$15)*(G2<=$D$2:$D$15)*(H2=$A$2:$A$15),0)+1,""))=H2,FALSE)

Again, confirm with Ctrl + Shift + Enter. Also if there are multiple matches, only the first match will trigger the TRUE.

Or if you want just the row number

=MATCH(1,(G2>=$C$2:$C$16)*(G2<=$D$2:$D$16)*(H2=$A$2:$A$16),0)+1


问:
Visual Studio Code Snippets - Using a number over 9 for a placeholder?
Whenever I make a snippet using ${#:Default}, if the # is over 9 then it will mess up the tabbing.

Am I doing something wrong here? Is this a limitation to the snippet placeholders?

答:
Ok so. I solved this quickly. I considered deleting this but I had difficulty getting clarification so this example may help someone.

Doing the following will tab to any 3# before moving on.

```<code>"Create a Timeline Event" : {
    "prefix": "event_timeline",
    "body":
    [
        "- Title: ${1:Title}",
        "  Description: ${2:description.}",
        "  EventDate:",
        "    Year: ${30:Year}",
        "    Month: ${31:Month}",
        "    Day: ${32:Day}",
        "    Hour: ${33:Hour}",
        "    Minute: ${34:Minute}",
        "${4:TimelineEntry}"
    ],
    "description": "Creates a timeline event for the DnD timeline"
}
</code>```

Check these docs out. It does show [0-9]+ for the ints, so maybe this is intended.

Body:
Ok so. I solved this quickly. I considered deleting this but I had difficulty getting clarification so this example may help someone.

Doing the following will tab to any 3# before moving on.

"Create a Timeline Event" : {
    "prefix": "event_timeline",
    "body":
    [
        "- Title: ${1:Title}",
        "  Description: ${2:description.}",
        "  EventDate:",
        "    Year: ${30:Year}",
        "    Month: ${31:Month}",
        "    Day: ${32:Day}",
        "    Hour: ${33:Hour}",
        "    Minute: ${34:Minute}",
        "${4:TimelineEntry}"
    ],
    "description": "Creates a timeline event for the DnD timeline"
}

Check these docs out. It does show [0-9]+ for the ints, so maybe this is intended.