问:
Modeling an analog psuedo random LFO signal (low pass filtering in Javascript)
I'm writing a Javascript program to programmatically create MIDI signals for procedurally generated music that uses external inputs to modify/manipulate the sound in response to changes in an environment.

One of the things I'm trying to do is figure out how to program an analog pseudo random low frequency oscillator (LFO) signal like the dashed line in the image below:

This signal will drive MIDI effects like pitch bend or modulation.

The function should take a single value input that controls how dramatically the signal fluctuates.  When the input is 0, the resulting signal should be 0, or a flat line.  And as the input value increases, the signal should become proportionally more and more erratic.

I feel like I have an idea of how to generate a step function (like the solid line in the image above) that achieves those goals, but I have no idea how to "smooth" it (i.e. low pass filter it) to get a continuous curve like the dashed line.  Ultimately that smoothed/continuous/analog function would be sampled, say, every 100 ms and broad cast as a new MIDI pitch bend instruction, etc.

答:
I would just use an existing animation library, such as TweenJS.  https://www.createjs.com/docs/tweenjs/modules/TweenJS.html  These libraries are normally meant for visual use, but they can be used generically as well.

Untested, but try something like this:

```<code>const cc = {
  modwheel: 0
};
createjs.Tween.get(cc).to({modwheel: 127}, 1000);
</code>```

Then, just observe the cc.modhweel property every 100ms or whatever "frame" you want.

See also:  https://stackoverflow.com/a/13501577/362536

Body:
I would just use an existing animation library, such as TweenJS.  https://www.createjs.com/docs/tweenjs/modules/TweenJS.html  These libraries are normally meant for visual use, but they can be used generically as well.

Untested, but try something like this:

const cc = {
  modwheel: 0
};
createjs.Tween.get(cc).to({modwheel: 127}, 1000);

Then, just observe the cc.modhweel property every 100ms or whatever "frame" you want.

See also:  https://stackoverflow.com/a/13501577/362536


来源: stackexchange

问:
How do I set up a 3 node Kafka Cluster
I need to setup 3 node Kafka cluster with 30 topics connecting to number of source DBs. I am not sure an exact number of messages to be processed but I guess there will be millions per day.

The retention of Kafka Topics and data is to be set at 30 days. I should able to get back to 30 days earlier data in case needed.

Could you please advise me how I should proceed.

Many Thanks

答:
SETUP: You can setup multi broker cluster by following instructions in given documentation.
https://kafka.apache.org/quickstart#quickstart_multibroker

In 3 node cluster, you should configure 3 brokers and 3 zookeeper nodes and replication factor 3 for your topics. Depending on your requirement/use case, you can have 3 or more partitions for each topic.

RETENTION: You can define retention policy using log.retention.hours
https://kafka.apache.org/documentation/#brokerconfigs

You should gather more information on how your data would be produced and consumed. Depending on your processing logic at consumer side, consuming one million messages per partition shouldn't be big deal. Though, You can add more partitions for parallel processing and increased throughput.

You should be specific in your question, but i tried and hope this helps!

ContentLicense: CC BY-SA 3.0

Title: How do I set up a 3 node Kafka Cluster


问:
How to install extra packages in Google Colaboratory's VM?
I'm playing with Google Colaboratory, and noticed right off the bat that tqdm is not pre-installed. Is there any way to install additional packages?

答:
Yup. You can use pip or apt to install packages as needed.

One example for pip is in the welcome notebook:

```<code>!pip install -q matplotlib-venn
from matplotlib_venn import venn2
venn2(subsets = (3, 2, 1))
</code>```

An example for apt is in the snippets:

```<code>!apt update && apt install -y libfluidsynth1
</code>```

In the case of tdqm, !pip install tqdm worked for me.

Body:
Yup. You can use pip or apt to install packages as needed.

One example for pip is in the welcome notebook:

!pip install -q matplotlib-venn
from matplotlib_venn import venn2
venn2(subsets = (3, 2, 1))

An example for apt is in the snippets:

!apt update && apt install -y libfluidsynth1

In the case of tdqm, !pip install tqdm worked for me.


问:
Reverse Ajax responseText detection
This function gets called when an ajax requests readyState == 3,

```<code>function(context, xhrobj, itself){
    //Test if context.responseText is available here.

    var text = context.responseText;
    //Do stuff
}
</code>```

How would I be able to test if context.responseText is available? I am currently doing this,

```<code>if ($.browser.msie) return false;
</code>```

But I really don't want to do browser detection, Is there a way to detect if context.responseText is unavailabe? Specifically for IE7/8, I am not supporting 6 or below.

I've tried,

```<code>if('responseText' in context) return false;
</code>```

which doesn't work because it is in context, just not available, and

```<code>try{context.responseText;} catch(x){return false;}
</code>```

but this seems like a hack.

答:
The Context will not have initialized the response object whether text, xml.  Therefore, unless you implement some sort of an observer for the actual creation/initialization/population of the response the 2nd try...catch seems to do what you need it to do.  It is not a hack, as the context.responseText isn't created and therefore, uninitialized.

I will continue to monitor this thread, but I think IMHO your approach is appropriate.

best of luck,

Josh

ContentLicense: CC BY-SA 2.5

Title: Reverse Ajax responseText detection

Body:
This function gets called when an ajax requests readyState == 3,

function(context, xhrobj, itself){
    //Test if context.responseText is available here.

    var text = context.responseText;
    //Do stuff
}

How would I be able to test if context.responseText is available? I am currently doing this,

if ($.browser.msie) return false;

But I really don't want to do browser detection, Is there a way to detect if context.responseText is unavailabe? Specifically for IE7/8, I am not supporting 6 or below.

I've tried,

if('responseText' in context) return false;

which doesn't work because it is in context, just not available, and

try{context.responseText;} catch(x){return false;}

but this seems like a hack.


问:
Navigation Controller Loop

I'm making an app which has a shopping cart feature. The shopping cart VC is accessible from several VCs via a button on the navigation bar. So far I only have one Navigation Controller and as shown in the image, each VC takes me to the next one, nothing fancy. The 3rd VC (blue arrow pointing to) is a VC that shows the product/item's details and enables me to add it to the cart.

Problem comes with the Shopping Cart VC. To edit the item, I'd like to re-use the same product/item's details (blue arrow pointing to) VC I used earlier.

Right now, I don't really have an issue but I have noticed that once I created the blue segue, the Navigation Bar of the 3rd VC disappeared in the Storyboard however I was still able to see it when I ran the app.

NOTE:

All the segues in the picture are "Show"

The shopping cart VC doesn't have a button to show itself like the other 3 does. So technically I prevented endless/loop of the shopping cart VC - product/item details VC showing one another.

My questions are:

Is it wrong to design the app that way with a VC going to another VC and that other VC can go back to the first VC? Am I going to face issues down the road, perhaps memory leaks of some sort?

Is there a better way to achieve what I am trying to achieve?

If someone needs further explanation please let me know and I'll edit my question.

EDIT: To clarify, the blue segue is basically a button in a UITableView in the cart VC. If you tap that button, it should open the product/item details VC and lets you edit the item's color, etc. In the item details VC, instead of adding the item as a new item to the cart, I'd show an Edit button which would send the edit request to the API and dismiss the VC back to the shopping cart, or I could use the back button in the navigation controller to get back to the shopping cart.

EDIT2: @beshio

Thanks for the answer. However VC1 is actually my root VC where all the app starts. I didn't get why removed VCs from the Navigation Controller's stack. I would like the Back button to work as intended.

So far I have achieved what I wanted but I'm afraid that having two VCs segue-ing to each other would cause a problem. I have already disabled the Cart button in VC3 in case VC3 was presented from the Cart so loops would be prevented. I am only worried about any memory leaks down the road.

答:
Awesome.

In these scenarios you should use setViewControllers([UIViewController], animated: Bool) to get the desired viewcontrollers in the stack when you get many controllers stacked up in cycles.

Other way is you write your own class derived from UINavigationController having methods, pushToCheckout(animated:Bool), popToEditCart(animated:Bool) , removeIntermediateControllers()

Title: Navigation Controller Loop


问:
Post request with raw body using NSURLSession
I have stuck here. Below is my code for Post request with raw body using NSURLSession. I got response = NULL and no error.

```<code>NSString* stringRequest = @"https://chocudan.com/api/shops/by_ids";
NSURL* urlRequest = [NSURL URLWithString:stringRequest];

NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:urlRequest];
request.HTTPMethod = @"POST";

NSString* bodyRequest = @"563c268b84ba489c4729f149";

//I have to tried a base64 convert here but still not work.
//request.HTTPBody = [NSData base64DataFromString:bodyRequest];

request.HTTPBody = [bodyRequest dataUsingEncoding:NSUTF8StringEncoding];

NSURLSessionConfiguration* configureSession = [NSURLSessionConfiguration defaultSessionConfiguration];

configureSession.HTTPAdditionalHeaders = @{@"Content-Type" : @"application/json charset=utf-8",
                                           @"Content-Lenght" : @"180"};

NSURLSession* session = [NSURLSession sessionWithConfiguration:configureSession];

NSURLSessionDataTask* dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

    NSHTTPURLResponse* respHttp = (NSHTTPURLResponse*) response;

    if (!error && respHttp.statusCode == 200) {

        NSDictionary* respondData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];

        NSLog(@"%@", respondData);
    }else{

        NSLog(@"%@", error);
    }

}];

[dataTask resume];
</code>```

I have to try with postman and everything work fine. This is pictures.

Thank in advance.

答:
If you want to post raw, and param is a format of NSString, you only need to do this:

```<code>NSData *param_data = [encry_str dataUsingEncoding:NSUTF8StringEncoding];
murequest.HTTPBody = param_data;
</code>```

If we can’t get anything from that response, notice that the response serializer is correct. Any additional settings, please deal it with server.

Body:
I have stuck here. Below is my code for Post request with raw body using NSURLSession. I got response = NULL and no error.

NSString* stringRequest = @"https://chocudan.com/api/shops/by_ids";
NSURL* urlRequest = [NSURL URLWithString:stringRequest];

NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:urlRequest];
request.HTTPMethod = @"POST";

NSString* bodyRequest = @"563c268b84ba489c4729f149";

//I have to tried a base64 convert here but still not work.
//request.HTTPBody = [NSData base64DataFromString:bodyRequest];

request.HTTPBody = [bodyRequest dataUsingEncoding:NSUTF8StringEncoding];

NSURLSessionConfiguration* configureSession = [NSURLSessionConfiguration defaultSessionConfiguration];

configureSession.HTTPAdditionalHeaders = @{@"Content-Type" : @"application/json charset=utf-8",
                                           @"Content-Lenght" : @"180"};

NSURLSession* session = [NSURLSession sessionWithConfiguration:configureSession];

