问:
Sequelize model getters in TypeScript
What is the correct way of using this.getDataValue in a getter function for a Sequelize model when using TypeScript?

This is the error I'm getting:

Property 'getDataValue' does not exist on type 'string | DataTypeAbstract | DefineAttributeColumnOptions'.

Property 'getDataValue' does not exist on type 'string'.

My model definition:

```<code>import * as Sequelize from 'sequelize';
import sequelize from '../db-connection';

export interface IUserAttributes {
    date_of_birth: Date;
    name: string;
}

export interface IUserInstance extends Sequelize.Instance<IUserAttributes> {
    date_of_birth: Date;
    name: string;
}

const User = sequelize.define<IUserAttributes, IUserInstance>('user', {
    name: {
        type: Sequelize.STRING,
        validate: {
            notEmpty: true,
        },
    },
    date_of_birth: {
        get(): Date {
            return new Date(this.getDataValue('date_of_birth'));
        },
        type: Sequelize.DATEONLY,
        validate: {
            isDate: true,
            notEmpty: true,
        },
    },
});

export default User;
</code>```

答:
Here is a working example> It casts the underlying TEXT value in column data to a new JSONB type column called payload:</p>

```<code>import {DataTypes, Model, Sequelize} from 'sequelize';

export class Book extends Model {
    public id!: number;
    public name!: string;
    public payload!: any;
    private data!: string;
}

export const initBook = (sequelize: Sequelize) => {
    Book.init(
        {
            id: {
                type: DataTypes.INTEGER,
                primaryKey: true
            },
            name: {
                type: DataTypes.STRING(100),
                primaryKey: false
            },
            data: {
                type: DataTypes.TEXT,
                primaryKey: false
            },
            payload: {
                type: DataTypes.JSONB,
                allowNull: false,
                field: 'data',
                get(this: any) {
                    const j = this.getDataValue('payload');
                    return JSON.parse(j);
                }
            }
        },
        {
            tableName: 'book',
            sequelize // this bit is important
        }
    );
};

export default {Book, initBook};
</code>```

Title: Sequelize model getters in TypeScript

Body:
What is the correct way of using this.getDataValue in a getter function for a Sequelize model when using TypeScript?

This is the error I'm getting:

Property 'getDataValue' does not exist on type 'string | DataTypeAbstract | DefineAttributeColumnOptions'.

Property 'getDataValue' does not exist on type 'string'.

My model definition:

import * as Sequelize from 'sequelize';
import sequelize from '../db-connection';

export interface IUserAttributes {
    date_of_birth: Date;
    name: string;
}

export interface IUserInstance extends Sequelize.Instance<IUserAttributes> {
    date_of_birth: Date;
    name: string;
}

const User = sequelize.define<IUserAttributes, IUserInstance>('user', {
    name: {
        type: Sequelize.STRING,
        validate: {
            notEmpty: true,
        },
    },
    date_of_birth: {
        get(): Date {
            return new Date(this.getDataValue('date_of_birth'));
        },
        type: Sequelize.DATEONLY,
        validate: {
            isDate: true,
            notEmpty: true,
        },
    },
});

export default User;

Body:
Here is a working example> It casts the underlying TEXT value in column data to a new JSONB type column called payload:

import {DataTypes, Model, Sequelize} from 'sequelize';

export class Book extends Model {
    public id!: number;
    public name!: string;
    public payload!: any;
    private data!: string;
}

export const initBook = (sequelize: Sequelize) => {
    Book.init(
        {
            id: {
                type: DataTypes.INTEGER,
                primaryKey: true
            },
            name: {
                type: DataTypes.STRING(100),
                primaryKey: false
            },
            data: {
                type: DataTypes.TEXT,
                primaryKey: false
            },
            payload: {
                type: DataTypes.JSONB,
                allowNull: false,
                field: 'data',
                get(this: any) {
                    const j = this.getDataValue('payload');
                    return JSON.parse(j);
                }
            }
        },
        {
            tableName: 'book',
            sequelize // this bit is important
        }
    );
};

export default {Book, initBook};


来源: stackexchange

问:
-bash: gcloud: command not found on Mac
I'm following the Quickstart for Mac OS X to install the cloud SDK.  Following the steps exactly,

1) python -V returns "Python 2.7.10"

2) Download and extract using ./install.sh the 64bit version of the SDK in google-cloud-sdk returns...

```<code>Welcome to the Google Cloud SDK!

To help improve the quality of this product, we collect anonymized usage data
and anonymized stacktraces when crashes are encountered; additional information
is available at <https://cloud.google.com/sdk/usage-statistics>. You may choose
to opt out of this collection now (by choosing 'N' at the below prompt), or at
any time in the future by running the following command:

    gcloud config set disable_usage_reporting true

Do you want to help improve the Google Cloud SDK (Y/n)?  Y

Your current Cloud SDK version is: 170.0.1
The latest available version is: 170.0.1

┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                                  Components                                                 │
├───────────────┬──────────────────────────────────────────────────────┬──────────────────────────┬───────────┤
│     Status    │                         Name                         │            ID            │    Size   │
├───────────────┼──────────────────────────────────────────────────────┼──────────────────────────┼───────────┤
│ Not Installed │ App Engine Go Extensions                             │ app-engine-go            │  97.7 MiB │
│ Not Installed │ Cloud Bigtable Command Line Tool                     │ cbt                      │   4.0 MiB │
│ Not Installed │ Cloud Bigtable Emulator                              │ bigtable                 │   3.5 MiB │
│ Not Installed │ Cloud Datalab Command Line Tool                      │ datalab                  │   < 1 MiB │
│ Not Installed │ Cloud Datastore Emulator                             │ cloud-datastore-emulator │  15.4 MiB │
│ Not Installed │ Cloud Datastore Emulator (Legacy)                    │ gcd-emulator             │  38.1 MiB │
│ Not Installed │ Cloud Pub/Sub Emulator                               │ pubsub-emulator          │  33.2 MiB │
│ Not Installed │ Emulator Reverse Proxy                               │ emulator-reverse-proxy   │  14.5 MiB │
│ Not Installed │ Google Container Local Builder                       │ container-builder-local  │   3.7 MiB │
│ Not Installed │ Google Container Registry's Docker credential helper │ docker-credential-gcr    │   2.2 MiB │
│ Not Installed │ gcloud Alpha Commands                                │ alpha                    │   < 1 MiB │
│ Not Installed │ gcloud Beta Commands                                 │ beta                     │   < 1 MiB │
│ Not Installed │ gcloud app Java Extensions                           │ app-engine-java          │ 128.1 MiB │
│ Not Installed │ gcloud app PHP Extensions (Mac OS X)                 │ app-engine-php-darwin    │  21.9 MiB │
│ Not Installed │ gcloud app Python Extensions                         │ app-engine-python        │   6.5 MiB │
│ Not Installed │ kubectl                                              │ kubectl                  │  15.9 MiB │
│ Installed     │ BigQuery Command Line Tool                           │ bq                       │   < 1 MiB │
│ Installed     │ Cloud SDK Core Libraries                             │ core                     │   6.7 MiB │
│ Installed     │ Cloud Storage Command Line Tool                      │ gsutil                   │   3.0 MiB │
└───────────────┴──────────────────────────────────────────────────────┴──────────────────────────┴───────────┘
To install or remove components at your current SDK version [170.0.1], run:
  $ gcloud components install COMPONENT_ID
  $ gcloud components remove COMPONENT_ID

To update your SDK installation to the latest version [170.0.1], run:
  $ gcloud components update

==> Source [/Users/shaneoseasnain/Desktop/google-cloud-sdk/completion.bash.inc] in your profile to enable shell command completion for gcloud.
==> Source [/Users/shaneoseasnain/Desktop/google-cloud-sdk/path.bash.inc] in your profile to add the Google Cloud SDK command line tools to your $PATH.

For more information on how to get started, please visit:
  https://cloud.google.com/sdk/docs/quickstarts
</code>```

3) I've restarted the terminal and run gcloud init from inside google-cloud-sdk.  This returns "command not found."  If I run ls, I see the following directory structure:

```<code>LICENSE               completion.zsh.inc      path.fish.inc
README                deb                     path.zsh.inc
RELEASE_NOTES         install.bat             platform
VERSION               install.sh              properties
bin                   lib                     rpm
completion.bash.inc   path.bash.inc
</code>```

4) I've tried to run gcloud init inside bin as well, but get the same problem, command not found.

The only other suggestions I can see from the install guide are "enable command-completion in your bash shell, and/or enable usage reporting."  I'm not sure how to do this but command completion and reporting don't look like they should be related to this problem.  There is a lot written about command not found but they relate to other problems where, for example, gcloud has stopped working after a while or problems in older versions.  Has anyone a tip how to get the cloud sdk working?

Thanks

答:
Sometimes, after installation, you need just restart your terminal. that's it :)

take a look at here: Quickstart for macOS

ContentLicense: CC BY-SA 3.0

Title: -bash: gcloud: command not found on Mac

Body:
I'm following the Quickstart for Mac OS X to install the cloud SDK.  Following the steps exactly,

1) python -V returns "Python 2.7.10"

2) Download and extract using ./install.sh the 64bit version of the SDK in google-cloud-sdk returns...

Welcome to the Google Cloud SDK!

To help improve the quality of this product, we collect anonymized usage data
and anonymized stacktraces when crashes are encountered; additional information
is available at <https://cloud.google.com/sdk/usage-statistics>. You may choose
to opt out of this collection now (by choosing 'N' at the below prompt), or at
any time in the future by running the following command:

    gcloud config set disable_usage_reporting true

Do you want to help improve the Google Cloud SDK (Y/n)?  Y

Your current Cloud SDK version is: 170.0.1
The latest available version is: 170.0.1

┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                                  Components                                                 │
├───────────────┬──────────────────────────────────────────────────────┬──────────────────────────┬───────────┤
│     Status    │                         Name                         │            ID            │    Size   │
├───────────────┼──────────────────────────────────────────────────────┼──────────────────────────┼───────────┤
│ Not Installed │ App Engine Go Extensions                             │ app-engine-go            │  97.7 MiB │
│ Not Installed │ Cloud Bigtable Command Line Tool                     │ cbt                      │   4.0 MiB │
│ Not Installed │ Cloud Bigtable Emulator                              │ bigtable                 │   3.5 MiB │
│ Not Installed │ Cloud Datalab Command Line Tool                      │ datalab                  │   < 1 MiB │
│ Not Installed │ Cloud Datastore Emulator                             │ cloud-datastore-emulator │  15.4 MiB │
│ Not Installed │ Cloud Datastore Emulator (Legacy)                    │ gcd-emulator             │  38.1 MiB │
│ Not Installed │ Cloud Pub/Sub Emulator                               │ pubsub-emulator          │  33.2 MiB │
│ Not Installed │ Emulator Reverse Proxy                               │ emulator-reverse-proxy   │  14.5 MiB │
│ Not Installed │ Google Container Local Builder                       │ container-builder-local  │   3.7 MiB │
│ Not Installed │ Google Container Registry's Docker credential helper │ docker-credential-gcr    │   2.2 MiB │
│ Not Installed │ gcloud Alpha Commands                                │ alpha                    │   < 1 MiB │
│ Not Installed │ gcloud Beta Commands                                 │ beta                     │   < 1 MiB │
│ Not Installed │ gcloud app Java Extensions                           │ app-engine-java          │ 128.1 MiB │
│ Not Installed │ gcloud app PHP Extensions (Mac OS X)                 │ app-engine-php-darwin    │  21.9 MiB │
│ Not Installed │ gcloud app Python Extensions                         │ app-engine-python        │   6.5 MiB │
│ Not Installed │ kubectl                                              │ kubectl                  │  15.9 MiB │
│ Installed     │ BigQuery Command Line Tool                           │ bq                       │   < 1 MiB │
│ Installed     │ Cloud SDK Core Libraries                             │ core                     │   6.7 MiB │
│ Installed     │ Cloud Storage Command Line Tool                      │ gsutil                   │   3.0 MiB │
└───────────────┴──────────────────────────────────────────────────────┴──────────────────────────┴───────────┘
To install or remove components at your current SDK version [170.0.1], run:
  $ gcloud components install COMPONENT_ID
  $ gcloud components remove COMPONENT_ID

To update your SDK installation to the latest version [170.0.1], run:
  $ gcloud components update

==> Source [/Users/shaneoseasnain/Desktop/google-cloud-sdk/completion.bash.inc] in your profile to enable shell command completion for gcloud.
==> Source [/Users/shaneoseasnain/Desktop/google-cloud-sdk/path.bash.inc] in your profile to add the Google Cloud SDK command line tools to your $PATH.

For more information on how to get started, please visit:
  https://cloud.google.com/sdk/docs/quickstarts

3) I've restarted the terminal and run gcloud init from inside google-cloud-sdk.  This returns "command not found."  If I run ls, I see the following directory structure:

LICENSE               completion.zsh.inc      path.fish.inc
README                deb                     path.zsh.inc
RELEASE_NOTES         install.bat             platform
VERSION               install.sh              properties
bin                   lib                     rpm
completion.bash.inc   path.bash.inc

4) I've tried to run gcloud init inside bin as well, but get the same problem, command not found.

The only other suggestions I can see from the install guide are "enable command-completion in your bash shell, and/or enable usage reporting."  I'm not sure how to do this but command completion and reporting don't look like they should be related to this problem.  There is a lot written about command not found but they relate to other problems where, for example, gcloud has stopped working after a while or problems in older versions.  Has anyone a tip how to get the cloud sdk working?

Thanks

ContentLicense: CC BY-SA 4.0


问:
Classnotfoundexception when copy paste a .ser file from a previous project to a new one
I have a project and serialized a class and got the .ser file on the same folder where the .classpath file is at. Now I created another project and copy paste the .ser from the previous one to the new one in the folder where the . classpath is at as well. But when I run the program I get classnotfoundexception. How can I go about this situation. I'm new to exclipse and I could use some help on what to do. Thank you.</p>

答: Oh thanks by the way I figured it out. I added the first project via Java build path to the second one and imported the specific class! Now I can copy all the .ser files to the new project I'm working on.</p>


问:
Dynamically add meta tags to index.html for shared link previews
I have an angular page that displays rich content (PDF, images, videos, etc). I need to create a shareable link to that HTML page with the right metatags so the correct title and description are displayed on rich link previews (when other services like Facebook, twitter, SMS, etc. display it). The shareable link has all the data needed encoded in it for my project to fetch the HTML page content. How can I add the correct metatags to the index.html page of my angular project dynamically so that the shareable link preview appears correctly on other services?

Example of how I want the link preview to appear when shared on other platforms:
https://i.stack.imgur.com/ZRJ8X.png

答:
For meta tags to work, they must be on the HTML page of the link before any javascript is run. Some platforms may run some javascript on the external site when generating a link preview, but in general, meta tags must be on the html page before angular boots up, so client side code on the given page will not work for this purpose.

For my purposes, I have found the most effective way to accomplish this effect is to serve shareable links separately from the angular project, as HTML redirects.

For example, you can have your shareable links actually link to your API, and have the API pass the data along when redirecting. Instead of example.com/article?id=2&exampleParam=123, you'd have api.example.com/share?id=2&exampleParam=123. The /share API endpoint would return an HTML file with the correct meta tags on it, along with a meta tag that will redirect to your app: <meta http-equiv="refresh" content="0; URL='https://example.com/article?id=2&shareableParam=123'" />

You just need to have your shareable link lead to an HTML page that has the correct meta tags, with a redirect to the actual URL on your app. There isn't any easier way to do this as far as I am aware, given that the meta tags must be present before angular is run. Server-side rendered angular projects are a totally different game, though, but I assume most people running into this issue will be using clientside rendering only.


问:
What's wrong with my function that gives current date in string type
When i do compare 2 string current date and past date it shows me that current date is not bigger than past date.

I tried to compare str and str2 and the comparison is true.

```<code>string str="21/05/2019";
    string str2="7/06/2019";
    string c=GetCurrentDate();
    if(c>str)
    {
        cout<<"true";
    }
</code>```

and function

```<code>inline string GetCurrentDate()
{
    auto t = time(nullptr);
    auto tm = *localtime(&t);
    ostringstream oss;
    oss << put_time(&tm, "%d/%m/%Y");
    auto strCurrentDate= oss.str();
    return strCurrentDate;
}
</code>```

答:
Comparing strings is different from comparing date/time types. It is better to use some built-in type for representing dates, such as std::time::chrono or something alike. C++ gives you the tools to manipulate these type, so you don't need to reinvent the wheel.

Although I believe std::time is not "user-friendly", I suggest to have a look at the reference below.

https://en.cppreference.com/w/cpp/chrono/system_clock/now

Body:
When i do compare 2 string current date and past date it shows me that current date is not bigger than past date.

I tried to compare str and str2 and the comparison is true.

string str="21/05/2019";
    string str2="7/06/2019";
    string c=GetCurrentDate();
    if(c>str)
    {
        cout<<"true";
    }

and function

inline string GetCurrentDate()
{
    auto t = time(nullptr);
    auto tm = *localtime(&t);
    ostringstream oss;
    oss << put_time(&tm, "%d/%m/%Y");
    auto strCurrentDate= oss.str();
    return strCurrentDate;
}


问:
How to use CSS counter increment for dynamic page numbers
I am trying to add page numbers to my html print out and came across Counter Increment. I tried using it for my pages, but it is only showing Page 1 every time. Help would be appreciated.

P.S. I have already tried following other solutions similar to mine, but none work so far. My case is different because I am using it inside of a table header.

.page-number{
    text-align:center;
}
thead {
    display:table-header-group;
}

@media print{
     .page-number:before{
        counter-increment: page;
        content: "Page " counter(page);
     }
   }
@media screen{
    .page-number:before {
        counter-increment: page;
        content: "Page " counter(page);
        }
     }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="SetupMainTable">
  <thead>
    <tr>
       <td colspan="4">Company Name</td>
       <td colspan="5" class="right" style="font-size:25px;">Daily Time Ticket</td>
       <td colspan="1"><div class="page-number"></div></td>
    </tr>
  </thead>
</table>  </code>```

Eg:Example that print's same Page 1  on all pages

Code editor link

Code editor Preview link - just press ctrl+p to test

Expected Answer

It Should print incremental Page 1 Page 2 Page 3 number on all pages after pressing ctrl + p Print

Long story short:

Press Ctrl + P → Print current window → Add a footer in the bottom of the page(Current Window) like Page <counter> counter is a number starting from 1 .

So the Page will be like

PS: Counter shouldn't visible on the page

答:
Not sure about your intended output but if you try this snippet I think it does what you are asking [i.e. incrementing the page number]. The code was readapted from [this original sample] 1

body {
  /* Set "my-sec-counter" to 0 */
  counter-reset: my-sec-counter;
}

h2::before {
  /* Increment "my-sec-counter" by 1 */
  counter-increment: my-sec-counter;
  content: "Section " counter(my-sec-counter) ". ";
}

#page-number::before {
  /* Increment "my-sec-counter" by 1 */
  counter-increment: my-sec-counter;
  content: "Page " counter(my-sec-counter) ". ";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>HTML Tutorial</h2>
<h2>CSS Tutorial</h2>
<h2>JavaScript Tutorial</h2>
<h2>Bootstrap Tutorial</h2>
<h2>SQL Tutorial</h2>
<h2>PHP Tutorial</h2>

<tr>
  <td colspan="4">Company Name</td>
  <td colspan="5" class="right" style="font-size:25px;">Daily Time Ticket</td>
  <td colspan="1">
    <div id="page-number"></div>
  </td>
</tr>

<tr>
  <td colspan="4">Company Name</td>
  <td colspan="5" class="right" style="font-size:25px;">Daily Time Ticket</td>
  <td colspan="1">
    <div id="page-number"></div>
  </td>
</tr></code>```

Body:
I am trying to add page numbers to my html print out and came across Counter Increment. I tried using it for my pages, but it is only showing Page 1 every time. Help would be appreciated.

P.S. I have already tried following other solutions similar to mine, but none work so far. My case is different because I am using it inside of a table header.

.page-number{
    text-align:center;
}
thead {
    display:table-header-group;
}

@media print{
     .page-number:before{
        counter-increment: page;
        content: "Page " counter(page);
     }
   }
@media screen{
    .page-number:before {
        counter-increment: page;
        content: "Page " counter(page);
        }
     }

       Company Name
       Daily Time Ticket

Eg:Example that print's same Page 1  on all pages

Code editor link

Code editor Preview link - just press ctrl+p to test

Expected Answer

It Should print incremental Page 1 Page 2 Page 3 number on all pages after pressing ctrl + p Print

Long story short:

Press Ctrl + P → Print current window → Add a footer in the bottom of the page(Current Window) like Page <counter> counter is a number starting from 1 .

So the Page will be like

PS: Counter shouldn't visible on the page

Body:
Not sure about your intended output but if you try this snippet I think it does what you are asking [i.e. incrementing the page number]. The code was readapted from [this original sample] 1

body {
  /* Set "my-sec-counter" to 0 */
  counter-reset: my-sec-counter;
}

h2::before {
  /* Increment "my-sec-counter" by 1 */
  counter-increment: my-sec-counter;
  content: "Section " counter(my-sec-counter) ". ";
}

#page-number::before {
  /* Increment "my-sec-counter" by 1 */
  counter-increment: my-sec-counter;
  content: "Page " counter(my-sec-counter) ". ";
}

<h2>HTML Tutorial</h2>
<h2>CSS Tutorial</h2>
<h2>JavaScript Tutorial</h2>
<h2>Bootstrap Tutorial</h2>
<h2>SQL Tutorial</h2>
<h2>PHP Tutorial</h2>

<tr>
  <td colspan="4">Company Name</td>
  <td colspan="5" class="right" style="font-size:25px;">Daily Time Ticket</td>
  <td colspan="1">
    <div id="page-number"></div>
  </td>
</tr>

<tr>
  <td colspan="4">Company Name</td>
  <td colspan="5" class="right" style="font-size:25px;">Daily Time Ticket</td>
  <td colspan="1">
    <div id="page-number"></div>
  </td>
</tr>