NSURLSessionDataTask* dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

    NSHTTPURLResponse* respHttp = (NSHTTPURLResponse*) response;

    if (!error && respHttp.statusCode == 200) {

        NSDictionary* respondData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];

        NSLog(@"%@", respondData);
    }else{

        NSLog(@"%@", error);
    }

}];

[dataTask resume];

I have to try with postman and everything work fine. This is pictures.

Thank in advance.

Body:
If you want to post raw, and param is a format of NSString, you only need to do this:

NSData *param_data = [encry_str dataUsingEncoding:NSUTF8StringEncoding];
murequest.HTTPBody = param_data;

If we can’t get anything from that response, notice that the response serializer is correct. Any additional settings, please deal it with server.


问:
connect to mysql using php vpn
I have a php script that accesses a mysql database. It lives on a server that has been migrated to aws (amazon web services). This server hosts a website that used to live on a physical server part of a private network.

The databases are still on that private network. I need to connect to a mysql database that is on a server with no public ip address. There is a vpn set up for this network.
I would like to ssh or vpn to the network from the aws server.
This is just to query something once a day.

I tried exec('ssh -f -L 3307:PrivateMYSQLServer:3306 USER@VPNADDRESS') but could not get it to work.

Is there a one liner that I can insert into the php script?

thanks

答:
You’ll have to set up the server in which your script runs to connect back to your network via your VPN client. </p>

<p>Alternatively, you can set up a site to site VPN between your data center and AWS. </p>

Title: connect to mysql using php vpn

Body:
You’ll have to set up the server in which your script runs to connect back to your network via your VPN client.

Alternatively, you can set up a site to site VPN between your data center and AWS.


问:
node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON]
[add]
So my next problem is that when i try adding a new dependence (npm install --save socket.io). The JSON file is also valid. I get this error:
Failed to parse json

```<code>npm ERR! Unexpected string
npm ERR! File: /Users/John/package.json
npm ERR! Failed to parse package.json data.
npm ERR! package.json must be actual JSON, not just JavaScript.
npm ERR!
npm ERR! This is not a bug in npm.
npm ERR! Tell the package author to fix their package.json file. JSON.parse
</code>```

So I've been trying to figure out why this error has been returning. All of the files (HTML,JSON,JS) are inside the same folder on my desktop. I'm using node.js and socket.io

This is my JS file:

```<code>var app = require('express')();
var http = require('http').Server(app);

app.get('/', function(req, res){
  res.sendFile('index.html');
});

http.listen(3000,function(){
    console.log('listening on : 3000');
});
</code>```

This is what is getting returned:

```<code>MacBook-Pro:~ John$ node /Users/John/Desktop/Chatapp/index.js
listening on : 3000
TypeError: path must be absolute or specify root to res.sendFile
    at ServerResponse.sendFile (/Users/John/node_modules/express/lib/response.js:389:11)
    at /Users/John/Desktop/Chatapp/index.js:5:7
    at Layer.handle [as handle_request] (/Users/John/node_modules/express/lib/router/layer.js:76:5)
    at next (/Users/John/node_modules/express/lib/router/route.js:100:13)
    at Route.dispatch (/Users/John/node_modules/express/lib/router/route.js:81:3)
    at Layer.handle [as handle_request] (/Users/John/node_modules/express/lib/router/layer.js:76:5)
    at /Users/John/node_modules/express/lib/router/index.js:234:24
    at Function.proto.process_params (/Users/John/node_modules/express/lib/router/index.js:312:12)
    at /Users/John/node_modules/express/lib/router/index.js:228:12
    at Function.match_layer (/Users/John/node_modules/express/lib/router/index.js:295:3)
TypeError: path must be absolute or specify root to res.sendFile
    at ServerResponse.sendFile (/Users/John/node_modules/express/lib/response.js:389:11)
    at /Users/John/Desktop/Chatapp/index.js:5:7
    at Layer.handle [as handle_request] (/Users/John/node_modules/express/lib/router/layer.js:76:5)
    at next (/Users/John/node_modules/express/lib/router/route.js:100:13)
    at Route.dispatch (/Users/John/node_modules/express/lib/router/route.js:81:3)
    at Layer.handle [as handle_request] (/Users/John/node_modules/express/lib/router/layer.js:76:5)
    at /Users/John/node_modules/express/lib/router/index.js:234:24
    at Function.proto.process_params (/Users/John/node_modules/express/lib/router/index.js:312:12)
    at /Users/John/node_modules/express/lib/router/index.js:228:12
    at Function.match_layer (/Users/John/node_modules/express/lib/router/index.js:295:3)
</code>```

答:
in .mjs files we for now don't have __dirname

hence

```<code>res.sendFile('index.html', { root: '.' })
</code>```

ContentLicense: CC BY-SA 4.0

Body:
[add]
So my next problem is that when i try adding a new dependence (npm install --save socket.io). The JSON file is also valid. I get this error:
Failed to parse json

npm ERR! Unexpected string
npm ERR! File: /Users/John/package.json
npm ERR! Failed to parse package.json data.
npm ERR! package.json must be actual JSON, not just JavaScript.
npm ERR!
npm ERR! This is not a bug in npm.
npm ERR! Tell the package author to fix their package.json file. JSON.parse

So I've been trying to figure out why this error has been returning. All of the files (HTML,JSON,JS) are inside the same folder on my desktop. I'm using node.js and socket.io

This is my JS file:

var app = require('express')();
var http = require('http').Server(app);

app.get('/', function(req, res){
  res.sendFile('index.html');
});

http.listen(3000,function(){
    console.log('listening on : 3000');
});

This is what is getting returned:

MacBook-Pro:~ John$ node /Users/John/Desktop/Chatapp/index.js
listening on : 3000
TypeError: path must be absolute or specify root to res.sendFile
    at ServerResponse.sendFile (/Users/John/node_modules/express/lib/response.js:389:11)
    at /Users/John/Desktop/Chatapp/index.js:5:7
    at Layer.handle [as handle_request] (/Users/John/node_modules/express/lib/router/layer.js:76:5)
    at next (/Users/John/node_modules/express/lib/router/route.js:100:13)
    at Route.dispatch (/Users/John/node_modules/express/lib/router/route.js:81:3)
    at Layer.handle [as handle_request] (/Users/John/node_modules/express/lib/router/layer.js:76:5)
    at /Users/John/node_modules/express/lib/router/index.js:234:24
    at Function.proto.process_params (/Users/John/node_modules/express/lib/router/index.js:312:12)
    at /Users/John/node_modules/express/lib/router/index.js:228:12
    at Function.match_layer (/Users/John/node_modules/express/lib/router/index.js:295:3)
TypeError: path must be absolute or specify root to res.sendFile
    at ServerResponse.sendFile (/Users/John/node_modules/express/lib/response.js:389:11)
    at /Users/John/Desktop/Chatapp/index.js:5:7
    at Layer.handle [as handle_request] (/Users/John/node_modules/express/lib/router/layer.js:76:5)
    at next (/Users/John/node_modules/express/lib/router/route.js:100:13)
    at Route.dispatch (/Users/John/node_modules/express/lib/router/route.js:81:3)
    at Layer.handle [as handle_request] (/Users/John/node_modules/express/lib/router/layer.js:76:5)
    at /Users/John/node_modules/express/lib/router/index.js:234:24
    at Function.proto.process_params (/Users/John/node_modules/express/lib/router/index.js:312:12)
    at /Users/John/node_modules/express/lib/router/index.js:228:12
    at Function.match_layer (/Users/John/node_modules/express/lib/router/index.js:295:3)

Body:
in .mjs files we for now don't have __dirname

hence

res.sendFile('index.html', { root: '.' })


问:
Autodesk Forge: BIM spaces and rooms in the Forge viewer
Is there any way to find a list of IFC spaces and/or RVT rooms in the Forge viewer? I'm making a building simulation app and I'm looking for a way to allow users to select individual spaces/rooms to run their simulation.</p>

答: You can see this blog writen by Xiaodong Liang Make shader face for room object of the model</p>


问:
How to check whether two arrays have the same parameters in every position, i
I'm having trouble with the following problem:

boolean sameStepShape(int[] a, int[] b) that checks whether the two parameter arrays a and b are the same overall shape in that every position i has the same classification (upstep, downstep or plateau) in both arrays. (Your method may assume that a and b have same length.)

```<code>public boolean sameStepShape(int[] a, int[] b) {
boolean sameStep = true;

for (int i = 0; i < a.length - 1; i++) {
    if(a[i] < a[i+1] && b[i] < b[i+1]){
        return sameStep;
    }
    else if(a[i] > a[i+1] && b[i] > b[i+1]) {
        return sameStep;
    }
    else if(a[i] == a[i+1] && b[i] == b[i+1]) {
        return sameStep;
    }
}
return sameStep = false;
}
</code>```

However, this code isnt passing the test class and im not too sure why. I'm a little stumped. If anyone can offer any input, it'd be greatly appreciated.

EDIT: Apologies, I forgot to include this piece of informtion:

"Based on how the value in some array position i compares to the value in its successor position i + 1, each position i in the array a is classified as an upstep if a[i]  a[i + 1], and a plateau if a[i] == a[i + 1]. The last position of the array has no such classification, since there is no successor element that we could compare its value with."

答:
I figured this out a while ago but I thought I'd post the solution here just for everyone to see.</p>

```<code>public boolean sameStepShape(int[] a, int[] b) {
boolean sameStep = false;

for (int i = 0; i < a.length - 1; i++) {
    if((a[i] < a[i+1]) && (b[i] >= b[i+1])){
        return sameStep;
    }
    else if((a[i] > a[i+1]) && (b[i] <= b[i+1])) {
        return sameStep;
    }
    else if((a[i] == a[i+1] && b[i] != b[i+1])) {
        return sameStep;
    }
}
return sameStep = true;
}
</code>```

Body:
I'm having trouble with the following problem:

boolean sameStepShape(int[] a, int[] b) that checks whether the two parameter arrays a and b are the same overall shape in that every position i has the same classification (upstep, downstep or plateau) in both arrays. (Your method may assume that a and b have same length.)

public boolean sameStepShape(int[] a, int[] b) {
boolean sameStep = true;

for (int i = 0; i < a.length - 1; i++) {
    if(a[i] < a[i+1] && b[i]  a[i+1] && b[i] > b[i+1]) {
        return sameStep;
    }
    else if(a[i] == a[i+1] && b[i] == b[i+1]) {
        return sameStep;
    }
}
return sameStep = false;
}

However, this code isnt passing the test class and im not too sure why. I'm a little stumped. If anyone can offer any input, it'd be greatly appreciated.

EDIT: Apologies, I forgot to include this piece of informtion:

"Based on how the value in some array position i compares to the value in its successor position i + 1, each position i in the array a is classified as an upstep if a[i]  a[i + 1], and a plateau if a[i] == a[i + 1]. The last position of the array has no such classification, since there is no successor element that we could compare its value with."