问:
regarding two dimensional arrays
if i have created an array like
int marks[4][2];
then the name of the array must give me the address of the first element,as is in case of one dimensional array,but it is not so?
& also

printf("%d",marks[0]);
&
printf("%d",marks);
 yield the same result?????????

答:
```<code>printf("%d",marks);
</code>```

Giving a wrong format-specifier leads to undefined-behavior. marks leads to a pointer to 1D array( i.e., pointer pointing to the first element of first row ).

So, to print a pointer's content %p should be used instead.

```<code>printf("%p",marks);
</code>```

And it seems you are trying to print the value at a location 0*0. So -

```<code>printf("%d",marks[0][0]);  // [m][n] is the way of accessing 2D array elements.
</code>```

Title: regarding two dimensional arrays

Body:
printf("%d",marks);

Giving a wrong format-specifier leads to undefined-behavior. marks leads to a pointer to 1D array( i.e., pointer pointing to the first element of first row ).

So, to print a pointer's content %p should be used instead.

printf("%p",marks);

And it seems you are trying to print the value at a location 0*0. So -

printf("%d",marks[0][0]);  // [m][n] is the way of accessing 2D array elements.


问:
Cannot connect through tcp remotely
I’m developing an app that connects on port 9050 through the public ip of my server. It works fine on lan but if I’m connected on a different network it fails what can I do to fix this?</p>

答:
I don't have any code to go by and I know nothing about your network configuration, but I'll tell you what I generally do when debugging a network-enabled app. First, look at your firewall rules. This will obviously vary depending on what OS you're using but on Windows 10 application-specific permissions are located in Control Panel > System and Security > Windows Defender Firewall > Advanced Settings.

After making sure your app can get through your devices' firewall, check the router settings next. Your packets may not getting by whatever inbuilt security protocols are in place. Since your program works with LAN but not over the Internet, this is a distinct possibility. Also, depending on your network configuration, port forwarding may be necessary; if you're sending data via a public IP address, the router needs some way to know which device on the local network needs to be receiving it. Additionally, if you're trying to connect to your server from the same network you're hosting it on, make sure you use the IP loopback address, which I believe is always 127.0.0.1, or in C# IPAddress.Loopback. Public addresses often won't work when connecting to a local host.

If you're still having problems, I recommend using Wireshark. It's an advanced diagnostics tool that tells you exactly what is being sent and received over your network, and can help pinpoint otherwise hard to spot issues.

Title: Cannot connect through tcp remotely


问:
jquery ui Dialog: cannot call methods on dialog prior to initialization
I have an app on jquery 1.5 with dialogs worked fine.
While I have a lot of .live handlers, I changed this to .on.
For that, I have to update jquery (now 1.8.3 an jquerui 1.9.1).

Now, I got: Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

Following is the code:

Javascript

```<code>var opt = {
        autoOpen: false,
        modal: true,
        width: 550,
        height:650,
        title: 'Details'
};

$(document).ready(function() {
$("#divDialog").dialog(opt);
    $("#divDialog").dialog("open");
...
</code>```

html code

```<code><div id="divDialog">
<div id="divInDialog"></div>
</div>
</code>```

Any idea why this might be happening?

答:
My case is different, it fails because of the scope of 'this':

```<code>//this fails:
$("#My-Dialog").dialog({
  ...
  close: ()=>{
    $(this).dialog("close");
  }
});

//this works:
$("#My-Dialog").dialog({
  ...
  close: function(){
    $(this).dialog("close");
  }
});
</code>```

Body:
I have an app on jquery 1.5 with dialogs worked fine.
While I have a lot of .live handlers, I changed this to .on.
For that, I have to update jquery (now 1.8.3 an jquerui 1.9.1).

Now, I got: Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

Following is the code:

Javascript

var opt = {
        autoOpen: false,
        modal: true,
        width: 550,
        height:650,
        title: 'Details'
};

$(document).ready(function() {
$("#divDialog").dialog(opt);
    $("#divDialog").dialog("open");
...

html code

Any idea why this might be happening?

Body:
My case is different, it fails because of the scope of 'this':

//this fails:
$("#My-Dialog").dialog({
  ...
  close: ()=>{
    $(this).dialog("close");
  }
});

//this works:
$("#My-Dialog").dialog({
  ...
  close: function(){
    $(this).dialog("close");
  }
});


问:
add extra field woocommerce checkout out
im attempting to add an extra field to the woocommerce place order button using </p>

```<code>/**
 * Add PO checkout field
 */

add_action( 'woocommerce_review_order_before_payment', 'invoice_po' );
function invoice_po($checkout)
    {
    woocommerce_form_field('invoice_po_field', array(
        'type' => 'text',
        'class' => array(
            'form-row-wide') ,
            'label' => __('Invoice Customer PO') ,
            'placeholder' => __('PO123456789') ,
            'required' => true,
    ) , $checkout->get_value('invoice_po_field'));
}

add_action('woocommerce_checkout_update_order_meta', 'add_po_to_order_meta');
function add_po_to_order_meta($order_id)
{
  if (!empty($_POST['invoice_po_field'])) {
    update_post_meta($order_id, 'Invoice Field', sanitize_text_field($_POST['invoice_po_field']));
  }
}
</code>```

<p>this method works fine if i want to add it before or after order notes but will not work if attempting to add before place order button does any one know why i cant add a field on in this section </p>

答:
The error with my code was ($checkout) this variable is only relevant to the address and customer notes section of the checkout page to allow access to all page hooks i just removed it </p>

```<code>/**
 * Add PO checkout field
 */
add_action( 'woocommerce_review_order_before_payment', 'invoice_po');
function invoice_po()
{
    $user = wp_get_current_user();
    if (in_array('invoice_customer', $user->roles)) {
        woocommerce_form_field('invoice_po_field', array(
            'type' => 'text',
            'class' => array('form-row-wide') ,
            'label' => __('Invoice Customer PO') ,
            'placeholder' => __('PO123456789') ,
            'required' => true
        ));
    }
}

add_action('woocommerce_checkout_update_order_meta', 'add_po_to_order_meta');
function add_po_to_order_meta($order_id)
{
  if (!empty($_POST['invoice_po_field'])) {
    update_post_meta($order_id, 'Invoice Field', sanitize_text_field($_POST['invoice_po_field']));
  }
}
</code>```

Body:
im attempting to add an extra field to the woocommerce place order button using

/**
 * Add PO checkout field
 */

add_action( 'woocommerce_review_order_before_payment', 'invoice_po' );
function invoice_po($checkout)
    {
    woocommerce_form_field('invoice_po_field', array(
        'type' => 'text',
        'class' => array(
            'form-row-wide') ,
            'label' => __('Invoice Customer PO') ,
            'placeholder' => __('PO123456789') ,
            'required' => true,
    ) , $checkout->get_value('invoice_po_field'));
}

add_action('woocommerce_checkout_update_order_meta', 'add_po_to_order_meta');
function add_po_to_order_meta($order_id)
{
  if (!empty($_POST['invoice_po_field'])) {
    update_post_meta($order_id, 'Invoice Field', sanitize_text_field($_POST['invoice_po_field']));
  }
}

this method works fine if i want to add it before or after order notes but will not work if attempting to add before place order button does any one know why i cant add a field on in this section

Body:
The error with my code was ($checkout) this variable is only relevant to the address and customer notes section of the checkout page to allow access to all page hooks i just removed it

/**
 * Add PO checkout field
 */
add_action( 'woocommerce_review_order_before_payment', 'invoice_po');
function invoice_po()
{
    $user = wp_get_current_user();
    if (in_array('invoice_customer', $user->roles)) {
        woocommerce_form_field('invoice_po_field', array(
            'type' => 'text',
            'class' => array('form-row-wide') ,
            'label' => __('Invoice Customer PO') ,
            'placeholder' => __('PO123456789') ,
            'required' => true
        ));
    }
}

add_action('woocommerce_checkout_update_order_meta', 'add_po_to_order_meta');
function add_po_to_order_meta($order_id)
{
  if (!empty($_POST['invoice_po_field'])) {
    update_post_meta($order_id, 'Invoice Field', sanitize_text_field($_POST['invoice_po_field']));
  }
}


问:
How to create a switching function in Python?
I'm having difficulty creating a program that switches between string "X" and "O" every time the function is ran.

So for example, the first time switcher() is ran, it prints "x," and the next time it runs, it prints "o," and third it prints "x," and so forth

I've been able to achieve this without a function and just using an if else loop, but I can't do it using a function

```<code>def switch(value):
    if value == 0:
        x = value
        x + 1
        print("value: " + str(x) + " | turn: x")
        return x
    else:
        print("o")
        return 0

x = 0
for i in range(4):
    switch(x)
</code>```

it outputs:

```<code>value: 0 | turn: x
value: 0 | turn: x
value: 0 | turn: x
value: 0 | turn: x
</code>```

In order to achieve this, I make it so that when x = 0, it prints "X" and when it's 1 it prints "O," and then resets back to 0. It stays as 0 and only gives me x.

答:
You could use boolean indexing:

```<code>def switch(options=('X', 'O')):
    val = False
    while True:
        val = not val
        yield options[val]

switcher = switch()
for _ in range(5):
    print(next(switcher))
</code>```

This prints:

```<code>O
X
O
X
O
</code>```

Body:
I'm having difficulty creating a program that switches between string "X" and "O" every time the function is ran.

So for example, the first time switcher() is ran, it prints "x," and the next time it runs, it prints "o," and third it prints "x," and so forth

I've been able to achieve this without a function and just using an if else loop, but I can't do it using a function

def switch(value):
    if value == 0:
        x = value
        x + 1
        print("value: " + str(x) + " | turn: x")
        return x
    else:
        print("o")
        return 0

x = 0
for i in range(4):
    switch(x)

it outputs:

value: 0 | turn: x
value: 0 | turn: x
value: 0 | turn: x
value: 0 | turn: x

In order to achieve this, I make it so that when x = 0, it prints "X" and when it's 1 it prints "O," and then resets back to 0. It stays as 0 and only gives me x.

Body:
You could use boolean indexing:

def switch(options=('X', 'O')):
    val = False
    while True:
        val = not val
        yield options[val]

switcher = switch()
for _ in range(5):
    print(next(switcher))

This prints:

O
X
O
X
O


问:
How does word2vec or skip-gram model convert words to vector?
I have been reading a lot of papers on NLP, and came across many models. I got the SVD Model and representing it in 2-D, but I still did not get how do we make a word vector by giving a corpus to the word2vec/skip-gram model? Is it also co-occurrence matrix representation for each word? Can you explain it by taking an example corpus:

```<code>Hello, my name is John.
John works in Google.
Google has the best search engine.
</code>```

Basically, how does skip gram convert John to a vector?

答:
First of all, you normally don't use SVD with Skip-Gram model, because Skip-Gram is based on neural network. You use SVD because you want to reduce the dimension of your word vector (ex: for visualization on 2D or 3D space), but in neural net you construct your embedding matrices with the dimension of your choice. You use SVD if you constructed your embedding matrix with co-occurrence matrix.

Vector representation with co-occurrence matrix

I wrote an article about this here.

Consider the following two sentences: "all that glitters is not gold" + "all is well that ends well"

Co-occurrence matrix is then:

With co-occurrence matrix, each row is a word vector for the word. However as you can see in the matrix constructed above, each row has 10 columns. This means that the word vectors are 10-dimensional, and can't be visualized in 2D or 3D space. So we run SVD to reduce it to 2 dimension:

Now that the word vectors are 2-dimensional, they can be visualized in a 2D space:

However, reducing the word vectors into 2D matrix results in significant loss of meaningful data, which is why you shouldn't reduce it down too much.

Lets take another example: achieve and success. Lets say they have 10-dimensional word vectors:

Since achieve and success convey similar meanings, their vector representations are similar. Notice their similar values & color band pattern. However, since these are 10-dimensional vectors, these can't be visualized. So we run SVD to reduce the dimension to 3D, and visualize them:

Each value in the word vector represents the word's position within the vector space. Similar words will have similar vectors, and as a result, will be placed closed with each other in the vector space.

Vector representation with Skip-Gram

I wrote an article about it here.

Skip-Gram uses neural net, and therefore does not use SVD because you can specify the word vector's dimension as a hyper-parameter when you first construct the network (if you really need to visualize, then we use a special technique called t-SNE, but not SVD).

Skip-Gram as the following structure:

With Skip-Gram, N-dimensional word vectors are randomly initialized. There are two embedding matrices: input weight matrix W_input and output weight matrix W_output

Lets take W_input as an example. Assume that the words of your interest are passes and should. Since the randomly initialized weight matrix is 3-dimensional, they can be visualized:

These weight matrices (W_input, and W_ouput) are optimized by predicting a center word's neighboring words, and updating the weights in a way that minimizes prediction error. The predictions are computed for each context words of a center word, and their prediction errors are summed up to calculate weight gradients

The weight matrices update equations are:

These updates are applied for each training sample within the corpus (since Word2Vec uses stochastic gradient descent).

Vanilla Skip-Gram vs Negative Sampling

The above Skip-Gram illustration assumes that we use vanilla Skip-Gram. In real-life, we don't use vanilla Skip-Gram because of its high computational cost. Instead, we use an adapted form of Skip-Gram, called negative sampling.

Body:
I have been reading a lot of papers on NLP, and came across many models. I got the SVD Model and representing it in 2-D, but I still did not get how do we make a word vector by giving a corpus to the word2vec/skip-gram model? Is it also co-occurrence matrix representation for each word? Can you explain it by taking an example corpus:

Hello, my name is John.
John works in Google.
Google has the best search engine.

Basically, how does skip gram convert John to a vector?


问:
Firefox sending two get request for a website
Clicking a link results in two calls for the page to the server. I install livehttp and inspected the header but can't figure out why it's sending the second request.</p>

```<code>http://example.com/schedule?delete=290376

GET /schedule?delete=290376 HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.13) Gecko/20110207 Firefox/3.6.13
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: http://example.com/schedule
Cookie: Code=XXX; CodeHash=XXXXX

HTTP/1.1 200 OK
Date: Tue, 01 Mar 2011 22:09:51 GMT
Server: Apache
X-Powered-By: PHP/5.2.17
Set-Cookie: Code=XXXX; expires=Wed, 02-Mar-2011 00:09:52 GMT; path=/
Set-Cookie: CodeHash=XXXX; expires=Wed, 02-Mar-2011 00:09:52 GMT; path=/
Keep-Alive: timeout=2, max=200
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/html
----------------------------------------------------------
http://example.com/schedule?delete=290376

GET /schedule?delete=290376 HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.13) Gecko/20110207 Firefox/3.6.13
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: http://example.com/schedule
Cookie: Code=XXXX; CodeHash=XXXXX

HTTP/1.1 302 Moved Temporarily
Date: Tue, 01 Mar 2011 22:09:55 GMT
Server: Apache
X-Powered-By: PHP/5.2.17
Set-Cookie: Code=XXX; expires=Wed, 02-Mar-2011 00:09:55 GMT; path=/
Set-Cookie: CodeHash=XXX; expires=Wed, 02-Mar-2011 00:09:55 GMT; path=/
Location: http://example.org/schedule?errors=5
Keep-Alive: timeout=2, max=200
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/html
----------------------------------------------------------
</code>```

答:
In case you didn't find your solution:

I have stumbled on that same issue, and it seems to be related to the page encoding. If FireFox downloads a page containing invalid characters (for example, utf-8 chars inside a page for which the Content-type header is something else), then it will download the page a second time and parse it in the encoding it has tried to guess from the invalid chars it detected in the first page.

So make sure your page either returns the correct Content-type header, or contains a meta http-equiv header with the correct encoding.

ContentLicense: CC BY-SA 2.5

Body:
Clicking a link results in two calls for the page to the server. I install livehttp and inspected the header but can't figure out why it's sending the second request.

http://example.com/schedule?delete=290376

GET /schedule?delete=290376 HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.13) Gecko/20110207 Firefox/3.6.13
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: http://example.com/schedule
Cookie: Code=XXX; CodeHash=XXXXX

HTTP/1.1 200 OK
Date: Tue, 01 Mar 2011 22:09:51 GMT
Server: Apache
X-Powered-By: PHP/5.2.17
Set-Cookie: Code=XXXX; expires=Wed, 02-Mar-2011 00:09:52 GMT; path=/
Set-Cookie: CodeHash=XXXX; expires=Wed, 02-Mar-2011 00:09:52 GMT; path=/
Keep-Alive: timeout=2, max=200
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/html
----------------------------------------------------------
http://example.com/schedule?delete=290376

GET /schedule?delete=290376 HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.13) Gecko/20110207 Firefox/3.6.13
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: http://example.com/schedule
Cookie: Code=XXXX; CodeHash=XXXXX