Body:
I figured this out a while ago but I thought I'd post the solution here just for everyone to see.

public boolean sameStepShape(int[] a, int[] b) {
boolean sameStep = false;

for (int i = 0; i < a.length - 1; i++) {
    if((a[i] < a[i+1]) && (b[i] >= b[i+1])){
        return sameStep;
    }
    else if((a[i] > a[i+1]) && (b[i] <= b[i+1])) {
        return sameStep;
    }
    else if((a[i] == a[i+1] && b[i] != b[i+1])) {
        return sameStep;
    }
}
return sameStep = true;
}


问:
How to remove a character in the dataframe using the stringi package?
I currently have a dataframe of stock KPIs and I would like to remove the "$" character from the data. However, I can only use one line of code in addition to the mandatory usage of the stringi package. Looking at the documentation, the "stri_replace_all_fixed" was the function that stood out to me, but upon running that function, my data frame lost its formatting. I tried combining both the lapply and the stri_replace_all_fixed functions to no avail. Pointers on how to address this problem would be much appreciated.

答:
With library(stringi)

```<code>yourdataframe[] <- lapply(yourdataframe, stri_replace_all_regex,"\\$", "")
</code>```

Body:
With library(stringi)

yourdataframe[] <- lapply(yourdataframe, stri_replace_all_regex,"\\$", "")


问:
Pandas send multiple DataFrames to_csv
I have three symbols with price data and successfully imported/modified that price data as shown below:

```<code>def read_files():
    assets = ['ES','ZN','VX']
    path = r"C:\Users\cost9\OneDrive\Documents\PYTHON\Exported_Data\%s\*.csv"

    files = []
    for a in assets:
        files.extend(glob.iglob(path % a))

    df_list = [pd.read_csv(f) for f in files]

    for b in df_list:
        b['Returns'] = b['Close'].pct_change()
</code>```

The sample data now looks like this after creating the 'Returns' column above:

```<code>Ticker  Date/Time   Close   Returns
ES U7   3/14/2017 5:29  2365.5
ES U7   3/14/2017 6:29  2362.25 -0.001373917
ES U7   3/14/2017 8:29  2355    -0.003069108
ES U7   3/14/2017 9:29  2359.25 0.001804671
ES U7   3/14/2017 10:29 2356    -0.001377556
ES U7   3/14/2017 11:29 2358    0.000848896
ES U7   3/14/2017 12:29 2358.5  0.000212044
ES U7   3/14/2017 13:29 2360.25 0.000741997
ES U7   3/14/2017 14:29 2360.5  0.000105921
ES U7   3/14/2017 21:29 2361.5  0.000423639
ES U7   3/14/2017 22:29 2363.5  0.000846919
ES U7   3/14/2017 23:29 2363.75 0.000105775
ES U7   3/15/2017 0:29  2364.5  0.000317292
ES U7   3/15/2017 1:29  2363.5  -0.000422922
</code>```

Each of the three symbols' CSV files would look like this. Now I want to move each of these three DataFrames into separate folders:

```<code>end_path_to_csv = "C:\\Users\\cost9\\OneDrive\\Documents\\PYTHON\\Daily Tasks\\Individual Trading\\%s\CSV\\15M\\Trend_Identifier\\blah.csv"

for c in df_list:
    c.to_csv(path_or_buf = end_path_to_csv % assets)
</code>```

I get this error:

```<code>IOError: [Errno 2] No such file or directory: "C:\\Users\\cost9\\OneDrive\\Documents\\PYTHON\\Daily Tasks\\Individual Trading\\['ES', 'ZN', 'VX']\\CSV\\15M\\Trend_Identifier\\blah.csv"
</code>```

Unfortunately I can't convert the 'assets' and 'df_list' (Dataframe) values into a dictionary - if I do that then the DataFrames won't be called and there's no csv data available.

I have three folders, each the exact same except for the symbol in the file directory, for example:

```<code>"C:\\Users\\cost9\\OneDrive\\Documents\\PYTHON\\Daily Tasks\\Individual Trading\\ES\\CSV\\15M\\Trend_Identifier\\blah.csv"
</code>```

This would be for the 'ES' symbol, the 'VX' would replace 'ES' if I was referring to that DataFrame and so on.

How can I save each dataframe into the corresponding folder?

答:
Just zip assets and df_list together and iterate over them.

```<code>assets = ['ES','ZN','VX']
dst_path = ...

for p, c in zip(assets, df_list):
    c.to_csv(dst_path % p)
</code>```

Title: Pandas send multiple DataFrames to_csv

Body:
I have three symbols with price data and successfully imported/modified that price data as shown below:

def read_files():
    assets = ['ES','ZN','VX']
    path = r"C:\Users\cost9\OneDrive\Documents\PYTHON\Exported_Data\%s\*.csv"

    files = []
    for a in assets:
        files.extend(glob.iglob(path % a))

    df_list = [pd.read_csv(f) for f in files]

    for b in df_list:
        b['Returns'] = b['Close'].pct_change()

The sample data now looks like this after creating the 'Returns' column above:

Ticker  Date/Time   Close   Returns
ES U7   3/14/2017 5:29  2365.5
ES U7   3/14/2017 6:29  2362.25 -0.001373917
ES U7   3/14/2017 8:29  2355    -0.003069108
ES U7   3/14/2017 9:29  2359.25 0.001804671
ES U7   3/14/2017 10:29 2356    -0.001377556
ES U7   3/14/2017 11:29 2358    0.000848896
ES U7   3/14/2017 12:29 2358.5  0.000212044
ES U7   3/14/2017 13:29 2360.25 0.000741997
ES U7   3/14/2017 14:29 2360.5  0.000105921
ES U7   3/14/2017 21:29 2361.5  0.000423639
ES U7   3/14/2017 22:29 2363.5  0.000846919
ES U7   3/14/2017 23:29 2363.75 0.000105775
ES U7   3/15/2017 0:29  2364.5  0.000317292
ES U7   3/15/2017 1:29  2363.5  -0.000422922

Each of the three symbols' CSV files would look like this. Now I want to move each of these three DataFrames into separate folders:

end_path_to_csv = "C:\\Users\\cost9\\OneDrive\\Documents\\PYTHON\\Daily Tasks\\Individual Trading\\%s\CSV\\15M\\Trend_Identifier\\blah.csv"

for c in df_list:
    c.to_csv(path_or_buf = end_path_to_csv % assets)

I get this error:

IOError: [Errno 2] No such file or directory: "C:\\Users\\cost9\\OneDrive\\Documents\\PYTHON\\Daily Tasks\\Individual Trading\\['ES', 'ZN', 'VX']\\CSV\\15M\\Trend_Identifier\\blah.csv"

Unfortunately I can't convert the 'assets' and 'df_list' (Dataframe) values into a dictionary - if I do that then the DataFrames won't be called and there's no csv data available.

I have three folders, each the exact same except for the symbol in the file directory, for example:

"C:\\Users\\cost9\\OneDrive\\Documents\\PYTHON\\Daily Tasks\\Individual Trading\\ES\\CSV\\15M\\Trend_Identifier\\blah.csv"

This would be for the 'ES' symbol, the 'VX' would replace 'ES' if I was referring to that DataFrame and so on.

How can I save each dataframe into the corresponding folder?

Body:
Just zip assets and df_list together and iterate over them.

assets = ['ES','ZN','VX']
dst_path = ...

for p, c in zip(assets, df_list):
    c.to_csv(dst_path % p)


问:
Incorrectly Inferred Type in Generic Closure with Protocol Extension Constrained by Self
While trying to implement a function in Swift I ran into an issue where it seems that type inference broke on certain function parameters. Taking notes from other languages, I wanted to implement a function in Swift which takes two parameters: an object and a block which returns another object of the same type as the previous object. I started implementing it like so:

```<code>func prepare<T>(_ object: T?, with block: ((T?) -> T?)) -> T? {
    return block(object)
}
</code>```

After attempting to use that inside of a UITableViewController class, I experienced an issue with the naming, as it seemed to be struggling with the segue function prepare(for:sender:)