HTTP/1.1 302 Moved Temporarily
Date: Tue, 01 Mar 2011 22:09:55 GMT
Server: Apache
X-Powered-By: PHP/5.2.17
Set-Cookie: Code=XXX; expires=Wed, 02-Mar-2011 00:09:55 GMT; path=/
Set-Cookie: CodeHash=XXX; expires=Wed, 02-Mar-2011 00:09:55 GMT; path=/
Location: http://example.org/schedule?errors=5
Keep-Alive: timeout=2, max=200
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/html
----------------------------------------------------------


问:
mikrotik add hotspot user from javascript API
I try to develop an app to create user in mikrotik user manager via api. And I also tried JavaScript in the terminal by using following command:

```<code>$node script name.js
</code>```

That is working and a user created.
Then I tried to run that JavaScript by on click html button. Then JavaScript doesn't run and no user crated. Code follows:

```<code><html>
<head>

 </head>
<body>
<button type = "button" onclick="conn();">Try it</button>
<script type="text/javascript">
var api = require('mikronode');
 var connection = new api('192.168.5.1','admin','xxxxxx');
 connection.connect(function conn() {

    conn.closeOnDone(true); // All channels need to complete before the connection will close.

    var actionChannel=conn.openChannel();
    // These will run synchronsously
    actionChannel.write(['/tool/user-manager/user/add','=username=tiran','=password=123456','=customer=admin']); // don't care to do anything after it's done.
    actionChannel.write(['/tool/user-manager/user/create-and-activate-profile','=customer=admin','=numbers=tiran','=profile=general']); // don't care to do anything after it's done.
    //actionChannel.write('/tool/user-manager/user/print',function(chan) {

       //chan.on('done',function(data) {
          //packets=api.parseItems(data);
          //packets.forEach(function(packet) {
              //alert('done');
             //alert('user: '+JSON.stringify(packet));
              //console.log('user: '+JSON.stringify(packet));
          //});
          //listenChannel.close(); // This should call the /cancel command to stop the listen.
       //});
    //});
    actionChannel.close(); // The above commands will complete before this is closed.
 });
</script>
 </body>
 </html>
</code>```

答: That code is for NodeJS, you cannot run in directly on the browser as JavaScript</p>

Body:
I try to develop an app to create user in mikrotik user manager via api. And I also tried JavaScript in the terminal by using following command:

$node script name.js

That is working and a user created.
Then I tried to run that JavaScript by on click html button. Then JavaScript doesn't run and no user crated. Code follows:

<button type = "button" onclick="conn();">Try it</button>


问:
Javascript - deepEqual Comparison
Question (From Eloquent Javascript 2nd Edition, Chapter 4, Exercise 4):

Write a function, deepEqual, that takes two values and returns true only if they
      are the same value or are objects with the same properties whose values are also
      equal when compared with a recursive call to deepEqual.

Test Cases:

```<code>var obj = {here: {is: "an"}, object: 2};
console.log(deepEqual(obj, obj));
// → true
console.log(deepEqual(obj, {here: 1, object: 2}));
// → false
console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
// → true
</code>```

My code:

```<code>var deepEqual = function (x, y) {
  if ((typeof x == "object" && x != null) && (typeof y == "object" && y != null)) {
    if (Object.keys(x).length != Object.keys(y).length)
      return false;
    for (var prop in x) {
      if (y.hasOwnProperty(prop))
        return deepEqual(x[prop], y[prop]);
    /*This is most likely where my error is. The question states that all the values
    should be checked via recursion; however, with the current setup, only the first
    set of properties will be checked. It passes the test cases, but I would like
    to solve the problem correctly!*/
      }
    }
  else if (x !== y)
    return false;
  else
    return true;
}
</code>```

I think I have the general idea down; however, like I stated in the comment, the program will not check the second property in the objects. I feel like I have a structural/logic problem and am simply using recursion in the wrong way, as I originally intended to loop through the properties, use recursion to compare the values of the first property, then continue on in the loop to the next property and compare again.  Although, I'm not sure if that's even possible?

I've given a good amount of thought and tried a couple different approaches, but this was the most correct answer I've come to so far.  Any possible tips to point me in the right direction?

答:
Although that it's more verbose, maybe this option is easier to read:</p>

```<code>function deepEqual(elem1, elem2) {
    if(elem1 === elem2) {
        return true;
    }
    if(typeof elem1 == 'object' && typeof elem2 == 'object' && elem1 != null && elem2 != null) {
      if(Object.keys(elem1).length == Object.keys(elem2).length) {
          for(let key of Object.keys(elem1)) {
              if(elem2.hasOwnProperty(key) != true) {
                  return false;
              }
          }
          for(let key of Object.keys(elem1)) {
              if(typeof elem1[key] == 'object' && typeof elem2[key] == 'object' && typeof elem1[key] != null && typeof elem2[key] != null) {
                  return deepEqual(elem1[key], elem2[key]);
              }
              else {
                if(elem1[key] !== elem2[key]) {
                    return false;
                }
              }
          } else {
            return false;
          }
        }
      }
    else {
        return false;
    }
    return true;
  }
</code>```

Title: Javascript - deepEqual Comparison

Body:
Question (From Eloquent Javascript 2nd Edition, Chapter 4, Exercise 4):

Write a function, deepEqual, that takes two values and returns true only if they
      are the same value or are objects with the same properties whose values are also
      equal when compared with a recursive call to deepEqual.

Test Cases:

var obj = {here: {is: "an"}, object: 2};
console.log(deepEqual(obj, obj));
// → true
console.log(deepEqual(obj, {here: 1, object: 2}));
// → false
console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
// → true

My code:

var deepEqual = function (x, y) {
  if ((typeof x == "object" && x != null) && (typeof y == "object" && y != null)) {
    if (Object.keys(x).length != Object.keys(y).length)
      return false;
    for (var prop in x) {
      if (y.hasOwnProperty(prop))
        return deepEqual(x[prop], y[prop]);
    /*This is most likely where my error is. The question states that all the values
    should be checked via recursion; however, with the current setup, only the first
    set of properties will be checked. It passes the test cases, but I would like
    to solve the problem correctly!*/
      }
    }
  else if (x !== y)
    return false;
  else
    return true;
}

I think I have the general idea down; however, like I stated in the comment, the program will not check the second property in the objects. I feel like I have a structural/logic problem and am simply using recursion in the wrong way, as I originally intended to loop through the properties, use recursion to compare the values of the first property, then continue on in the loop to the next property and compare again.  Although, I'm not sure if that's even possible?

I've given a good amount of thought and tried a couple different approaches, but this was the most correct answer I've come to so far.  Any possible tips to point me in the right direction?

Body:
Although that it's more verbose, maybe this option is easier to read:

function deepEqual(elem1, elem2) {
    if(elem1 === elem2) {
        return true;
    }
    if(typeof elem1 == 'object' && typeof elem2 == 'object' && elem1 != null && elem2 != null) {
      if(Object.keys(elem1).length == Object.keys(elem2).length) {
          for(let key of Object.keys(elem1)) {
              if(elem2.hasOwnProperty(key) != true) {
                  return false;
              }
          }
          for(let key of Object.keys(elem1)) {
              if(typeof elem1[key] == 'object' && typeof elem2[key] == 'object' && typeof elem1[key] != null && typeof elem2[key] != null) {
                  return deepEqual(elem1[key], elem2[key]);
              }
              else {
                if(elem1[key] !== elem2[key]) {
                    return false;
                }
              }
          } else {
            return false;
          }
        }
      }
    else {
        return false;
    }
    return true;
  }


问:
For loop to filter by lat every 5 decimal places
I need to write a for loop to use the dplyr::filter() function to filter latitude every 5 points, and then average the trait for each 5 degree bin.

I would like to do this for in 5 degree lat bins continuously from -180 to 180 and then o

The data frame is organized with 2 columns: lat and trait

so for instance:

```<code>lat             trait
-0.830361   0.113935
-0.795028   0.113935
-0.729722   0.113935
-0.729722   0.113935
8.021833    0.113935
5.473333    0.113935
5.436333    0.113935
7.366667    0.113935
</code>```

I would like each trait to be average over the bin and then output into a df.

```<code>data.df %>%
  dplyr::filter(lat >= -180 & lat <= -175, .preserve= T)
</code>```

The end output will be a data frame with one column containing all the bins, and the second column containing the averages

答:
Here's a base R solution with cut() and aggregate()

```<code>data.df$lat_group <- cut(data.df$lat, breaks = seq(-180, 180, 5))
aggregate(trait ~ lat_group, data = data.df, FUN = mean)

  lat_group     trait
1    (-5,0] 1.3354512
2    (5,10] 0.8354512

aggregate(data.df[, c('lat', 'trait')], by = data.df['lat_group'], FUN = mean)
#or
#aggregate(data.df[, c('lat', 'trait')], by = list(lat_group = data.df$lat_group), FUN = mean)

  lat_group        lat     trait
1    (-5,0] -0.7712082 1.3354512
2    (5,10]  6.5745415 0.8354512
</code>```

Data (copying and pasting from @Jon Spring)

```<code>data.df <- read.table(
  header = T,
  stringsAsFactors = F,
  text = "lat             trait
  -0.830361   5
  -0.795028   0.113935
  -0.729722   0.113935
  -0.729722   0.113935
  8.021833    3
  5.473333    0.113935
  5.436333    0.113935
  7.366667    0.113935")
</code>```

Body:
I need to write a for loop to use the dplyr::filter() function to filter latitude every 5 points, and then average the trait for each 5 degree bin.

I would like to do this for in 5 degree lat bins continuously from -180 to 180 and then o

The data frame is organized with 2 columns: lat and trait

so for instance:

lat             trait
-0.830361   0.113935
-0.795028   0.113935
-0.729722   0.113935
-0.729722   0.113935
8.021833    0.113935
5.473333    0.113935
5.436333    0.113935
7.366667    0.113935

I would like each trait to be average over the bin and then output into a df.

data.df %>%
  dplyr::filter(lat >= -180 & lat <= -175, .preserve= T)

The end output will be a data frame with one column containing all the bins, and the second column containing the averages

Body:
Here's a base R solution with cut() and aggregate()

data.df$lat_group <- cut(data.df$lat, breaks = seq(-180, 180, 5))
aggregate(trait ~ lat_group, data = data.df, FUN = mean)

  lat_group     trait
1    (-5,0] 1.3354512
2    (5,10] 0.8354512

aggregate(data.df[, c('lat', 'trait')], by = data.df['lat_group'], FUN = mean)
#or
#aggregate(data.df[, c('lat', 'trait')], by = list(lat_group = data.df$lat_group), FUN = mean)

  lat_group        lat     trait
1    (-5,0] -0.7712082 1.3354512
2    (5,10]  6.5745415 0.8354512

Data (copying and pasting from @Jon Spring)