I decided to just change the name to resolve this one (I'll save the above for another question):

```<code>func bootstrap<T>(_ object: T?, with block: ((T?) -> T?)) -> T? {
    return block(object)
}
</code>```

This name will do for now. So I have a bootstrap(_:with:) function which takes an object and a closure, returning an object of the same type as the object argument. I can call this easily with certain objects, for example an Int:

```<code>bootstrap(1, with: { $0 + 1 })  // returns 2
</code>```

This of course isn't what the function is there for, however. So I used it in its actual intended application, where I have a small UIView-derived class with a single member:

```<code>class ContactDetailHeaderView: UIView, Nibbable {
    var user: User?
}
</code>```

This is fetched from a nib using the following protocol extension function on the Nibbable protocol:

```<code>extension Nibbable where Self: UIResponder {
    static func getRoot(withOwner owner: Any, options: [AnyHashable:Any]? = nil) -> Self? {
        return self.nib.instantiate(withOwner: owner, options: options).first as? Self
    }
}
</code>```

With this, we can retrieve an object from nib (our UINibobject for this class) and cast it as Self which in this case is ContactDetailHeaderView. Then, we can use our previously declared function to setup the object. We do this inside of a UITableViewController-derived class ContactDetailTableViewController which I will condense for the purpose of this question:

```<code>class ContactDetailTableViewController: UITableViewController {
    var user: User?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.backgroundView = bootstrap(ContactDetailHeaderView.getRoot(withOwner: self), with: { $0?.user = self.user })
    }
}
</code>```

However, we get an error invoking this function:

```<code>Value of type 'UIView' has no member 'user'
</code>```

This is unexpected. Our getRoot(withOwner:options:) function should return Self which is ContactDetailHeaderView, right?

Let's expand on the type inference by replacing the shorthand arguments with named parameters and explicitly defined types:

```<code>bootstrap(ContactDetailHeaderView.getRoot(withOwner: self),
    with: { (header: ContactDetailHeaderView?) -> ContactDetailHeaderView? in
        header?.user = self.user
    }
)
</code>```

Surely there is no way that our object can be interpreted as UIView now? Well, we still get the same error:

```<code>Value of type 'UIView' has no member 'user'
</code>```

Why does this happen? Even when I check the autocomplete in Xcode, the header argument here shows the user member as a valid accessible property. Using the getRoot(withOwner:options:) function elsewhere produces the expected result:

```<code>ContactDetailHederView.getRoot(withOwner: self)?.user = self.user
</code>```

Then why does it not work inside the bootstrap(_:with:) closure? Is this a bug? Is there something else I'm missing?

Any help would be greatly appreciated.

I'll attach a gist with enough code to reproduce the problem in a playground. For simplicity's sake, I'll replace some of the unnecessary bits with something more manageable (e.g. change user type from User which is an internal object to String which is available in the standard library)

Please keep in mind that this question is not about what the function does or why it does it. There are plenty of ways to implement the same thing, many of which are likely far better. I would like to solve this compiler error regardless of whether or not I even use this function in its current form.

答:
Please keep in mind that this question is not about what the function does or why it does it. There are plenty of ways to implement the same thing, many of which are likely far better. I would like to solve this compiler error regardless of whether or not I even use this function in its current form.

Good, because this has way too many optionals. But it's easy to fix (it's just really hard to understand because it's too complicated).

bootstrap is supposed to return a T?. You pass it this:

```<code>{ (header: ContactDetailHeaderView?) -> ContactDetailHeaderView? in
    header?.user = self.user
}
</code>```

That returns Void. That causes the type engine to run down all kinds of rabbit holes (especially since any T can become T?). The fix is to return T:

```<code>{ (header: ContactDetailHeaderView?) -> ContactDetailHeaderView? in
    header?.user = self.user
    return header
}
</code>```

In your gist, this would be:

```<code>self.tableView.backgroundView = bootstrap(ContactDetailHeaderView.getRoot(withOwner: self),
                                with: { $0?.user = self.user; return $0 })
</code>```

Body:
While trying to implement a function in Swift I ran into an issue where it seems that type inference broke on certain function parameters. Taking notes from other languages, I wanted to implement a function in Swift which takes two parameters: an object and a block which returns another object of the same type as the previous object. I started implementing it like so:

func prepare<T>(_ object: T?, with block: ((T?) -> T?)) -> T? {
    return block(object)
}

After attempting to use that inside of a UITableViewController class, I experienced an issue with the naming, as it seemed to be struggling with the segue function prepare(for:sender:)

I decided to just change the name to resolve this one (I'll save the above for another question):

func bootstrap<T>(_ object: T?, with block: ((T?) -> T?)) -> T? {
    return block(object)
}

This name will do for now. So I have a bootstrap(_:with:) function which takes an object and a closure, returning an object of the same type as the object argument. I can call this easily with certain objects, for example an Int:

bootstrap(1, with: { $0 + 1 })  // returns 2

This of course isn't what the function is there for, however. So I used it in its actual intended application, where I have a small UIView-derived class with a single member:

class ContactDetailHeaderView: UIView, Nibbable {
    var user: User?
}

This is fetched from a nib using the following protocol extension function on the Nibbable protocol:

extension Nibbable where Self: UIResponder {
    static func getRoot(withOwner owner: Any, options: [AnyHashable:Any]? = nil) -> Self? {
        return self.nib.instantiate(withOwner: owner, options: options).first as? Self
    }
}

With this, we can retrieve an object from nib (our UINibobject for this class) and cast it as Self which in this case is ContactDetailHeaderView. Then, we can use our previously declared function to setup the object. We do this inside of a UITableViewController-derived class ContactDetailTableViewController which I will condense for the purpose of this question:

class ContactDetailTableViewController: UITableViewController {
    var user: User?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.backgroundView = bootstrap(ContactDetailHeaderView.getRoot(withOwner: self), with: { $0?.user = self.user })
    }
}

However, we get an error invoking this function:

Value of type 'UIView' has no member 'user'

This is unexpected. Our getRoot(withOwner:options:) function should return Self which is ContactDetailHeaderView, right?

Let's expand on the type inference by replacing the shorthand arguments with named parameters and explicitly defined types:

bootstrap(ContactDetailHeaderView.getRoot(withOwner: self),
    with: { (header: ContactDetailHeaderView?) -> ContactDetailHeaderView? in
        header?.user = self.user
    }
)

Surely there is no way that our object can be interpreted as UIView now? Well, we still get the same error:

Value of type 'UIView' has no member 'user'

Why does this happen? Even when I check the autocomplete in Xcode, the header argument here shows the user member as a valid accessible property. Using the getRoot(withOwner:options:) function elsewhere produces the expected result:

ContactDetailHederView.getRoot(withOwner: self)?.user = self.user

Then why does it not work inside the bootstrap(_:with:) closure? Is this a bug? Is there something else I'm missing?

Any help would be greatly appreciated.

I'll attach a gist with enough code to reproduce the problem in a playground. For simplicity's sake, I'll replace some of the unnecessary bits with something more manageable (e.g. change user type from User which is an internal object to String which is available in the standard library)

Please keep in mind that this question is not about what the function does or why it does it. There are plenty of ways to implement the same thing, many of which are likely far better. I would like to solve this compiler error regardless of whether or not I even use this function in its current form.

Body:
Please keep in mind that this question is not about what the function does or why it does it. There are plenty of ways to implement the same thing, many of which are likely far better. I would like to solve this compiler error regardless of whether or not I even use this function in its current form.

Good, because this has way too many optionals. But it's easy to fix (it's just really hard to understand because it's too complicated).

bootstrap is supposed to return a T?. You pass it this:

{ (header: ContactDetailHeaderView?) -> ContactDetailHeaderView? in
    header?.user = self.user
}

That returns Void. That causes the type engine to run down all kinds of rabbit holes (especially since any T can become T?). The fix is to return T:

{ (header: ContactDetailHeaderView?) -> ContactDetailHeaderView? in
    header?.user = self.user
    return header
}

In your gist, this would be:

self.tableView.backgroundView = bootstrap(ContactDetailHeaderView.getRoot(withOwner: self),
                                with: { $0?.user = self.user; return $0 })


问:
Using PHP & Curl to login to my websites form
Im trying to login to my useraccount on a site i use to download files from so i can automatically grab the file without me having to visit the site.

This is the form:

```<code> <form method='post' action='/news.php'>
 <div>
             Username: <input class='tbox' type='text'     name='username' size='15' value='' maxlength='20' />
             Password: <input class='tbox' type='password' name='userpass' size='15' value='' maxlength='20' />
             <input type='hidden' name='autologin' value='1' />
             <input class='button' type='submit' name='userlogin' value='Login' />
 </div>
 </form>
</code>```

Here is the PHP ive got so far.

```<code><?php
$username="my_user";
$password="my_passs";
$url="the_url";
$cookie="cookie.txt";

$postdata = "username=".$username."&userpass=".$password;

$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
curl_setopt ($ch, CURLOPT_TIMEOUT, 60);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt ($ch, CURLOPT_REFERER, $url);

curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt ($ch, CURLOPT_POST, 1);
$result = curl_exec ($ch);

echo $result;
curl_close($ch);
?>
</code>```

Am i doing something wrong? It just displays the website at the moment but doesn't log me in. Ive never used Curl before.

Thanks

答:
Use a headless browser - a really scalable solution. (Tell me if it works with google account :)

What I did (useful for myself as well :)

Install composer https://getcomposer.org (if not installed)
Ensure it's installed by typing in command line

```<code>     composer -V
</code>```

Create a folder, say, TryGoutte somewhere in your web server directory

Create a file composer.json (just to test composer):

```<code> {
   "require": {
       "monolog/monolog": "1.0.*"
    }
 }
</code>```

Type "composer install". It should install monolog.

Type "composer require fabpot/goutte". It should install all packages for
"goutte" https://github.com/FriendsOfPHP/Goutte
(pronounced gu:t, like boot)

Then, create file, say try-goutte.php in TryGoutte.

```<code>  <?php
use Goutte\Client;
use GuzzleHttp\Client as GuzzleClient;

require 'vendor/autoload.php';

$client = new \Goutte\Client();

// Create and use a guzzle client instance that will time out after 90 seconds
$guzzleClient = new \GuzzleHttp\Client(array(
'timeout' => 90,
// To overcome Curl SSL 60 error
// https://github.com/FriendsOfPHP/Goutte/issues/214
'verify' => false,
));

$client->setClient($guzzleClient);

$crawler = $client->request('GET', 'https://github.com/');
$crawler = $client->click($crawler->selectLink('Sign in')->link());
$form = $crawler->selectButton('Sign in')->form();
$crawler = $client->submit($form, array('login' => 'trygoutte', 'password' => 'trygoutte1'));

print_r($crawler->text());

?>
</code>```

Enjoy and code further!

UPDATE: implemented here http://lycenok.com/site-login/programmatic-site-login.php to check if the solution works for you

Body:
Im trying to login to my useraccount on a site i use to download files from so i can automatically grab the file without me having to visit the site.

This is the form:

 <form method='post' action='/news.php'>

             Username: <input class='tbox' type='text'     name='username' size='15' value='' maxlength='20' />
             Password: <input class='tbox' type='password' name='userpass' size='15' value='' maxlength='20' />
             <input type='hidden' name='autologin' value='1' />
             <input class='button' type='submit' name='userlogin' value='Login' />

 </form>

Here is the PHP ive got so far.

<?php
$username="my_user";
$password="my_passs";
$url="the_url";
$cookie="cookie.txt";

$postdata = "username=".$username."&userpass=".$password;

$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
curl_setopt ($ch, CURLOPT_TIMEOUT, 60);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt ($ch, CURLOPT_REFERER, $url);

curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt ($ch, CURLOPT_POST, 1);
$result = curl_exec ($ch);

echo $result;
curl_close($ch);
?>

Am i doing something wrong? It just displays the website at the moment but doesn't log me in. Ive never used Curl before.

Thanks

Body:
Use a headless browser - a really scalable solution. (Tell me if it works with google account :)

What I did (useful for myself as well :)

Install composer https://getcomposer.org (if not installed)
Ensure it's installed by typing in command line

     composer -V

Create a folder, say, TryGoutte somewhere in your web server directory

Create a file composer.json (just to test composer):

 {
   "require": {
       "monolog/monolog": "1.0.*"
    }
 }

Type "composer install". It should install monolog.

Type "composer require fabpot/goutte". It should install all packages for
"goutte" https://github.com/FriendsOfPHP/Goutte
(pronounced gu:t, like boot)

Then, create file, say try-goutte.php in TryGoutte.

  <?php
use Goutte\Client;
use GuzzleHttp\Client as GuzzleClient;

require 'vendor/autoload.php';

$client = new \Goutte\Client();

// Create and use a guzzle client instance that will time out after 90 seconds
$guzzleClient = new \GuzzleHttp\Client(array(
'timeout' => 90,
// To overcome Curl SSL 60 error
// https://github.com/FriendsOfPHP/Goutte/issues/214
'verify' => false,
));

$client->setClient($guzzleClient);

$crawler = $client->request('GET', 'https://github.com/');
$crawler = $client->click($crawler->selectLink('Sign in')->link());
$form = $crawler->selectButton('Sign in')->form();
$crawler = $client->submit($form, array('login' => 'trygoutte', 'password' => 'trygoutte1'));

print_r($crawler->text());

?>

Enjoy and code further!

UPDATE: implemented here http://lycenok.com/site-login/programmatic-site-login.php to check if the solution works for you


问:
WISE Uninstaller doesn't remove itself
I know, I know...stop using WISE. That's not really an option for me right now. We have too much on our plate to write a completely new installer and change our entire build process, which is what would have to be done.

ANYWAYS, the problem is that our uninstall EXE doesn't delete itself when uninstalling. It is located in the Program Files folder, where our app is installed. After the uninstaller is done, we want all files removed and the app folder deleted. Instead, the uninstaller remains along with the app folder, since it can't seem to remove itself while it is running.

This seems like a rudimentary task, since all the other programs installed on my computer have their uninstallers located in their Program Files folder as well and they are removed after uninstalling, yet I can't seem to find anyone else with the same problem via Google. It makes sense to me that the file can't be deleted since it is currently loaded into memory, but *whining tone* everyone else does it...why can't I?

EDIT: If it helps, I am running Wise Installation Studio 7.0 and modifying the uninstall script in the WiseScript Package Editor. The part that removes the Program Files folder looks like Delete File(s) %MAINDIR%\*.* where %MAINDIR% is the app folder in Program Files. There are two available options for this command (both of which are on)--Include Sub-Directories and Remove Directory Containing Files.

答:
If you can't find some other way to do it, here's a dirty trick: make the last step in your installer to fire off a cmd.exe that waits for your Wise process to end, then deletes it.

An example of how to do this in a batch script with tasklist:

```<code>rem Expand variables delayed with !! syntax for for loop
setlocal EnableExtensions EnableDelayedExpansion

rem Create a loop with a label and goto
:loopstart
for /F "delims= " %%a in ('tasklist /FI "imagename eq wiseuninstaller.exe"') do (
   if not "%%a"=="INFO: No tasks are running which match the specified criteria." (
      set stillrunning=no
   ) else (
      set stillrunning=yes

      rem Add a 5 second delay with ping and throw out the output.
      ping -n 5 > NUL 2>&1
   )
)

if "!stillrunning!"=="yes" goto :loopstart

del wiseuninstaller.exe
</code>```

I haven't tested this code or checked it much for syntax errors, but it's close.  for /? and tasklist /? from the command line can help you figure out how to tweak this to your needs.

Title: WISE Uninstaller doesn't remove itself

Body:
If you can't find some other way to do it, here's a dirty trick: make the last step in your installer to fire off a cmd.exe that waits for your Wise process to end, then deletes it.

An example of how to do this in a batch script with tasklist:

rem Expand variables delayed with !! syntax for for loop
setlocal EnableExtensions EnableDelayedExpansion

rem Create a loop with a label and goto
:loopstart
for /F "delims= " %%a in ('tasklist /FI "imagename eq wiseuninstaller.exe"') do (
   if not "%%a"=="INFO: No tasks are running which match the specified criteria." (
      set stillrunning=no
   ) else (
      set stillrunning=yes

      rem Add a 5 second delay with ping and throw out the output.
      ping -n 5 > NUL 2>&1
   )
)

if "!stillrunning!"=="yes" goto :loopstart

del wiseuninstaller.exe

I haven't tested this code or checked it much for syntax errors, but it's close.  for /? and tasklist /? from the command line can help you figure out how to tweak this to your needs.


问:
Aggregate sequential time recordings in R
I am trying to calculate the sequential recordings in a time series, and aggregate the data for these sequences.

Example Data

Here is an example of the data taken at a maximum frequency of 1 second:

```<code>timestamp   Value
06:07:23    0.439
06:07:24    0.556
06:07:25    0.430
06:07:26    0.418
06:07:27    0.407
06:07:47    0.439
06:07:48    0.420
06:07:49    0.405
09:55:21    0.507
09:55:22    0.439
10:03:24    0.439
10:03:25    0.439
10:03:36    1.708
10:03:37    0.608
10:03:38    0.439
10:03:46    0.484
10:03:47    0.380
10:03:48    0.607
10:03:49    0.439
10:03:50    0.439
10:03:51    0.439
10:03:52    0.430
10:03:53    0.439
10:03:54    4.924
10:03:55    1.012
10:03:56    0.887
10:03:57    0.439
10:03:58    0.439
10:04:18    0.447
10:04:19    0.447
</code>```

As can be seen, there are periods whereby a value is taken every second. I am trying to find a way to aggregate if there was no gap between the observations to end up with something as follows:

```<code>timestamp   max     duration
06:07:23    0.556   5
06:07:47    0.439   3
09:55:21    0.507   2
10:03:24    0.439   2
10:03:36    1.708   3
10:03:46    1.012   13
10:04:18    0.447   2
</code>```

I am struggling to find a way of grouping the data by the sequential data. The closest answer I have been able to find is this one, however, the answers were provided over three and a half years ago and I was struggling to get the data.table method working.

Any ideas much appreciated!

Body:
I am trying to calculate the sequential recordings in a time series, and aggregate the data for these sequences.

Example Data

Here is an example of the data taken at a maximum frequency of 1 second:

timestamp   Value
06:07:23    0.439
06:07:24    0.556
06:07:25    0.430
06:07:26    0.418
06:07:27    0.407
06:07:47    0.439
06:07:48    0.420
06:07:49    0.405
09:55:21    0.507
09:55:22    0.439
10:03:24    0.439
10:03:25    0.439
10:03:36    1.708
10:03:37    0.608
10:03:38    0.439
10:03:46    0.484
10:03:47    0.380
10:03:48    0.607
10:03:49    0.439
10:03:50    0.439
10:03:51    0.439
10:03:52    0.430
10:03:53    0.439
10:03:54    4.924
10:03:55    1.012
10:03:56    0.887
10:03:57    0.439
10:03:58    0.439
10:04:18    0.447
10:04:19    0.447

As can be seen, there are periods whereby a value is taken every second. I am trying to find a way to aggregate if there was no gap between the observations to end up with something as follows:

timestamp   max     duration
06:07:23    0.556   5
06:07:47    0.439   3
09:55:21    0.507   2
10:03:24    0.439   2
10:03:36    1.708   3
10:03:46    1.012   13
10:04:18    0.447   2

I am struggling to find a way of grouping the data by the sequential data. The closest answer I have been able to find is this one, however, the answers were provided over three and a half years ago and I was struggling to get the data.table method working.

Any ideas much appreciated!

Body:
Here is an attempt in data.table:

dat[,
  .(timestamp = timestamp[1], max = max(Value), duration=.N),
  by = cumsum(c(FALSE, diff(as.POSIXct(dat$timestamp, format="%H:%M:%S", tz="UTC")) > 1))
]

#   cumsum timestamp   max duration
#1:      0  06:07:23 0.556        5
#2:      1  06:07:47 0.439        3
#3:      2  09:55:21 0.507        2
#4:      3  10:03:24 0.439        2
#5:      4  10:03:36 1.708        3
#6:      5  10:03:46 4.924       13
#7:      6  10:04:18 0.447        2


答: If you have a correctly configured site-to-site VPN (and routing tables, security groups, etc.), one end in your VPC and the other end in your private on premises network, then you don't need to create an SSH tunnel. Just connect to your database and run the query.</p>

Title: connect to mysql using php vpn

Body:
I have a php script that accesses a mysql database. It lives on a server that has been migrated to aws (amazon web services). This server hosts a website that used to live on a physical server part of a private network.

The databases are still on that private network. I need to connect to a mysql database that is on a server with no public ip address. There is a vpn set up for this network.
I would like to ssh or vpn to the network from the aws server.
This is just to query something once a day.

I tried exec('ssh -f -L 3307:PrivateMYSQLServer:3306 USER@VPNADDRESS') but could not get it to work.

Is there a one liner that I can insert into the php script?

thanks


问:
"docker build -f" command does not seem to progress and shows no error
Docker newbie here.

Installed Docker toolbox in Windows 7.

Have a '.df' to create a Tomcat image.This file has all the required commands.

In the 'Docker Quick start terminal' typed on the below command

```<code>docker build -f tomcat.df -t demo/tomcat:8 .
</code>```

There seems to be no progress or no error.

Please share any fix to resolve this issue.

答:
The first step of a docker build is to package up the build context and send it to the docker server (it's a client/server app even if you're running locally). All of the COPY and ADD commands are done with this context, not your workstation's filesystem, since the build could be run on another system. Once the context is done being zipped up and sent to the server you'll start to see some output.

So if you see a long delay without any output from the docker build command, look into reducing the size of this context. Don't include any unnecessary directories and files, and don't make some top level directory your context. It's possible that your context could be sent until you run out of disk space if your context includes the temporary folder docker uses to receive that context on the host.

You indicate the directory of your build context as the last argument to the build, often a single . to indicate the current directory. To pass a different directory for your context, you can cd to the other location, or provide a different path instead of the ..

Note that the Dockerfile location is relative to the build context and should be included in your context. You can also exclude files from the build context by including a .dockerignore file with a syntax similar to .gitignore in the root of your build context.

Body:
Docker newbie here.

Installed Docker toolbox in Windows 7.

Have a '.df' to create a Tomcat image.This file has all the required commands.

In the 'Docker Quick start terminal' typed on the below command

docker build -f tomcat.df -t demo/tomcat:8 .

There seems to be no progress or no error.

Please share any fix to resolve this issue.


问:
How to prevent scrollbar from repositioning web page?
I have a website with center-aligned DIV. Now, some pages need scrolling, some don't. When I move from one type to another, the appearance of a scrollbar moves the page a few pixels to the side. Is there any way to avoid this without explicitly showing the scrollbars on each page?</p>

答:
Extending off of Rapti's answer, this should work just as well, but it adds more margin to the right side of the body and hides it with negative html margin, instead of adding extra padding that could potentially affect the page's layout. This way, nothing is changed on the actual page (in most cases), and the code is still functional.

```<code>html {
    margin-right: calc(100% - 100vw);
}
body {
    margin-right: calc(100vw - 100%);
}
</code>```

Body:
Extending off of Rapti's answer, this should work just as well, but it adds more margin to the right side of the body and hides it with negative html margin, instead of adding extra padding that could potentially affect the page's layout. This way, nothing is changed on the actual page (in most cases), and the code is still functional.

html {
    margin-right: calc(100% - 100vw);
}
body {
    margin-right: calc(100vw - 100%);
}


答:
You are looping over df_list, yet the path is the same in every loop-iteration.Try this:</p>

```<code>end_path_to_csv = "C:\\Users\\cost9\\OneDrive\\Documents\\PYTHON\\Daily Tasks\\Individual Trading\\%s\CSV\\15M\\Trend_Identifier\\blah.csv"

for idx, c in enumerate(df_list):
    c.to_csv(path_or_buf = end_path_to_csv % assets[idx])
</code>```

Title: Pandas send multiple DataFrames to_csv

Body:
You are looping over df_list, yet the path is the same in every loop-iteration.Try this:

end_path_to_csv = "C:\\Users\\cost9\\OneDrive\\Documents\\PYTHON\\Daily Tasks\\Individual Trading\\%s\CSV\\15M\\Trend_Identifier\\blah.csv"

for idx, c in enumerate(df_list):
    c.to_csv(path_or_buf = end_path_to_csv % assets[idx])


答:
It took awhile to figure out what you want, but I think you're looking for:

```<code>awk '!a[$1 $3] {a[$1 $3] = $1","$3","}
    {a[$1 $3] = a[$1 $3] " " $2 " " $4}
    END {for(i in a) print a[i]}' FS=, input-file
</code>```

or

```<code>awk '{a[$1","$3] = a[$1","$3] " " $2 " " $4}
    END {for(i in a) print i","a[i]}' FS=, input-file
</code>```

There are many variations on the theme.

Title: manipulate input file and create a new file using awk

Body:
Input

1473697,5342715,256,0.3

1473697,7028427,256,0.1

1473697,5342716,256,0.3

1473697,5342715,257,0.3

1473697,7028427,257,0.1

1473610,7028427,256,0.1

1473610,5342715,256,0.3

1473610,7028422,256,0.1

Output

1473697,256,5342715 0.3 7028427 0.1 5342716 0.3

1473697,257,5342715 0.3 7028427 0.1

1473610,256,7028427 0.1 5342715 0.3 7028422 0.1

OFS and FS is = ,
is there a way to search unique lines base on column 1 and 3
then print the line with the details from column 2 and 4

Body:
It took awhile to figure out what you want, but I think you're looking for:

awk '!a[$1 $3] {a[$1 $3] = $1","$3","}
    {a[$1 $3] = a[$1 $3] " " $2 " " $4}
    END {for(i in a) print a[i]}' FS=, input-file

or

awk '{a[$1","$3] = a[$1","$3] " " $2 " " $4}
    END {for(i in a) print i","a[i]}' FS=, input-file

There are many variations on the theme.


问:
jQuery .Noconflict Issue
I have a problem that I just cannot resolve and its driving me insane. I am using the jQuery library and I am using ".noconflict".

I am trying to use this on my blog with the following script -

http://www.internetmarketingmonitor.org/word-press-plugins/imm-glossary-wordpress-plugin

The problem is - I keep getting the following error -

```<code>>  [Exception... "Component returned failure code: 0x80070057
> (NS_ERROR_ILLEGAL_VALUE) [nsIDOMXPathEvaluator.evaluate]"  nsresult:
> "0x80070057 (NS_ERROR_ILLEGAL_VALUE)"  location: "JS frame ::http://myblog.com/wp-content/plugins/IMM-Glossary/JavaScripts/prototype.js
> :: anonymous :: line 1081"  data: no]
> Source:http://myblog.com/wp-content/plugins/IMM-Glossary/JavaScripts/prototype.js
</code>```

What's not making sense is that I AM USING .NOCONFLICT? - The error can be easily replicated by simply downloading this plugin and putting the *.js on the same page as jquery?

Would anyone be able to help ?

答:
I found a slightly alt method of fixing my jquery conflicts that I hope might help others.

Like on this page I did the

  jq=jQuery.noConflict(true);

Just after the jquery.min.js was called. Then I did a

  jq=jQuery.noConflict(false);

after my actual script to make my page's lavalamp work. Now both my lavalamp and the side nav (which was causing the jquery conflict) are getting along.  :)

Possibly a lazy cheater way of going about it but I'm still learning here! hehe

OwnerDisplayName: Tom

Title: jQuery .Noconflict Issue

Body:
I have a problem that I just cannot resolve and its driving me insane. I am using the jQuery library and I am using ".noconflict".

I am trying to use this on my blog with the following script -

http://www.internetmarketingmonitor.org/word-press-plugins/imm-glossary-wordpress-plugin

The problem is - I keep getting the following error -

>  [Exception... "Component returned failure code: 0x80070057
> (NS_ERROR_ILLEGAL_VALUE) [nsIDOMXPathEvaluator.evaluate]"  nsresult:
> "0x80070057 (NS_ERROR_ILLEGAL_VALUE)"  location: "JS frame ::http://myblog.com/wp-content/plugins/IMM-Glossary/JavaScripts/prototype.js
> :: anonymous :: line 1081"  data: no]
> Source:http://myblog.com/wp-content/plugins/IMM-Glossary/JavaScripts/prototype.js

What's not making sense is that I AM USING .NOCONFLICT? - The error can be easily replicated by simply downloading this plugin and putting the *.js on the same page as jquery?

Would anyone be able to help ?


问:
How to format the content of a Java Properties object when using a Stream?
The static method System.getProperties() returns a Properties object containing the System Properties as key-value pairs.

In the SO post How would I print the JVM's system properties using Java 8 and lambdas? Radiodef provided a solution which works fine, and it can be enhanced to also sort the output:

```<code>        System.getProperties()
                .entrySet()
                .stream()
                .map(e -> e.getKey() + ": " + e.getValue())
                .sorted()
                .forEach(System.out::println);
</code>```

Here is a small portion of the sorted output produced by that statement:

I tried unsucessfully to amend the statement above so that the property values in the output are left-aligned. Since java.vm.specification.version happens to be the longest System Properties key, the formatted presentation of the output shown above should look like this:

Obviously the tricky part is to somehow know the length of the longest key prior to formatting the output. Any suggestions on how to achieve this in a single statement using a Stream, or is it impossible?

Update:

I forgot to state in the original post that an additional constraint is that the solution should also work using a parallel stream. My apologies for the oversight.

答:
This works:</p>

```<code>    AtomicInteger len = new AtomicInteger();
    ((Map<String, String>)(Map)System.getProperties())
    .entrySet()
    .parallelStream()
    .peek(e -> len.set(Integer.max(e.getKey().length(), len.get())))
    .sorted((e1, e2) -> (e1.getKey()).compareTo(e2.getKey()))
    .forEachOrdered(e -> System.out.printf("%-" + len + "s %s%n", e.getKey() + ":", e.getValue()));
</code>```

Body:
The static method System.getProperties() returns a Properties object containing the System Properties as key-value pairs.

In the SO post How would I print the JVM's system properties using Java 8 and lambdas? Radiodef provided a solution which works fine, and it can be enhanced to also sort the output:

        System.getProperties()
                .entrySet()
                .stream()
                .map(e -> e.getKey() + ": " + e.getValue())
                .sorted()
                .forEach(System.out::println);

Here is a small portion of the sorted output produced by that statement:

I tried unsucessfully to amend the statement above so that the property values in the output are left-aligned. Since java.vm.specification.version happens to be the longest System Properties key, the formatted presentation of the output shown above should look like this:

Obviously the tricky part is to somehow know the length of the longest key prior to formatting the output. Any suggestions on how to achieve this in a single statement using a Stream, or is it impossible?

Update:

I forgot to state in the original post that an additional constraint is that the solution should also work using a parallel stream. My apologies for the oversight.

Body:
This works:

    AtomicInteger len = new AtomicInteger();
    ((Map<String, String>)(Map)System.getProperties())
    .entrySet()
    .parallelStream()
    .peek(e -> len.set(Integer.max(e.getKey().length(), len.get())))
    .sorted((e1, e2) -> (e1.getKey()).compareTo(e2.getKey()))
    .forEachOrdered(e -> System.out.printf("%-" + len + "s %s%n", e.getKey() + ":", e.getValue()));


问:
How do I send a direct message to someone when they join a server with discord.py
I'm writing a bot for my discord server and I want to send an automatic direct message to anyone who joins the server for the first time. I have looked through the documentation and I can't find anything about how to do this. I am using python 3.5 and discord.py version 0.16.12.</p>

答:
https://discordpy.readthedocs.io/en/latest/api.html#discord.on_member_join

You can do something along the lines of:

```<code>await bot.send_message(member, "hello")
</code>```

Body:
https://discordpy.readthedocs.io/en/latest/api.html#discord.on_member_join

You can do something along the lines of:

await bot.send_message(member, "hello")


问:
Passing OSC messages between two computers over WAN via UDP and Node.js
I'm trying to write some minimalist client-server code to pass OSC messages between two computers that are on different local networks. Specifically my end goal is to send and receive from MAX patches in Ableton, using MAX's UDPSend and UDPReceive functions, which simply listen on local ports. Here is the server code, that I have Ableton's OSC Send MIDI module send to. This correctly receives output from the first computer's MAX patch, some MIDI data from a channel.

```<code>var osc = require('osc-min'),
dgram = require('dgram');
var remotes = [];
var FileReader = require('fs');

// listen for OSC messages and print them to the console
var udp = dgram.createSocket('udp4', function(msg, rinfo) {
  try {
    var oscmsg = osc.fromBuffer(msg);
    console.log(oscmsg);
    remotes.forEach(function(remote, index, array) {
        udp.send(msg, 0, oscmsg.length, 10000, remote);
        console.log('Sent OSC message to %s:%d', remote, 10000);
    });
  } catch (err) {
    console.log(err);
  }

});

FileReader.readFile('ips.txt', 'utf8', function(err, data) {
    // By lines
    var lines = data.split('\n');
    for(var line = 0; line < lines.length; line++){
        remotes.push(lines[line]);
    }
});

udp.bind(9998);
console.log('Listening for OSC messages on port 9998');
</code>```

The server correctly gets an OSC message like this:

```<code>{ address: '/Note1',
args: [ { type: 'integer', value: 60 } ],
oscType: 'message' }
</code>```

I then want to relay Computer 1's message to my remote server on port 9998 to the rest of the computers I have listening on port 10000. (The server is an Amazon EC2 Ubuntu instance.) The public IPs of these computers are in a file ips.txt.

On the receiving computers (testing on Windows), I set up a Node client to receive data via its public IP and relay it to localhost so the MAX patch can see it. Thus, any messages sent to 10000 on this computer will be sent to 127.0.0.1:9999.

```<code>var osc = require('osc-min'),
    dgram = require('dgram'),
    remote;

// listen for OSC messages and print them to the console
var udp = dgram.createSocket('udp4', function(msg, rinfo) {

  try {
    var oscmsg = osc.fromBuffer(msg);
    console.log(oscmsg);
    send(msg);
  } catch (err) {
    console.log('Could not decode OSC message');
  }

});

function send(oscMessage) {

  udp.send(oscMessage, 0, oscMessage.length, 9999, "127.0.0.1");
  console.log('Sent OSC message to %s:%d', "127.0.0.1", 9999);

}
udp.bind(10000);
console.log('Listening for OSC messages on port 10000');
</code>```

The problem is, the server's message never seems to reach the client. Once the server receives the message, it produces output as such:

```<code>Listening for OSC messages on port 9998
{ address: '/Velocity1',
args: [ { type: 'integer', value: 100 } ],   oscType: 'message' }
Sent OSC message to client-public-ip:10000
</code>```

But the client simply hangs on it's initial listening state

```<code>Listening for OSC messages on port 10000
</code>```

I thought this may be a problem with my firewall, and I made sure to enable UDP specifically through the port and on all the applications involved, to no gain. I'm hoping to avoid using HTTPRequests. I'd greatly appreciate any suggestions.

Edit: I created a diagram to help visualize what's supposed to be going on between these three computers. The dashed boxes represent the local network that computer is on (they are all on different networks). I hope this helps a bit.

答:
Daniel's solution to use WebSockets is correct. However, I also needed to be sure to connect the clients via the DNS name rather than the public ip address. For example:

```<code>const WebSocketClient = require('websocket').client;
const port = process.env.PORT || 3000;
const wsc = new WebSocketClient();
wsc.connect('ws://ec2.compute-1.amazonaws.com:4000/', 'echo-protocol');
</code>```

As opposed to:

```<code>wsc.connect('ws://1.2.3.4:4000/', 'echo-protocol');
</code>```

More details about this problem here.

I also used the 'websocket' npm module instead of 'ws,' but I'm not sure that made a difference.

Body:
I'm trying to write some minimalist client-server code to pass OSC messages between two computers that are on different local networks. Specifically my end goal is to send and receive from MAX patches in Ableton, using MAX's UDPSend and UDPReceive functions, which simply listen on local ports. Here is the server code, that I have Ableton's OSC Send MIDI module send to. This correctly receives output from the first computer's MAX patch, some MIDI data from a channel.

var osc = require('osc-min'),
dgram = require('dgram');
var remotes = [];
var FileReader = require('fs');

// listen for OSC messages and print them to the console
var udp = dgram.createSocket('udp4', function(msg, rinfo) {
  try {
    var oscmsg = osc.fromBuffer(msg);
    console.log(oscmsg);
    remotes.forEach(function(remote, index, array) {
        udp.send(msg, 0, oscmsg.length, 10000, remote);
        console.log('Sent OSC message to %s:%d', remote, 10000);
    });
  } catch (err) {
    console.log(err);
  }

});

FileReader.readFile('ips.txt', 'utf8', function(err, data) {
    // By lines
    var lines = data.split('\n');
    for(var line = 0; line < lines.length; line++){
        remotes.push(lines[line]);
    }
});

udp.bind(9998);
console.log('Listening for OSC messages on port 9998');

The server correctly gets an OSC message like this:

{ address: '/Note1',
args: [ { type: 'integer', value: 60 } ],
oscType: 'message' }

I then want to relay Computer 1's message to my remote server on port 9998 to the rest of the computers I have listening on port 10000. (The server is an Amazon EC2 Ubuntu instance.) The public IPs of these computers are in a file ips.txt.

On the receiving computers (testing on Windows), I set up a Node client to receive data via its public IP and relay it to localhost so the MAX patch can see it. Thus, any messages sent to 10000 on this computer will be sent to 127.0.0.1:9999.

var osc = require('osc-min'),
    dgram = require('dgram'),
    remote;

// listen for OSC messages and print them to the console
var udp = dgram.createSocket('udp4', function(msg, rinfo) {

  try {
    var oscmsg = osc.fromBuffer(msg);
    console.log(oscmsg);
    send(msg);
  } catch (err) {
    console.log('Could not decode OSC message');
  }

});

function send(oscMessage) {

  udp.send(oscMessage, 0, oscMessage.length, 9999, "127.0.0.1");
  console.log('Sent OSC message to %s:%d', "127.0.0.1", 9999);

}
udp.bind(10000);
console.log('Listening for OSC messages on port 10000');

The problem is, the server's message never seems to reach the client. Once the server receives the message, it produces output as such:

Listening for OSC messages on port 9998
{ address: '/Velocity1',
args: [ { type: 'integer', value: 100 } ],   oscType: 'message' }
Sent OSC message to client-public-ip:10000

But the client simply hangs on it's initial listening state

Listening for OSC messages on port 10000

I thought this may be a problem with my firewall, and I made sure to enable UDP specifically through the port and on all the applications involved, to no gain. I'm hoping to avoid using HTTPRequests. I'd greatly appreciate any suggestions.

Edit: I created a diagram to help visualize what's supposed to be going on between these three computers. The dashed boxes represent the local network that computer is on (they are all on different networks). I hope this helps a bit.

Body:
Daniel's solution to use WebSockets is correct. However, I also needed to be sure to connect the clients via the DNS name rather than the public ip address. For example:

const WebSocketClient = require('websocket').client;
const port = process.env.PORT || 3000;
const wsc = new WebSocketClient();
wsc.connect('ws://ec2.compute-1.amazonaws.com:4000/', 'echo-protocol');

As opposed to:

wsc.connect('ws://1.2.3.4:4000/', 'echo-protocol');

More details about this problem here.

I also used the 'websocket' npm module instead of 'ws,' but I'm not sure that made a difference.


问:
C - I'm having trouble coding a "rotate right" function
I'm having a little trouble writing my code to rotate my hexadecimal digits right. Below is a function I wrote, where, if you call on it, passing it like so: rotr(0x12345678, 4), it should return 0x81234567. Instead, it's only returning 7 digits (as opposed to eight, like in the original value = 0x12345678).

Can someone please help me understand what is going on in the bit level? I'm having trouble understanding why my current code is returning 0x123456f, instead of 0x81234567. Thanks in advance!

Edit: is it because I'm shifting 0x12345678 too early? I'm mainly trying to figure out why only seven digits return back, as opposed to eight.

```<code>unsigned int rotr(unsigned int x, int n) {
    int i; //iterate for loop
    unsigned int y; //masked last bit
    unsigned int z; //final result

    for (i=1; i<=n; i++) {
        y = x & 0x1; //isolates last bit
        x = x >> 1; //shift right 1
        z = x | (y << (sizeof(x)-1)); //shifts mask back to first slot; OR
                                      //it with x
    }

    return z;
}
</code>```

答: sizeof(x) will give the size of the variable in bytes, while the shift operators work with numbers of bits. You need to convert these operands to use the same unit.

Body:
I'm having a little trouble writing my code to rotate my hexadecimal digits right. Below is a function I wrote, where, if you call on it, passing it like so: rotr(0x12345678, 4), it should return 0x81234567. Instead, it's only returning 7 digits (as opposed to eight, like in the original value = 0x12345678).

Can someone please help me understand what is going on in the bit level? I'm having trouble understanding why my current code is returning 0x123456f, instead of 0x81234567. Thanks in advance!

Edit: is it because I'm shifting 0x12345678 too early? I'm mainly trying to figure out why only seven digits return back, as opposed to eight.

unsigned int rotr(unsigned int x, int n) {
    int i; //iterate for loop
    unsigned int y; //masked last bit
    unsigned int z; //final result

    for (i=1; i<=n; i++) {
        y = x & 0x1; //isolates last bit
        x = x >> 1; //shift right 1
        z = x | (y << (sizeof(x)-1)); //shifts mask back to first slot; OR
                                      //it with x
    }

    return z;
}


问:
How to order django model by foreign key image title alphabetically
I have model that I need to be able to order in the admin panel alphabetically by the title of the image foreign key. Currently with the code below the models get ordered by when the associated 'logo' images were added to the database, as opposed to by the titles of the associated 'logo' images.</p>

```<code>class Client(models.Model):
    logo = models.ForeignKey(
        'wagtailimages.Image',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+',
    )
    homepage_visible = models.BooleanField(default=True)

    panels = [
        MultiFieldPanel([
            ImageChooserPanel('logo'),
            FieldPanel('homepage_visible'),
        ], heading='Client information'),
    ]

    def __str__(self):
        return self.logo.title

    class Meta:
        verbose_name = 'Client Logo'
        verbose_name_plural = 'Client Logos'
        ordering = ['logo']
</code>```

答:
You would want to do an ordering of 'logo__title' to reach to the attribute title of the logo object (wagtailimages.Image).

Remember, when altering the meta class you will have to make migrations and migrate for your ordering to occur.

```<code>class Meta:
    ordering = ['logo__title']
</code>```

Body:
I have model that I need to be able to order in the admin panel alphabetically by the title of the image foreign key. Currently with the code below the models get ordered by when the associated 'logo' images were added to the database, as opposed to by the titles of the associated 'logo' images.

class Client(models.Model):
    logo = models.ForeignKey(
        'wagtailimages.Image',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+',
    )
    homepage_visible = models.BooleanField(default=True)

    panels = [
        MultiFieldPanel([
            ImageChooserPanel('logo'),
            FieldPanel('homepage_visible'),
        ], heading='Client information'),
    ]

    def __str__(self):
        return self.logo.title

    class Meta:
        verbose_name = 'Client Logo'
        verbose_name_plural = 'Client Logos'
        ordering = ['logo']

Body:
You would want to do an ordering of 'logo__title' to reach to the attribute title of the logo object (wagtailimages.Image).

Remember, when altering the meta class you will have to make migrations and migrate for your ordering to occur.

class Meta:
    ordering = ['logo__title']


问:
Oracle PL/SQL Stored Procedure Cursor for update
I am trying to update the 'damage_amt' of cars by increasing the value by 'inc', but only for accidents that occurred in year 'year'.

```<code>CREATE or REPLACE PROCEDURE updateDMG(xyear VARCHAR2, inc NUMBER) AS
    CURSOR cur1 IS
        select a.DAMAGE_AMT
        from participated a join accident b
        on a.report_nr = b.report_nr
        for update;
    p_dmg PARTICPATED.damage_amt%TYPE;
    p_year NUMBER;
    inc_dmg NUMBER;
BEGIN
    p_year:=xyear;
    inc_dmg:=inc;
    OPEN cur1;
    LOOP
        FETCH cur1 bulk collect INTO p_dmg;
        EXIT WHEN cur1%NOTFOUND;
        UPDATE PARTICIPATED
        SET damage_amt = damage_amt * inc_dmg
        WHERE p_dmg like xyear;
    END LOOP;
    CLOSE cur1;
END updateDMG;
/
EXEC updateDMG('08', 0.10);
</code>```

But I'm getting the error:

```<code>PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following: begin function pragma procedure subtype <an identifier> <a double-quoted delimited-identifier> current cursor delete exists prior
</code>```

Obviously I am lacking knowledge on the syntax of this type of answer. Can anyone point out my error? I can't seem to find anything from searching.

EDIT: Was missing a / after END. Now it doesn't actually update the rows.

FINAL EDIT: Figured it out. I think some of my variables are unnecessary, but I could be wrong.

```<code>CREATE or REPLACE PROCEDURE updateDMG(xyear NUMBER, inc DECIMAL) AS
CURSOR cur1 IS
    select a.DAMAGE_AMT, extract(year from b.ACCIDENT_DATE)
    from participated a join accident b
    on a.report_nr = b.report_nr
    for update;

p_dmg PARTICIPATED.damage_amt%TYPE;
p_year NUMBER;
input_year NUMBER;
inc_dmg DECIMAL;

BEGIN
input_year:=xyear;
inc_dmg:=inc;
OPEN cur1;

    FETCH cur1 INTO p_dmg, p_year;

    MERGE INTO PARTICIPATED x
    USING ACCIDENT y
    ON (x.report_nr = y.report_nr)
    WHEN MATCHED THEN
    UPDATE SET x.damage_amt = x.damage_amt * (1 + inc_dmg/100)
    WHERE extract(year from y.accident_date) = input_year;

CLOSE cur1;

END updateDMG;
/
EXEC updateDMG(2008, 10);
</code>```

答:
I don't have a database right now to fully check syntax, but I would suggest something like this:

```<code>CREATE OR REPLACE PROCEDURE updatedmg (p_year NUMBER, p_inc DECIMAL)
AS
   l_next_year   NUMBER;
   l_from_date   DATE;
   l_to_date     DATE;
BEGIN
   l_next_year := p_year + 1;
   l_from_date := TO_DATE (p_year || '-01-01', 'RRRR-MM-DD');
   l_to_date := TO_DATE (l_next_year || '-01-01', 'RRRR-MM-DD');

   UPDATE participated pt
      SET pt.damage_amt = pt.damage_amt * (1 + p_inc / 100)
    WHERE pd.report_nr IN (SELECT ad.report_nr
                             FROM accident ad
                            WHERE ad.accident_date >= l_from_date
                                  AND ad.accident_date < l_to_date);
END updatedmg;
</code>```

Its simple and that way you probably can make better use of indexes on tables.

I hope it helps.

Good luck!

Body:
I am trying to update the 'damage_amt' of cars by increasing the value by 'inc', but only for accidents that occurred in year 'year'.

CREATE or REPLACE PROCEDURE updateDMG(xyear VARCHAR2, inc NUMBER) AS
    CURSOR cur1 IS
        select a.DAMAGE_AMT
        from participated a join accident b
        on a.report_nr = b.report_nr
        for update;
    p_dmg PARTICPATED.damage_amt%TYPE;
    p_year NUMBER;
    inc_dmg NUMBER;
BEGIN
    p_year:=xyear;
    inc_dmg:=inc;
    OPEN cur1;
    LOOP
        FETCH cur1 bulk collect INTO p_dmg;
        EXIT WHEN cur1%NOTFOUND;
        UPDATE PARTICIPATED
        SET damage_amt = damage_amt * inc_dmg
        WHERE p_dmg like xyear;
    END LOOP;
    CLOSE cur1;
END updateDMG;
/
EXEC updateDMG('08', 0.10);

But I'm getting the error:

PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following: begin function pragma procedure subtype <an identifier>  current cursor delete exists prior

Obviously I am lacking knowledge on the syntax of this type of answer. Can anyone point out my error? I can't seem to find anything from searching.

EDIT: Was missing a / after END. Now it doesn't actually update the rows.

FINAL EDIT: Figured it out. I think some of my variables are unnecessary, but I could be wrong.

CREATE or REPLACE PROCEDURE updateDMG(xyear NUMBER, inc DECIMAL) AS
CURSOR cur1 IS
    select a.DAMAGE_AMT, extract(year from b.ACCIDENT_DATE)
    from participated a join accident b
    on a.report_nr = b.report_nr
    for update;

p_dmg PARTICIPATED.damage_amt%TYPE;
p_year NUMBER;
input_year NUMBER;
inc_dmg DECIMAL;

BEGIN
input_year:=xyear;
inc_dmg:=inc;
OPEN cur1;

    FETCH cur1 INTO p_dmg, p_year;

    MERGE INTO PARTICIPATED x
    USING ACCIDENT y
    ON (x.report_nr = y.report_nr)
    WHEN MATCHED THEN
    UPDATE SET x.damage_amt = x.damage_amt * (1 + inc_dmg/100)
    WHERE extract(year from y.accident_date) = input_year;

CLOSE cur1;

END updateDMG;
/
EXEC updateDMG(2008, 10);

Body:
I don't have a database right now to fully check syntax, but I would suggest something like this:

CREATE OR REPLACE PROCEDURE updatedmg (p_year NUMBER, p_inc DECIMAL)
AS
   l_next_year   NUMBER;
   l_from_date   DATE;
   l_to_date     DATE;
BEGIN
   l_next_year := p_year + 1;
   l_from_date := TO_DATE (p_year || '-01-01', 'RRRR-MM-DD');
   l_to_date := TO_DATE (l_next_year || '-01-01', 'RRRR-MM-DD');

   UPDATE participated pt
      SET pt.damage_amt = pt.damage_amt * (1 + p_inc / 100)
    WHERE pd.report_nr IN (SELECT ad.report_nr
                             FROM accident ad
                            WHERE ad.accident_date >= l_from_date
                                  AND ad.accident_date < l_to_date);
END updatedmg;

Its simple and that way you probably can make better use of indexes on tables.

I hope it helps.

Good luck!


问:
Drag and drop remove target element
I feel like this should be really simple. I wrote a codepen for it, just to talk out the problem https://codepen.io/rubixKube/pen/yPXPzr.

I am trying to remove the parent node (span) without removing the thing I just dropped it into.

Just wondering if someone out there has a better idea of how to do this.

I've tried this on my onmouse event:

```<code>//capturing the elements in variables
var mytarget = event.target;
var mytargetsibling = event.target.previousElementSibling;

//next three lines are just how drag and drop works
event.preventDefault();
var data = event.dataTransfer.getData("text");
event.target.appendChild(document.getElementById(data));

//trying to remove it AND then put the child back
this.parentNode.remove(this);
mytargetsibling.appendChild(mytarget);
</code>```

function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  ev.target.appendChild(document.getElementById(data));
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tags {
  padding: 6px;
}

.drop-area {
  border: 1px solid red;
}

.drag-this {
  background: blue;
  color: white;
}</code>```

    Apple
    Drop HERE

Apple

```

答:
I'd suggest that, rather than event.target.appendChild() you use instead: event.target.parentNode.replaceChild(newElement, event.target) which will, as the method-name suggests, replace the existing child (event.target) with the new child (newElement):

function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text"),

    // cached as a variable to simplify the later
    // code for readability:
    elToAdd = document.getElementById(data),

    // we're accessing this node twice, so caching it here:
    dropBefore = ev.target;

  // moving from the dropBefore node to its parentNode,
  // and calling the replaceChild() method to insert
  // 'elToAdd' in place of the existing 'dropBefore' node:
  dropBefore.parentNode.replaceChild(elToAdd, dropBefore);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tags {
  padding: 6px;
}

.drop-area {
  border: 1px solid red;
}

.drag-this {
  background: blue;
  color: white;
}</code>```

    Apple
    Drop HERE

Apple

```
</div>
</div>
</p>

<p>Or, instead, you could use <code>Node.replaceWith()</code>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text"),

    // caching as variables to simplify the later
    // code for readability:
    elToAdd = document.getElementById(data),
    dropBefore = ev.target;

  // using childNode.replaceWith() to insert the
  // elToAdd Node in place of the existing
  // dropBefore Node:
  dropBefore.replaceWith(elToAdd);
}</code>```

.tags {
  padding: 6px;
}

.drop-area {
  border: 1px solid red;
}

.drag-this {
  background: blue;
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>
    <span class="header tags">Apple</span>
    <span class="drop-area target-drop tags" ondrop="drop(event)" ondragover="allowDrop(event)">Drop HERE</span>
  </li>
</ul>
<ul>
  <li><span id="drag1" class="drag-this tags" draggable="true" ondragstart="drag(event)">Apple</span></li>
</ul></code>```

References:

childNode.replaceWith().

Node.replaceChild().

Title: Drag and drop remove target element

Body:
I feel like this should be really simple. I wrote a codepen for it, just to talk out the problem https://codepen.io/rubixKube/pen/yPXPzr.

I am trying to remove the parent node (span) without removing the thing I just dropped it into.

Just wondering if someone out there has a better idea of how to do this.

I've tried this on my onmouse event:

//capturing the elements in variables
var mytarget = event.target;
var mytargetsibling = event.target.previousElementSibling;

//next three lines are just how drag and drop works
event.preventDefault();
var data = event.dataTransfer.getData("text");
event.target.appendChild(document.getElementById(data));

//trying to remove it AND then put the child back
this.parentNode.remove(this);
mytargetsibling.appendChild(mytarget);

function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  ev.target.appendChild(document.getElementById(data));
}