data.df <- read.table(
  header = T,
  stringsAsFactors = F,
  text = "lat             trait
  -0.830361   5
  -0.795028   0.113935
  -0.729722   0.113935
  -0.729722   0.113935
  8.021833    3
  5.473333    0.113935
  5.436333    0.113935
  7.366667    0.113935")


问:
How to retrieve pandas df multiindex from HDFStore?
If DataFrame with simple index is the case, one may retrieve index from HDFStore as follows:

df = pd.DataFrame(np.random.randn(2, 3), index=list('yz'), columns=list('abc'))
df

>>>      a          b           c
>>> y   -0.181063   1.919440    1.550992
>>> z   -0.701797   1.917156    0.645707
```

<pre class="lang-py prettyprint-override"><code>with pd.HDFStore('test.h5') as store:
    store.put('df', df, format='t')
    store.select_column('df', 'index')

>>> 0    y
>>> 1    z
>>> Name: index, dtype: object
</code>```

As stated in the docs.

But in case with MultiIndex such trick doesn't work:

df = pd.DataFrame(np.random.randn(2, 3),
                  index=pd.MultiIndex.from_tuples([(0,'y'), (1, 'z')], names=['lvl0', 'lvl1']),
                  columns=list('abc'))
df

>>>                 a           b           c
>>> lvl0    lvl1
>>>    0       y    -0.871125   0.001773     0.618647
>>>    1       z     1.001547   1.132322    -0.215681
```

<p>More precisely it returns <em>wrong</em> index:</p>

<pre class="lang-py prettyprint-override"><code>with pd.HDFStore('test.h5') as store:
    store.put('df', df, format='t')
    store.select_column('df', 'index')

>>> 0    0
>>> 1    1
>>> Name: index, dtype: int64
</code>```

How to retrieve correct DataFrame MultiIndex?

答:
One may use select with columns=['index'] parameter specified:

df = pd.DataFrame(np.random.randn(2, 3),
                  index=pd.MultiIndex.from_tuples([(0,'y'), (1, 'z')], names=['lvl0', 'lvl1']),
                  columns=list('abc'))
df

>>>                 a           b           c
>>> lvl0    lvl1
>>>    0       y    -0.871125   0.001773     0.618647
>>>    1       z     1.001547   1.132322    -0.215681
```

<pre class="lang-py prettyprint-override"><code>with pd.HDFStore('test.h5') as store:
    store.put('df', df, format='t')
    store.select('df', columns=['index'])

>>> lvl0    lvl1
>>>    0       y
>>>    1       z
</code>```

It works but seems not being documented.

Body:
If DataFrame with simple index is the case, one may retrieve index from HDFStore as follows:

df = pd.DataFrame(np.random.randn(2, 3), index=list('yz'), columns=list('abc'))
df

>>>      a          b           c
>>> y   -0.181063   1.919440    1.550992
>>> z   -0.701797   1.917156    0.645707

with pd.HDFStore('test.h5') as store:
    store.put('df', df, format='t')
    store.select_column('df', 'index')

>>> 0    y
>>> 1    z
>>> Name: index, dtype: object

As stated in the docs.

But in case with MultiIndex such trick doesn't work:

df = pd.DataFrame(np.random.randn(2, 3),
                  index=pd.MultiIndex.from_tuples([(0,'y'), (1, 'z')], names=['lvl0', 'lvl1']),
                  columns=list('abc'))
df

>>>                 a           b           c
>>> lvl0    lvl1
>>>    0       y    -0.871125   0.001773     0.618647
>>>    1       z     1.001547   1.132322    -0.215681

More precisely it returns wrong index:

with pd.HDFStore('test.h5') as store:
    store.put('df', df, format='t')
    store.select_column('df', 'index')

>>> 0    0
>>> 1    1
>>> Name: index, dtype: int64

How to retrieve correct DataFrame MultiIndex?

Body:
One may use select with columns=['index'] parameter specified:

df = pd.DataFrame(np.random.randn(2, 3),
                  index=pd.MultiIndex.from_tuples([(0,'y'), (1, 'z')], names=['lvl0', 'lvl1']),
                  columns=list('abc'))
df

>>>                 a           b           c
>>> lvl0    lvl1
>>>    0       y    -0.871125   0.001773     0.618647
>>>    1       z     1.001547   1.132322    -0.215681

with pd.HDFStore('test.h5') as store:
    store.put('df', df, format='t')
    store.select('df', columns=['index'])

>>> lvl0    lvl1
>>>    0       y
>>>    1       z

It works but seems not being documented.


问:
How to save the dictionary that have tuple keys
I would like to save the dictionary having tuple on keys.

I tried pickle, ujson, json to save the dictionary. All of them did not work.

The dictionary has:

```<code>dictionary = {(-30, -29, -72, -71): [[-29.99867621124457, -71.75349423197208, 220], [-29.996964568219873, -71.7521560207641, 220], [-29.99696437241995, -71.7507330056961, 220], [-29.99761665426199, -71.75016101067708, 220]]}
</code>```

I tried:

```<code>with open('depth_echo.txt', 'w') as file:
    file.write(ujson.dumps(dictionary)

import json
a, b, c = "abc"
data = {(1,2,3):(a,b,c), (2,6,3):(6,3,2)}
on_disk = json.dumps(data.items())
</code>```

答:
write the dictionary as string

```<code> with open(r'test.txt','w+') as f:
     f.write(str(dictionary))
</code>```

read using eval

```<code>dic = ''
with open(r'test.txt','r') as f:
         for i in f.readlines():
            dic=i #string
dic = eval(dic) # this is orignal dict with instace dict
</code>```

Body:
I would like to save the dictionary having tuple on keys.

I tried pickle, ujson, json to save the dictionary. All of them did not work.

The dictionary has:

dictionary = {(-30, -29, -72, -71): [[-29.99867621124457, -71.75349423197208, 220], [-29.996964568219873, -71.7521560207641, 220], [-29.99696437241995, -71.7507330056961, 220], [-29.99761665426199, -71.75016101067708, 220]]}

I tried:

with open('depth_echo.txt', 'w') as file:
    file.write(ujson.dumps(dictionary)

import json
a, b, c = "abc"
data = {(1,2,3):(a,b,c), (2,6,3):(6,3,2)}
on_disk = json.dumps(data.items())

Body:
write the dictionary as string

 with open(r'test.txt','w+') as f:
     f.write(str(dictionary))

read using eval

dic = ''
with open(r'test.txt','r') as f:
         for i in f.readlines():
            dic=i #string
dic = eval(dic) # this is orignal dict with instace dict


问:
Facebook-wall like MySQL Structure problem
I don’t want any code just a how-to answer.

I’m trying to add a facebook-wall-like feature to a webapp (not commercial, only experimental).

The first thing I thought about was to store something like “1/2011-10-10/texthere,2/2011-10-10/texthere” where 1 would be the id & 2011-10-10 the date. Then I would explode it in php and have an array. (Then search for each id in the users table etc…)

But this has some problems. One would be if I have too many posts, it will be extremely heavy to a webpage and very difficult to limit results (without talking about character restriction for the array’s sake).

So I thought about two other solutions that have the pros and cons for me.

Use one table with 4 columns: Poster
id, Receiver id, Message, Date Posted

One table for each user (desperate
solution :))

So, should I direclty go for my first other solution or there is a better one?

Adv thanks

答: One table per user is a bad idea. Storing different values in different columns is what databases are made for. So it's probably a much better idea! ;-)</p>


问:
How to pass a class as a function argument?
I want to pass classes that conform to a protocol as function parameters. Concretely: I have a breadth/depth first search algorithm that builds on (respectively) a Queue or Stack data structure. I would love to have a single function that accepts either my Queue or Stack class as an argument. Potentially wrapped in an enum that hides the Queue and Stack objects for a more friendly breadth first or depth first.

I tried to use if or switch variants with simple Strings as either "depth" or "breadth" but variables declared in a closure are invisible to the outer scope and then I would need to repeat almost the whole function body for both cases.

Here is a minimal, reproducible example. The actual example is more complicated but I get the same error and believe it has the same underlying problem.

protocol Container {
    associatedtype T
    var container: [T] { get }
    func push(_ thing: T)
}

public class fakeQueue<T>: Container {
    internal var container: [T] = [T]()
    public func push(_ thing: T) { container.append(thing) }
}

public class fakeStack<T>: Container {
    internal var container: [T] = [T]()
    public func push(_ thing: T) { container.insert(thing, at: 0) }
}

func addValue<Algorithm: Container>(someValue: String, algorithm: Algorithm) {
    // next line raises: Cannot specialize a non-generic definition
    let importantVariable = algorithm<String>()
    importantVariable.push("Something important")
}

// The call raises: Argument type 'fakeQueue.Type' does not conform to expected type 'Container'
addValue(someValue: "_", algorithm: fakeQueue) // or fakeStack

```

I understand that I can't use algorithm<String>(). In this version it raises the Error: Cannot specialize a non-generic definition. But when I use fakeStack<String>() or fakeQueue<String>() and simply avoid specifying an algorithm: fakeQueue it works as expected.

I simply want to avoid having to make two functions.

答:
Some initial cautions

Passing types in Swift is nearly always a Bad Smell. Swift does not treat metatypes like types.

Moreover, your addValue can never be written as specified. You cannot pass a Container into it or out of it, because Container is a generic protocol, which cannot be used as a type (e.g. when specifying a function parameter or function return type).

You can make generic classes that conform to a generic protocol, thus guaranteeing that you can push to an instance of any such class. But you cannot further unify them under some single head, because they are both generics and might be resolved differently.

Having said all that, we can probably make a pretty good approach to your idea, as I shall now demonstrate.

Revising your protocol and classes

Thinking about the general sort of thing you're trying to do, I suspect you're after an architecture somewhat like this:

```<code>protocol Pushable : class {
    associatedtype T
    init(_ t:T)
    var contents : [T] {get set}
    func push(_ t:T)
}

final class Stack<TT> : Pushable {
    init(_ t:TT) { self.contents = [t]}
    var contents = [TT]()
    func push(_ t:TT) {
        self.contents.append(t)
    }
}

final class Queue<TT> : Pushable {
    init(_ t:TT) { self.contents = [t]}
    var contents = [TT]()
    func push(_ t:TT) {
        self.contents.insert(t, at:0)
    }
}
</code>```

I've called your Container by the name Pushable just because the ability to call push is all we have in common right now. You'll notice that I've added an init to the Pushable protocol; that's so that we have a way of resolving a Pushable generic. Whatever value we initialize a Pushable with, its type becomes its generic parameterized type; at the moment, that instance goes into the contents and further instances can be pushed, though I'll show later how to change that.

So now we can say stuff like this:

```<code>let stack = Stack("howdy")
stack.push("farewell")
let queue = Queue(1)
queue.push(2)
</code>```

The joy of where clauses

Okay, now let's return to your desire to push an arbitrary value to an arbitrary Pushable. The way to express that is to use Pushable, not as a passed type or a return type, but as a constraint on a generic. That is something we are allowed to use a generic protocol for:

```<code>func push<TTT,P>(_ what:TTT, to pushable: P)
    where P:Pushable, P.T == TTT  {
        pushable.push(what)
}
</code>```

A factory method and passing a metatype

But you'll no doubt notice that I still haven't supplied a function with the ability to make a Queue-or-Stack. To do that, we would indeed need to pass a metatype. Aha, but I've given Pushable an init requirement! So now we can do it:

```<code>func createStackOrQueue<TTT,P>(_ what:TTT, type pushableType: P.Type) -> P
    where P:Pushable, P.T == TTT {
       return P.init(what)
}

let stack = createStackOrQueue("howdy", type:Stack.self)
</code>```

That isn't identically what you were trying to do, but perhaps it's close enough to get you going.

Factory method, passing only metatypes

If you really insist on passing metatypes around, let's change init so that it too takes a metatype:

```<code>protocol Pushable : class {
    associatedtype T
    init(_ t:T.Type)
    var contents : [T] {get set}
    func push(_ t:T)
}

final class Stack<TT> : Pushable {
    init(_ t:TT.Type) { self.contents = [TT]()}
    var contents = [TT]()
    func push(_ t:TT) {
        self.contents.append(t)
    }
}

final class Queue<TT> : Pushable {
    init(_ t:TT.Type) { self.contents = [TT]()}
    var contents = [TT]()
    func push(_ t:TT) {
        self.contents.insert(t, at:0)
    }
}
</code>```

Now we can write a generic factory function very close to what you were originally after, where both the Pushable (Stack or Queue) and the content type are expressed as metatypes:

```<code>func createPushable<TTT,P>(_ whatElementType:TTT.Type, type pushableType: P.Type) -> P
    where P:Pushable, P.T == TTT {
        return P.init(TTT.self)
}
</code>```

I can't say I approve of that sort of thing, but at least you can see how it's done.

Something very close to your original idea

And now I think we can make something very close to your original conception, where we say whether we want a stack or a queue along with something to push onto it! Ready?

```<code>func createPushable<TTT,P>(type pushableType: P.Type, andPush element:TTT) -> P
    where P:Pushable, P.T == TTT {
        let result = P.init(type(of:element).self)
        result.push(element)
        return result
}
</code>```

And here's how to call it:

```<code>let stack = createPushable(type:Stack.self, andPush:"howdy")
</code>```

Body:
I want to pass classes that conform to a protocol as function parameters. Concretely: I have a breadth/depth first search algorithm that builds on (respectively) a Queue or Stack data structure. I would love to have a single function that accepts either my Queue or Stack class as an argument. Potentially wrapped in an enum that hides the Queue and Stack objects for a more friendly breadth first or depth first.

I tried to use if or switch variants with simple Strings as either "depth" or "breadth" but variables declared in a closure are invisible to the outer scope and then I would need to repeat almost the whole function body for both cases.

Here is a minimal, reproducible example. The actual example is more complicated but I get the same error and believe it has the same underlying problem.

protocol Container {
    associatedtype T
    var container: [T] { get }
    func push(_ thing: T)
}

public class fakeQueue<T>: Container {
    internal var container: [T] = [T]()
    public func push(_ thing: T) { container.append(thing) }
}

public class fakeStack<T>: Container {
    internal var container: [T] = [T]()
    public func push(_ thing: T) { container.insert(thing, at: 0) }
}

func addValue<Algorithm: Container>(someValue: String, algorithm: Algorithm) {
    // next line raises: Cannot specialize a non-generic definition
    let importantVariable = algorithm<String>()
    importantVariable.push("Something important")
}

// The call raises: Argument type 'fakeQueue.Type' does not conform to expected type 'Container'
addValue(someValue: "_", algorithm: fakeQueue) // or fakeStack

I understand that I can't use algorithm<String>(). In this version it raises the Error: Cannot specialize a non-generic definition. But when I use fakeStack<String>() or fakeQueue<String>() and simply avoid specifying an algorithm: fakeQueue it works as expected.

I simply want to avoid having to make two functions.

Body:
Some initial cautions

Passing types in Swift is nearly always a Bad Smell. Swift does not treat metatypes like types.

Moreover, your addValue can never be written as specified. You cannot pass a Container into it or out of it, because Container is a generic protocol, which cannot be used as a type (e.g. when specifying a function parameter or function return type).

You can make generic classes that conform to a generic protocol, thus guaranteeing that you can push to an instance of any such class. But you cannot further unify them under some single head, because they are both generics and might be resolved differently.

Having said all that, we can probably make a pretty good approach to your idea, as I shall now demonstrate.

Revising your protocol and classes

Thinking about the general sort of thing you're trying to do, I suspect you're after an architecture somewhat like this:

protocol Pushable : class {
    associatedtype T
    init(_ t:T)
    var contents : [T] {get set}
    func push(_ t:T)
}

final class Stack<TT> : Pushable {
    init(_ t:TT) { self.contents = [t]}
    var contents = [TT]()
    func push(_ t:TT) {
        self.contents.append(t)
    }
}

final class Queue<TT> : Pushable {
    init(_ t:TT) { self.contents = [t]}
    var contents = [TT]()
    func push(_ t:TT) {
        self.contents.insert(t, at:0)
    }
}

I've called your Container by the name Pushable just because the ability to call push is all we have in common right now. You'll notice that I've added an init to the Pushable protocol; that's so that we have a way of resolving a Pushable generic. Whatever value we initialize a Pushable with, its type becomes its generic parameterized type; at the moment, that instance goes into the contents and further instances can be pushed, though I'll show later how to change that.

So now we can say stuff like this:

let stack = Stack("howdy")
stack.push("farewell")
let queue = Queue(1)
queue.push(2)

The joy of where clauses

Okay, now let's return to your desire to push an arbitrary value to an arbitrary Pushable. The way to express that is to use Pushable, not as a passed type or a return type, but as a constraint on a generic. That is something we are allowed to use a generic protocol for:

func push<TTT,P>(_ what:TTT, to pushable: P)
    where P:Pushable, P.T == TTT  {
        pushable.push(what)
}

A factory method and passing a metatype

But you'll no doubt notice that I still haven't supplied a function with the ability to make a Queue-or-Stack. To do that, we would indeed need to pass a metatype. Aha, but I've given Pushable an init requirement! So now we can do it:

func createStackOrQueue<TTT,P>(_ what:TTT, type pushableType: P.Type) -> P
    where P:Pushable, P.T == TTT {
       return P.init(what)
}

let stack = createStackOrQueue("howdy", type:Stack.self)

That isn't identically what you were trying to do, but perhaps it's close enough to get you going.

Factory method, passing only metatypes

If you really insist on passing metatypes around, let's change init so that it too takes a metatype:

protocol Pushable : class {
    associatedtype T
    init(_ t:T.Type)
    var contents : [T] {get set}
    func push(_ t:T)
}

final class Stack<TT> : Pushable {
    init(_ t:TT.Type) { self.contents = [TT]()}
    var contents = [TT]()
    func push(_ t:TT) {
        self.contents.append(t)
    }
}

final class Queue<TT> : Pushable {
    init(_ t:TT.Type) { self.contents = [TT]()}
    var contents = [TT]()
    func push(_ t:TT) {
        self.contents.insert(t, at:0)
    }
}

Now we can write a generic factory function very close to what you were originally after, where both the Pushable (Stack or Queue) and the content type are expressed as metatypes:

func createPushable<TTT,P>(_ whatElementType:TTT.Type, type pushableType: P.Type) -> P
    where P:Pushable, P.T == TTT {
        return P.init(TTT.self)
}

I can't say I approve of that sort of thing, but at least you can see how it's done.

Something very close to your original idea

And now I think we can make something very close to your original conception, where we say whether we want a stack or a queue along with something to push onto it! Ready?

func createPushable<TTT,P>(type pushableType: P.Type, andPush element:TTT) -> P
    where P:Pushable, P.T == TTT {
        let result = P.init(type(of:element).self)
        result.push(element)
        return result
}

And here's how to call it:

let stack = createPushable(type:Stack.self, andPush:"howdy")


问:
PHP External IP
I am using software called gns3 to build networks.

I have the need to find out devices external ip from within an gns3 internal network. This would be like a pc behind a router doing NAT.

Please could someone tell me if there is a way that you can echo out the clients external ip in php so I can add a web server to one of my virtual networks within gns3 so I can visit it on some devices and find their external ip’s for testing?

Thanks in advance

答:
You need to make a request to an external website that could tell you the ip address you have. You may use checkip.dyndns.org - click the link to see your own ip addres.

if you want to do that from php here is an example code:

```<code><?php

//get website content as a string
$ipCheckUrl = 'http://checkip.dyndns.org';
$subject = file_get_contents($ipCheckUrl);

//extract from string just ip address
$pattern = '/Current IP Address\:\s*(\d+\.\d+\.\d+\.\d+)/U';
$ip = preg_match($pattern,$subject,$result) ? $result[1] : 'Error';

//print ip address.
echo $ip;
</code>```

Title: PHP External IP

Body:
You need to make a request to an external website that could tell you the ip address you have. You may use checkip.dyndns.org - click the link to see your own ip addres.

if you want to do that from php here is an example code:

<?php

//get website content as a string
$ipCheckUrl = 'http://checkip.dyndns.org';
$subject = file_get_contents($ipCheckUrl);

//extract from string just ip address
$pattern = '/Current IP Address\:\s*(\d+\.\d+\.\d+\.\d+)/U';
$ip = preg_match($pattern,$subject,$result) ? $result[1] : 'Error';

//print ip address.
echo $ip;


问:
Connecting to crypto exchange api. Error while "sign & send" message using methods "POST" or "DELETE"?
I'm quite new in coding and was hoping I get an advice how to solve my problem.
I'm writing a java code to connect to trade.io API, but I can't figure out how to submit the correct encrypted message to the exchange using "POST" and "DELETE".

So far, I managed to work out how to receive information with "GET", but no success on the others.

Here is what I wrote so far:

```<code>/*
* CancelOrder cancels an existing order ==> This doesn't work!
*/
    public String CancelOrder(String orderId) throws MalformedURLException,
        IOException {

        return signAndSend("/order/" + orderId, "DELETE");
    }

     /*
     * Reads the open orders in the account ==> This works!
     */
    public String getOpenOrders(String symbol) throws MalformedURLException,
        IOException {
        return signAndSend("/openOrders/" + symbol, "GET");
    }

    /*
     * Signs and Sends signature. This method is called when signature is
      needed.
     */
    private String signAndSend(String url, String method) throws
    MalformedURLException, IOException {

        String nonce = String.valueOf(System.currentTimeMillis());
        String baseUrl = UrlTradeio.urlV1;
        String ts = "?ts=" + nonce;

        String sign = hmac512Digest(ts, TRADEIO_SECRET_KEY).toUpperCase();

        HttpURLConnection con = (HttpURLConnection) new URL(baseUrl + url + ts).openConnection();
        con.setRequestProperty("Sign", sign);
        con.setRequestProperty("Key", TRADEIO_API_KEY);
        con.setRequestMethod(method);
        con.connect();

        InputStream response = con.getInputStream();
//
        try (Scanner scanner = new Scanner(response)) {

            String responseBody = scanner.next();

            return responseBody;
        }

    }
</code>```

The exchange provided very thorough example in C# here:

https://github.com/tradeio/api-csharpclient/blob/master/Tradeio.Client/TradeioApi.cs

Here is the output for "getOpenOrders" and the error message when I try to close the same.

ktos_eth open orders are: {"code":0,"timestamp":1559338453064,"orders":[{"orderId":"-72057593948251267","total":"0.0","orderType":"limit","commission":"0.0","createdAt":"2019-01-23T17:36:55.8633777Z","unitsFilled":"0.0","isPending":true,"status":"Working","type":"sell","requestedAmount":"75.0","baseAmount":"0.0","quoteAmount":"0.0","price":"0.00014000","isLimit":true,"loanRate":"0.0","rateStop":"0.0","instrument":"ktos_eth","requestedPrice":"0.00014000","remainingAmount":"75.0"}]}

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: https://api.exchange.trade.io/api/v1/order/-72057593948251267?ts=1559338452695
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1913)

Thanks in advance for looking into it

Cheers
Alex

答:
So - 403 means you authenticated properly and were known by the system - but the system determined you lacked the permissions. Essentially it found you as a user - but said you didn't have access to what you wanted to do. More info on status codes here https://httpstatuses.com/

Having worked with these API keys before - I wonder if you don't have the API key set to allow you to perform the actions that are giving you a 403.

I recommend reviewing the API key you created on the crypto site. Make sure that not only do you have a key - but you have enabled that key to be used with the actions you would like. It looks like trade.io calls them "Permissions" and can be reviewed here https://trade.io/en/api.

My guess is you only have "Read Access" enabled for that key, not "Trading".

And welcome to Stack Overflow :-) .

Body:
I'm quite new in coding and was hoping I get an advice how to solve my problem.
I'm writing a java code to connect to trade.io API, but I can't figure out how to submit the correct encrypted message to the exchange using "POST" and "DELETE".

So far, I managed to work out how to receive information with "GET", but no success on the others.

Here is what I wrote so far:

/*
* CancelOrder cancels an existing order ==> This doesn't work!
*/
    public String CancelOrder(String orderId) throws MalformedURLException,
        IOException {

        return signAndSend("/order/" + orderId, "DELETE");
    }

     /*
     * Reads the open orders in the account ==> This works!
     */
    public String getOpenOrders(String symbol) throws MalformedURLException,
        IOException {
        return signAndSend("/openOrders/" + symbol, "GET");
    }

    /*
     * Signs and Sends signature. This method is called when signature is
      needed.
     */
    private String signAndSend(String url, String method) throws
    MalformedURLException, IOException {

        String nonce = String.valueOf(System.currentTimeMillis());
        String baseUrl = UrlTradeio.urlV1;
        String ts = "?ts=" + nonce;

        String sign = hmac512Digest(ts, TRADEIO_SECRET_KEY).toUpperCase();

        HttpURLConnection con = (HttpURLConnection) new URL(baseUrl + url + ts).openConnection();
        con.setRequestProperty("Sign", sign);
        con.setRequestProperty("Key", TRADEIO_API_KEY);
        con.setRequestMethod(method);
        con.connect();

        InputStream response = con.getInputStream();
//
        try (Scanner scanner = new Scanner(response)) {

            String responseBody = scanner.next();

            return responseBody;
        }

    }

The exchange provided very thorough example in C# here:

https://github.com/tradeio/api-csharpclient/blob/master/Tradeio.Client/TradeioApi.cs

Here is the output for "getOpenOrders" and the error message when I try to close the same.

ktos_eth open orders are: {"code":0,"timestamp":1559338453064,"orders":[{"orderId":"-72057593948251267","total":"0.0","orderType":"limit","commission":"0.0","createdAt":"2019-01-23T17:36:55.8633777Z","unitsFilled":"0.0","isPending":true,"status":"Working","type":"sell","requestedAmount":"75.0","baseAmount":"0.0","quoteAmount":"0.0","price":"0.00014000","isLimit":true,"loanRate":"0.0","rateStop":"0.0","instrument":"ktos_eth","requestedPrice":"0.00014000","remainingAmount":"75.0"}]}

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: https://api.exchange.trade.io/api/v1/order/-72057593948251267?ts=1559338452695
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1913)

Thanks in advance for looking into it

Cheers
Alex


问:
Replacing Invalid XML characters from an excel file and writing it back to disk causes file is corrupted error on opening in MS Excel
A little background on problem:

We have an ASP.NET MVC5 Application where we use FlexMonster to show the data in grid. The data source is a stored procedure that brings all the data into the UI grid, and once user clicks on export button, it exports the report to Excel. However, in some cases export to excel is failing.
Some of the data has some invalid characters, and it is not possible/feasible to fix the source as suggested here

My approach so far:

EPPlus library fails on initializing the workbook as the input excel file contains some invalid XML characters. I could find that the file is dumped with some invalid character in it. I looked into the possible approaches .

Firstly, I identified the problematic character in the excel file. I first tried to replace the invalid character with blank space manually using Notepad++ and the EPPlus could successfully read the file.

Now using the approaches given in other SO thread here and here, I replaced all possible occurrences of invalid chars. I am using at the moment

XmlConvert.IsXmlChar

method to find out the problematic XML character and replacing with blank space.

I created a sample program where I am trying to work on the problematic excel sheet.

```<code>//in main method
String readFile = File.ReadAllText(filePath);
string content = RemoveInvalidXmlChars(readFile);
File.WriteAllText(filePath, content);

//removal of invalid characters
        static string RemoveInvalidXmlChars(string inputText)
        {
            StringBuilder withoutInvalidXmlCharsBuilder = new StringBuilder();
            int firstOccurenceOfRealData = inputText.IndexOf("<t>");
            int lastOccurenceOfRealData = inputText.LastIndexOf("</t>");

            if (firstOccurenceOfRealData < 0 ||
                lastOccurenceOfRealData < 0 ||
                firstOccurenceOfRealData > lastOccurenceOfRealData)
                return inputText;

            withoutInvalidXmlCharsBuilder.Append(inputText.Substring(0, firstOccurenceOfRealData));
            int remaining = lastOccurenceOfRealData - firstOccurenceOfRealData;
            string textToCheckFor = inputText.Substring(firstOccurenceOfRealData, remaining);

            foreach (char c in textToCheckFor)
            {
                withoutInvalidXmlCharsBuilder.Append((XmlConvert.IsXmlChar(c)) ? c : ' ');
            }
      withoutInvalidXmlCharsBuilder.Append(inputText.Substring(lastOccurenceOfRealData));

            return withoutInvalidXmlCharsBuilder.ToString();

        }
</code>```

If I replaces the problematic character manually using notepad++, then the file opens fine in MSExcel. The above mentioned code successfully replaces the same invalid character and writes the content back to the file. However, when I try to open the excel file using MS Excel, it throws an error saying that file may have been corrupted and no content is displayed (snapshots  below). Moreover, Following code

```<code>var excelPackage = new ExcelPackage(new FileInfo(filePath));
</code>```

on the file that I updated via Notepad++, throws following exception

```<code>"CRC error: the file being extracted appears to be corrupted. Expected 0x7478AABE, Actual 0xE9191E00"}
</code>```

My Questions:

Is my approach to modify content this way correct?

If yes, How can I write updated string to an Excel file?

If my approach is wrong then, How can I proceed to get rid of invalid XML chars?

Errors shown on opening file (without invalid XML char):

First Pop up

When I click on yes

Thanks in advance !

答:
It does sounds like a binary (presumable XLSX) file based on your last comment.  To confirm, open the file created by the FlexMonster with 7zip.  If it opens properly and you see a bunch of XML files in folders, its a XLSX.

In that case, a search/replace on a binary file sounds like a very bad idea.  It might work on the XML parts but might also replace legit chars in other parts.  I think the better approach would be to do as @PanagiotisKanavos suggests and use ZipArchive.  But  you have to do rebuild it in the right order otherwise Excel complains.  Similar to how it was done here  https://stackoverflow.com/a/33312038/1324284, you could do something like this:

```<code>public static void ReplaceXmlString(this ZipArchive xlsxZip, FileInfo outFile, string oldString, string newstring)
{
    using (var outStream = outFile.Open(FileMode.Create, FileAccess.ReadWrite))
    using (var copiedzip = new ZipArchive(outStream, ZipArchiveMode.Update))
    {
        //Go though each file in the zip one by one and copy over to the new file - entries need to be in order
        foreach (var entry in xlsxZip.Entries)
        {
            var newentry = copiedzip.CreateEntry(entry.FullName);
            var newstream = newentry.Open();
            var orgstream = entry.Open();

            //Copy non-xml files over
            if (!entry.Name.EndsWith(".xml"))
            {
                orgstream.CopyTo(newstream);
            }
            else
            {
                //Load the xml document to manipulate
                var xdoc = new XmlDocument();
                xdoc.Load(orgstream);

                var xml = xdoc.OuterXml.Replace(oldString, newstring);
                xdoc = new XmlDocument();
                xdoc.LoadXml(xml);

                xdoc.Save(newstream);
            }

            orgstream.Close();
            newstream.Flush();
            newstream.Close();
        }
    }
}
</code>```

When it is used like this:

```<code>[TestMethod]
public void ReplaceXmlTest()
{
    var datatable = new DataTable("tblData");
    datatable.Columns.AddRange(new[]
    {
        new DataColumn("Col1", typeof (int)),
        new DataColumn("Col2", typeof (int)),
        new DataColumn("Col3", typeof (string))
    });

    for (var i = 0; i < 10; i++)
    {
        var row = datatable.NewRow();
        row[0] = i;
        row[1] = i * 10;
        row[2] = i % 2 == 0 ? "ABCD" : "AXCD";
        datatable.Rows.Add(row);
    }

    using (var pck = new ExcelPackage())
    {
        var workbook = pck.Workbook;
        var worksheet = workbook.Worksheets.Add("source");

        worksheet.Cells.LoadFromDataTable(datatable, true);
        worksheet.Tables.Add(worksheet.Cells["A1:C11"], "Table1");

        //Now similulate the copy/open of the excel file into a zip archive
        using (var orginalzip = new ZipArchive(new MemoryStream(pck.GetAsByteArray()), ZipArchiveMode.Read))
        {
            var fi = new FileInfo(@"c:\temp\ReplaceXmlTest.xlsx");
            if (fi.Exists)
                fi.Delete();

            orginalzip.ReplaceXmlString(fi, "AXCD", "REPLACED!!");
        }
    }
}
</code>```

Gives this:

Just keep in mind that this is completely brute force.  Anything you can do to make the file filter smarter rather then simply doing ALL xml files would be a very good thing.  Maybe limit it to the SharedString.xml file if that is where the problem lies or in the xml files in the worksheet folders.  Hard to say without knowing more about the data.

Body:
A little background on problem:

We have an ASP.NET MVC5 Application where we use FlexMonster to show the data in grid. The data source is a stored procedure that brings all the data into the UI grid, and once user clicks on export button, it exports the report to Excel. However, in some cases export to excel is failing.
Some of the data has some invalid characters, and it is not possible/feasible to fix the source as suggested here

My approach so far:

EPPlus library fails on initializing the workbook as the input excel file contains some invalid XML characters. I could find that the file is dumped with some invalid character in it. I looked into the possible approaches .

Firstly, I identified the problematic character in the excel file. I first tried to replace the invalid character with blank space manually using Notepad++ and the EPPlus could successfully read the file.

Now using the approaches given in other SO thread here and here, I replaced all possible occurrences of invalid chars. I am using at the moment

XmlConvert.IsXmlChar

method to find out the problematic XML character and replacing with blank space.

I created a sample program where I am trying to work on the problematic excel sheet.

//in main method
String readFile = File.ReadAllText(filePath);
string content = RemoveInvalidXmlChars(readFile);
File.WriteAllText(filePath, content);

//removal of invalid characters
        static string RemoveInvalidXmlChars(string inputText)
        {
            StringBuilder withoutInvalidXmlCharsBuilder = new StringBuilder();
            int firstOccurenceOfRealData = inputText.IndexOf("<t>");
            int lastOccurenceOfRealData = inputText.LastIndexOf("</t>");

            if (firstOccurenceOfRealData < 0 ||
                lastOccurenceOfRealData < 0 ||
                firstOccurenceOfRealData > lastOccurenceOfRealData)
                return inputText;

            withoutInvalidXmlCharsBuilder.Append(inputText.Substring(0, firstOccurenceOfRealData));
            int remaining = lastOccurenceOfRealData - firstOccurenceOfRealData;
            string textToCheckFor = inputText.Substring(firstOccurenceOfRealData, remaining);

            foreach (char c in textToCheckFor)
            {
                withoutInvalidXmlCharsBuilder.Append((XmlConvert.IsXmlChar(c)) ? c : ' ');
            }
      withoutInvalidXmlCharsBuilder.Append(inputText.Substring(lastOccurenceOfRealData));

            return withoutInvalidXmlCharsBuilder.ToString();

        }

If I replaces the problematic character manually using notepad++, then the file opens fine in MSExcel. The above mentioned code successfully replaces the same invalid character and writes the content back to the file. However, when I try to open the excel file using MS Excel, it throws an error saying that file may have been corrupted and no content is displayed (snapshots  below). Moreover, Following code

var excelPackage = new ExcelPackage(new FileInfo(filePath));

on the file that I updated via Notepad++, throws following exception

"CRC error: the file being extracted appears to be corrupted. Expected 0x7478AABE, Actual 0xE9191E00"}

My Questions:

Is my approach to modify content this way correct?

If yes, How can I write updated string to an Excel file?

If my approach is wrong then, How can I proceed to get rid of invalid XML chars?

Errors shown on opening file (without invalid XML char):

First Pop up

When I click on yes

Thanks in advance !

Body:
It does sounds like a binary (presumable XLSX) file based on your last comment.  To confirm, open the file created by the FlexMonster with 7zip.  If it opens properly and you see a bunch of XML files in folders, its a XLSX.

In that case, a search/replace on a binary file sounds like a very bad idea.  It might work on the XML parts but might also replace legit chars in other parts.  I think the better approach would be to do as @PanagiotisKanavos suggests and use ZipArchive.  But  you have to do rebuild it in the right order otherwise Excel complains.  Similar to how it was done here  https://stackoverflow.com/a/33312038/1324284, you could do something like this:

public static void ReplaceXmlString(this ZipArchive xlsxZip, FileInfo outFile, string oldString, string newstring)
{
    using (var outStream = outFile.Open(FileMode.Create, FileAccess.ReadWrite))
    using (var copiedzip = new ZipArchive(outStream, ZipArchiveMode.Update))
    {
        //Go though each file in the zip one by one and copy over to the new file - entries need to be in order
        foreach (var entry in xlsxZip.Entries)
        {
            var newentry = copiedzip.CreateEntry(entry.FullName);
            var newstream = newentry.Open();
            var orgstream = entry.Open();

            //Copy non-xml files over
            if (!entry.Name.EndsWith(".xml"))
            {
                orgstream.CopyTo(newstream);
            }
            else
            {
                //Load the xml document to manipulate
                var xdoc = new XmlDocument();
                xdoc.Load(orgstream);

                var xml = xdoc.OuterXml.Replace(oldString, newstring);
                xdoc = new XmlDocument();
                xdoc.LoadXml(xml);

                xdoc.Save(newstream);
            }

            orgstream.Close();
            newstream.Flush();
            newstream.Close();
        }
    }
}

When it is used like this:

[TestMethod]
public void ReplaceXmlTest()
{
    var datatable = new DataTable("tblData");
    datatable.Columns.AddRange(new[]
    {
        new DataColumn("Col1", typeof (int)),
        new DataColumn("Col2", typeof (int)),
        new DataColumn("Col3", typeof (string))
    });

    for (var i = 0; i < 10; i++)
    {
        var row = datatable.NewRow();
        row[0] = i;
        row[1] = i * 10;
        row[2] = i % 2 == 0 ? "ABCD" : "AXCD";
        datatable.Rows.Add(row);
    }

    using (var pck = new ExcelPackage())
    {
        var workbook = pck.Workbook;
        var worksheet = workbook.Worksheets.Add("source");

        worksheet.Cells.LoadFromDataTable(datatable, true);
        worksheet.Tables.Add(worksheet.Cells["A1:C11"], "Table1");

        //Now similulate the copy/open of the excel file into a zip archive
        using (var orginalzip = new ZipArchive(new MemoryStream(pck.GetAsByteArray()), ZipArchiveMode.Read))
        {
            var fi = new FileInfo(@"c:\temp\ReplaceXmlTest.xlsx");
            if (fi.Exists)
                fi.Delete();

            orginalzip.ReplaceXmlString(fi, "AXCD", "REPLACED!!");
        }
    }
}

Gives this:

Just keep in mind that this is completely brute force.  Anything you can do to make the file filter smarter rather then simply doing ALL xml files would be a very good thing.  Maybe limit it to the SharedString.xml file if that is where the problem lies or in the xml files in the worksheet folders.  Hard to say without knowing more about the data.