.tags {
  padding: 6px;
}

.drop-area {
  border: 1px solid red;
}

.drag-this {
  background: blue;
  color: white;
}

    Apple
    Drop HERE

Apple

Body:
I'd suggest that, rather than event.target.appendChild() you use instead: event.target.parentNode.replaceChild(newElement, event.target) which will, as the method-name suggests, replace the existing child (event.target) with the new child (newElement):

function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text"),

    // cached as a variable to simplify the later
    // code for readability:
    elToAdd = document.getElementById(data),

    // we're accessing this node twice, so caching it here:
    dropBefore = ev.target;

  // moving from the dropBefore node to its parentNode,
  // and calling the replaceChild() method to insert
  // 'elToAdd' in place of the existing 'dropBefore' node:
  dropBefore.parentNode.replaceChild(elToAdd, dropBefore);
}

.tags {
  padding: 6px;
}

.drop-area {
  border: 1px solid red;
}

.drag-this {
  background: blue;
  color: white;
}

<ul>
  <li>
    <span class="header tags">Apple</span>
    <span class="drop-area target-drop tags" ondrop="drop(event)" ondragover="allowDrop(event)">Drop HERE</span>
  </li>
</ul>
<ul>
  <li><span id="drag1" class="drag-this tags" draggable="true" ondragstart="drag(event)">Apple</span></li>
</ul>

Or, instead, you could use Node.replaceWith():

function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text"),

    // caching as variables to simplify the later
    // code for readability:
    elToAdd = document.getElementById(data),
    dropBefore = ev.target;

  // using childNode.replaceWith() to insert the
  // elToAdd Node in place of the existing
  // dropBefore Node:
  dropBefore.replaceWith(elToAdd);
}

.tags {
  padding: 6px;
}

.drop-area {
  border: 1px solid red;
}

.drag-this {
  background: blue;
  color: white;
}

<ul>
  <li>
    <span class="header tags">Apple</span>
    <span class="drop-area target-drop tags" ondrop="drop(event)" ondragover="allowDrop(event)">Drop HERE</span>
  </li>
</ul>
<ul>
  <li><span id="drag1" class="drag-this tags" draggable="true" ondragstart="drag(event)">Apple</span></li>
</ul>

References:

childNode.replaceWith().

Node.replaceChild().