问:
Scikit learn preprocessing LabelBinarizer with lambda function
I am trying my hand on the Titanic dataset.

I would like to use the LabelBinarizer on a few columns and I would like to avoid using a for loop.

I am trying to use a lambda function but it doesn't work:

```<code>from sklearn.preprocessing import LabelBinarizer

pp = LabelBinarizer()

X = df['sex', 'embarked', 'alive'] df.apply(lambda X: pp.fit_transform())
</code>```

And:

```<code>df[['sex','embarked','alive']]= df[['sex','embarked','alive']].apply(lambda x: pp.fit_transform(x))
</code>```

Could someone point me in the right direction please?

答:
I think the issue is that because you are passing three cols on the left, sklearn is getting confused.

Alternative

But as @unutbu said, there is no difference in performance between df.apply and for so I'd just use this:

```<code>for col in ['sex','embarked','alive']:
     df[col] = pp.fit_transform(df[col])
</code>```

But if you really do a one liner, here's how you do it (warning, massive overkill):

Add another layer of indentation to the fit, tranform and fit_transform methods as the formatting doesn't work (should match the indentation of the def __init__ method.

```<code>class MultiColumnLabelBinarizer:
    def __init__(self,columns = None):
        self.columns = columns # array of column names to encode`

    def fit(self,X,y=None):
        return self # not relevant here

    def transform(self,X):
        '''
        Transforms columns of X specified in self.columns using
        LabelEncoder(). If no columns specified, transforms all
        columns in X.
        '''
        output = X.copy()
        if self.columns is not None:
            for col in self.columns:
                output[col] = LabelBinarizer().fit_transform(output[col])
        else:
            for colname,col in output.iteritems():
                output[colname] = LabelBinarizer().fit_transform(col)
        return output

    def fit_transform(self,X,y=None):
        return self.fit(X,y).transform(X)

df = MultiColumnLabelBinarizer(columns = ['embarked','alive']).fit_transform(df)
</code>```

Source: Label encoding across multiple columns in scikit-learn

Body:
I am trying my hand on the Titanic dataset.

I would like to use the LabelBinarizer on a few columns and I would like to avoid using a for loop.

I am trying to use a lambda function but it doesn't work:

from sklearn.preprocessing import LabelBinarizer

pp = LabelBinarizer()

X = df['sex', 'embarked', 'alive'] df.apply(lambda X: pp.fit_transform())

And:

df[['sex','embarked','alive']]= df[['sex','embarked','alive']].apply(lambda x: pp.fit_transform(x))

Could someone point me in the right direction please?

Body:
I think the issue is that because you are passing three cols on the left, sklearn is getting confused.

Alternative

But as @unutbu said, there is no difference in performance between df.apply and for so I'd just use this:

for col in ['sex','embarked','alive']:
     df[col] = pp.fit_transform(df[col])

But if you really do a one liner, here's how you do it (warning, massive overkill):

Add another layer of indentation to the fit, tranform and fit_transform methods as the formatting doesn't work (should match the indentation of the def __init__ method.

class MultiColumnLabelBinarizer:
    def __init__(self,columns = None):
        self.columns = columns # array of column names to encode`

    def fit(self,X,y=None):
        return self # not relevant here

    def transform(self,X):
        '''
        Transforms columns of X specified in self.columns using
        LabelEncoder(). If no columns specified, transforms all
        columns in X.
        '''
        output = X.copy()
        if self.columns is not None:
            for col in self.columns:
                output[col] = LabelBinarizer().fit_transform(output[col])
        else:
            for colname,col in output.iteritems():
                output[colname] = LabelBinarizer().fit_transform(col)
        return output

    def fit_transform(self,X,y=None):
        return self.fit(X,y).transform(X)

df = MultiColumnLabelBinarizer(columns = ['embarked','alive']).fit_transform(df)

Source: Label encoding across multiple columns in scikit-learn


来源: stackexchange

问:
hosting multiple websites on SBS2008 server
Disclaimer: I'm new to the server end of websites so my question may not be well formed.   I'm also new to working in an SBS (Microsoft Small Business Server 2008) environment so what I think I know may not apply here.

If you're still reading, thanks!  What I'm trying to do is setup a company intranet site on our SBS (Standard Ed) server.  Currently there are a number of sites already configured to run on port 80 so I'm assuming (possibly incorrectly?) that I can add the intranet site on port 80 as  well.  I currently have the intranet running on port 8550 or something along those lines, but my users have to type http: //server:8550 and that's not too intuitive.  I'd like for them to type http: //intranet, or just intranet in the address line and get to where they're going.  I need to know how to redirect a friendly address like http: //intranet or just intranet to the site listening on http: //server:8550 address.

Can this be done?

(sorry for the spacing in the URLs above, I'm a new user and can't post hyperlinks in my questions yet.)

答: You need to get "intranet" registered in your company's DNS and point it at your server.  (Either with an "A" record pointing to the server's IP address, or a "CNAME" record to the server's name.)  Then in your IIS site, add a new host header set to "All Unassigned" IP address, port 80, with a host header of "intranet".  Those 3 values have to be unique across all other websites on the box for it to work.</p>

ContentLicense: CC BY-SA 2.5


问:
How to add button to PHP file
my friend asked me to improve his site. He needs to add button to job list post but I don't know how, I am using only HTML/CSS, not PHP.

There is a code:

```<code><?php if( $permalink ) : ?>
            <a href="<?php echo esc_url($permalink);?>"><?php echo $thumbnail_image_output;?></a>
        <?php else:?>
            <?php echo $thumbnail_image_output;?>
        <?php endif;?>
    </div>
</div>
<?php endif;?>

<div class="person_data">

    <?php if( $permalink ) : ?>
        <h5 class="person_name"><a href="<?php echo esc_url($permalink);?>"><?php the_title();?></a></h5>
    <?php else:?>
        <h5 class="person_name"><?php the_title();?></h5>
    <?php endif;?>

    <?php if(! empty( $position )) : ?>
        <span class="position"><?php echo apply_filters( "rtframework_team_position", esc_attr( $position ) );?></span>
    <?php endif;?>

    <?php if(! empty( $short_data )) : ?>
    <div class="profile">
        <?php echo apply_filters( "the_content", $short_data );?>
    </div>
    <?php endif;?>

    <?php do_action("rtframework_staff_media_links",$post->ID); ?>
</div>
</code>```

The question is, how to add button with link to the full post above the "the_content"?

I will be very happy if you show me the way.

Sorry for my English and have nice day :-)

答:
I agree with your friend, from a usability viewpoint a "read article" link helps a lot. But it should be below the teaser text, not above. And that's easy to do, just create an  tag wherever you want it to be, encapsulate it with a check for $permalink and put <?php echo $permalink; ?> in the href attribute. In this example it would be between the teaser text and the social media buttons (and look like the button on the home page):

```<code><?php if(! empty( $short_data )) : ?>
<div class="profile">
    <?php echo apply_filters( "the_content", $short_data );?>
</div>
<?php endif;?>

<?php if( $permalink ) : ?>
    <a href="<?php echo $permalink; ?>" target="_self" title="read more" class="button_  style-1 small"><span><span>read more</span></span></a>
<?php endif;?>

<?php do_action("rtframework_staff_media_links",$post->ID); ?>
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to add button to PHP file

Body:
my friend asked me to improve his site. He needs to add button to job list post but I don't know how, I am using only HTML/CSS, not PHP.

There is a code:

<?php if( $permalink ) : ?>
            <a href="<?php echo esc_url($permalink);?>"><?php echo $thumbnail_image_output;?>
        <?php else:?>
            <?php echo $thumbnail_image_output;?>
        <?php endif;?>

<?php endif;?>

    <?php if( $permalink ) : ?>

<a href="<?php echo esc_url($permalink);?>"><?php the_title();?>

    <?php else:?>

<?php the_title();?>

    <?php endif;?>

    <?php if(! empty( $position )) : ?>
        <?php echo apply_filters( "rtframework_team_position", esc_attr( $position ) );?>
    <?php endif;?>

    <?php if(! empty( $short_data )) : ?>

        <?php echo apply_filters( "the_content", $short_data );?>

    <?php endif;?>

    <?php do_action("rtframework_staff_media_links",$post->ID); ?>

The question is, how to add button with link to the full post above the "the_content"?

I will be very happy if you show me the way.

Sorry for my English and have nice day :-)

Body:
I agree with your friend, from a usability viewpoint a "read article" link helps a lot. But it should be below the teaser text, not above. And that's easy to do, just create an  tag wherever you want it to be, encapsulate it with a check for $permalink and put <?php echo $permalink; ?> in the href attribute. In this example it would be between the teaser text and the social media buttons (and look like the button on the home page):

<?php if(! empty( $short_data )) : ?>
<div class="profile">
    <?php echo apply_filters( "the_content", $short_data );?>
</div>
<?php endif;?>

<?php if( $permalink ) : ?>
    <a href="<?php echo $permalink; ?>" target="_self" title="read more" class="button_  style-1 small"><span><span>read more</span></span></a>
<?php endif;?>

<?php do_action("rtframework_staff_media_links",$post->ID); ?>


问:
Sticky footer at bottom without having content in body overlap
I have a sticky footer that sticks to the bottom, but the problem is the contents in the body and the footer overlap.

I currently have my html, body, and main set to height 100% / min-height: 100%, but and my footer is positioned absolute with left: 0 and bottom: 0. The problem with this is, I have my background image positioned at the bottom of my main and it overlaps onto the positioned absolute footer.

I also tried not having my footer positioned absolute and just have the main height 100%, and this works fine, but I have to scroll down to see the footer. Why is the footer being pushed down so much that I need to scroll down? I want the footer to be exactly at the bottom of the page without having to scroll down to see it.

```<code><html>
   <body>
     <main>
       <div>Contents here</div>
     </main>
     <footer/>
   </body>
</html>

html, body, main {
   height: 100%;
}
.content {
    background-repeat: no-repeat;
    background-position-y: 100%;
    background-position-x: center;
    background-size: 1000px;
}
</code>```

答:
This is sticky footer code that works. You might want to use this layout to solve your issue.

html, body {
  height: 100%;
  margin: 0;
}
.content {
  padding: 20px;
  min-height: 100%;
  margin: 0 auto -50px;
}
.footer,
.push {
  height: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content">
  <h1>Sticky Footer with Negative Margin 1</h1>
  <p><button id="add">Add Content</button></p>
  <div class="push"></div>
</div>

<footer class="footer">
  Footer
</footer></code>```

Body:
I have a sticky footer that sticks to the bottom, but the problem is the contents in the body and the footer overlap.

I currently have my html, body, and main set to height 100% / min-height: 100%, but and my footer is positioned absolute with left: 0 and bottom: 0. The problem with this is, I have my background image positioned at the bottom of my main and it overlaps onto the positioned absolute footer.

I also tried not having my footer positioned absolute and just have the main height 100%, and this works fine, but I have to scroll down to see the footer. Why is the footer being pushed down so much that I need to scroll down? I want the footer to be exactly at the bottom of the page without having to scroll down to see it.

Contents here

html, body, main {
   height: 100%;
}
.content {
    background-repeat: no-repeat;
    background-position-y: 100%;
    background-position-x: center;
    background-size: 1000px;
}

Body:
This is sticky footer code that works. You might want to use this layout to solve your issue.

html, body {
  height: 100%;
  margin: 0;
}
.content {
  padding: 20px;
  min-height: 100%;
  margin: 0 auto -50px;
}
.footer,
.push {
  height: 50px;
}

<div class="content">
  <h1>Sticky Footer with Negative Margin 1</h1>
  <p><button id="add">Add Content</button></p>
  <div class="push"></div>
</div>

<footer class="footer">
  Footer
</footer>


问:
How to pass ARG value to ENTRYPOINT?
Docker 1.9 allows to pass arguments to a dockerfile. See link: https://docs.docker.com/engine/reference/builder/#arg

How can i pass the same arugments within ENTRYPOINT Instruction??

My dockerfile has

ARG $Version=3.1

  ENTRYPOINT /tmp/folder-$Version/sample.sh start

I am getting an error while creating container with above dockerfile.
Please suggest what is the correct way to specify the argument within ENTRYPOINT instruction??

答:
Like Blake Mitchell sais, you cannot use ARG in ENTRYPOINT. However you can use your ARG as a value for ENV, that way you can use it with ENTRYPOINT:

Dockerfile

```<code>ARG my_arg
ENV my_env_var=$my_arg

ENTRYPOINT echo $my_env_var
</code>```

and  run:

```<code>docker build --build-arg "my_arg=foo" ...
</code>```

Title: How to pass ARG value to ENTRYPOINT?

Body:
Like Blake Mitchell sais, you cannot use ARG in ENTRYPOINT. However you can use your ARG as a value for ENV, that way you can use it with ENTRYPOINT:

Dockerfile

ARG my_arg
ENV my_env_var=$my_arg

ENTRYPOINT echo $my_env_var

and  run:

docker build --build-arg "my_arg=foo" ...

ContentLicense: CC BY-SA 4.0


问:
Fill array in Firebase Cloud Functions from Firebase database
I have a function thats triggered onWrite() and I successfully load the data I want. The thing I am having a hard time trying to solve is when later in that function I want to load a list with tokens stored in the database.

This is what I've got so far.

```<code>const root = event.data.ref.root
const loadMembers = root.child(`groups/${nameOfGroup}/members`).once('value')
const users = loadMembers.then( snap => {
    const members = snap.val()

    // something like this
   // const members = user.child({id})
})
</code>```

Is there a way to do that?

The data is stored like this.

```<code>{ ekXL3hQyBsNaYaPYudHRySahX5s2:
   { emailAddress: 'notMyRealEmail123@gmail.com',
     firstName: 'user 1',
     token: 'token4life',
     lastName: '1 User',
     phoneNumber: '+1112222' },
  syRUK9NG11TSHYLMRWbxCFhf2eJ3:
   { emailAddress: 'user2@gmail.cool',
     firstName: 'User 2',
     id: 'token2m8s',
     lastName: '2 User',
     phoneNumber: '+111111111' }
</code>```

答:
If I understand your question correctly you want something like this:</p>

```<code>const root = event.data.ref.root
const loadMembers = root.child(`groups/${nameOfGroup}/members`).once('value')
const users = loadMembers.then( snap => {
    const members = snap.val()
    console.log(members);

    snap.forEach(function(childSnap) {
        console.log(childSnap.val());

        var email = childSnap.child("emailAddress").val();
        var token = childSnap.child("token").val();

        console.log("Token: " + token);
    });
 })
</code>```

Body:
I have a function thats triggered onWrite() and I successfully load the data I want. The thing I am having a hard time trying to solve is when later in that function I want to load a list with tokens stored in the database.

This is what I've got so far.

const root = event.data.ref.root
const loadMembers = root.child(`groups/${nameOfGroup}/members`).once('value')
const users = loadMembers.then( snap => {
    const members = snap.val()

    // something like this
   // const members = user.child({id})
})

Is there a way to do that?

The data is stored like this.

{ ekXL3hQyBsNaYaPYudHRySahX5s2:
   { emailAddress: 'notMyRealEmail123@gmail.com',
     firstName: 'user 1',
     token: 'token4life',
     lastName: '1 User',
     phoneNumber: '+1112222' },
  syRUK9NG11TSHYLMRWbxCFhf2eJ3:
   { emailAddress: 'user2@gmail.cool',
     firstName: 'User 2',
     id: 'token2m8s',
     lastName: '2 User',
     phoneNumber: '+111111111' }

Body:
If I understand your question correctly you want something like this:

const root = event.data.ref.root
const loadMembers = root.child(`groups/${nameOfGroup}/members`).once('value')
const users = loadMembers.then( snap => {
    const members = snap.val()
    console.log(members);

    snap.forEach(function(childSnap) {
        console.log(childSnap.val());

        var email = childSnap.child("emailAddress").val();
        var token = childSnap.child("token").val();

        console.log("Token: " + token);
    });
 })


问:
gcloud command not found - while installing Google Cloud SDK
I am on a mac and am trying to install the Google Cloud SDK (including the gcloud command line utility) using this command in terminal

```<code>curl https://sdk.cloud.google.com | bash
</code>```

as seen at https://cloud.google.com/sdk/

It got all the way to the end and finished but even after I restarted my shell, the gcloud command still says it's not found.

Why isn't this installation working?

答:
I'm running zsh and found this gist very helpful: https://gist.github.com/dwchiang/10849350

Edit the ~/.zshrc file to include these two lines:

```<code># The next line updates PATH for the Google Cloud SDK.
source /Users/YOUR_USERNAME/google-cloud-sdk/path.zsh.inc

# The next line enables zsh completion for gcloud.
source /Users/YOUR_USERNAME/google-cloud-sdk/completion.zsh.inc
</code>```

This assumes you installed the package in your main directory from the official docs

Body:
I am on a mac and am trying to install the Google Cloud SDK (including the gcloud command line utility) using this command in terminal

curl https://sdk.cloud.google.com | bash

as seen at https://cloud.google.com/sdk/

It got all the way to the end and finished but even after I restarted my shell, the gcloud command still says it's not found.

Why isn't this installation working?

Body:
I'm running zsh and found this gist very helpful: https://gist.github.com/dwchiang/10849350

Edit the ~/.zshrc file to include these two lines:

# The next line updates PATH for the Google Cloud SDK.
source /Users/YOUR_USERNAME/google-cloud-sdk/path.zsh.inc

# The next line enables zsh completion for gcloud.
source /Users/YOUR_USERNAME/google-cloud-sdk/completion.zsh.inc

This assumes you installed the package in your main directory from the official docs


问:
How to tweak an existing nodejs module and use it outside node_modules folder?
I'm using the module node-libcurl. When I deploy my app to Heroku it crashes when I initiate a function from the module (that works on my computer).

Thus I would like to add some logging to the existing node-libcurl module to troubleshoot the issue, and put it in my lib folder outside the node_modules (I excluded it from the git heroku repo).

I added node-pre-gyp lib to the node_modules explicitly.

For information the error is self-explanatory:

```<code>Error: getInfo failed. Error: An unknown option was passed in to libcurl
at Curl.getInfo (/app/node_modules/node-libcurl/lib/Curl.js:1023:15)
at Object.keys.filter.forEach.key (/app/src/libs/node-libcurl-promise.js:70:23)
at Array.forEach (<anonymous>)
at Curl.curl.on (/app/src/libs/node-libcurl-promise.js:69:6)
at emitThree (events.js:136:13)
at Curl.emit (events.js:217:7)
at Curl._onEnd (/app/node_modules/node-libcurl/lib/Curl.js:929:10)
at Multi.<anonymous> (/app/node_modules/node-libcurl/lib/Curl.js:52:14)
</code>```

I would like to figure out what is the option that I set and that doesn't work
 on Heroku and that works on my computer.

Thank you!

答: The key might be in the error messase: An unknown option was passed in to libcurl. It implies that libcurl was told to set/use an option that it doesn't know about. Probably because it is (too) old so your code is using an option that was added to a newer libcurl version and node-libcurl was built to use one or more of those newer options that your older libcurl doesn't know about!

Body:
I'm using the module node-libcurl. When I deploy my app to Heroku it crashes when I initiate a function from the module (that works on my computer).

Thus I would like to add some logging to the existing node-libcurl module to troubleshoot the issue, and put it in my lib folder outside the node_modules (I excluded it from the git heroku repo).

I added node-pre-gyp lib to the node_modules explicitly.

For information the error is self-explanatory:

Error: getInfo failed. Error: An unknown option was passed in to libcurl
at Curl.getInfo (/app/node_modules/node-libcurl/lib/Curl.js:1023:15)
at Object.keys.filter.forEach.key (/app/src/libs/node-libcurl-promise.js:70:23)
at Array.forEach (<anonymous>)
at Curl.curl.on (/app/src/libs/node-libcurl-promise.js:69:6)
at emitThree (events.js:136:13)
at Curl.emit (events.js:217:7)
at Curl._onEnd (/app/node_modules/node-libcurl/lib/Curl.js:929:10)
at Multi.<anonymous> (/app/node_modules/node-libcurl/lib/Curl.js:52:14)

I would like to figure out what is the option that I set and that doesn't work
 on Heroku and that works on my computer.

Thank you!


问:
Wordpress don't recognize url parameters
I'm using wordpress and developed an angular code to open a button in my DOM The calculated fields are correctly working, but I need to use a angular created code to display a button in according to an parameter (called campanha) value.
Let me try explain th history:
I'm working with Marketing in Google Adwords campaigns, and we created 3  campaigns, (one for Brazil, other for US and other for UK, i.e.), and the values of each campaign are sent to me through the Google search page.

Below I have an example from what I'm talking:

```<code><http://www.redecidada.org.br/calculo-cota-aprendizes> (working)
<http://www.redecidada.org.br/calculo-cota-aprendizes?campanha=mg> (404)
<http://www.redecidada.org.br/calculo-cota-aprendizes/?campanha=mg> (404)
</code>```

答:
It seems that the problem is on your wordpress page/configuration.
If you try: http://www.redecidada.org.br/calculo-cota-aprendizes/?nome-campanha=mg.

There's no problem if you change "campanha" text... The error is in your code/page. Need more info.

Body:
I'm using wordpress and developed an angular code to open a button in my DOM The calculated fields are correctly working, but I need to use a angular created code to display a button in according to an parameter (called campanha) value.
Let me try explain th history:
I'm working with Marketing in Google Adwords campaigns, and we created 3  campaigns, (one for Brazil, other for US and other for UK, i.e.), and the values of each campaign are sent to me through the Google search page.

Below I have an example from what I'm talking:

<http://www.redecidada.org.br/calculo-cota-aprendizes> (working)
<http://www.redecidada.org.br/calculo-cota-aprendizes?campanha=mg> (404)
<http://www.redecidada.org.br/calculo-cota-aprendizes/?campanha=mg> (404)


问:
How to make Socket IO work over HTTPS using node.js
This is frustrating me like crazy!

i'm using a proxy so that any requests that go to myurl/APP/ are answered by node.js at myurl:8001

I now need this to work over https. easy.... i thought.

i have Apache serving up the old version from the public folder. That is stand alone, and when i'm done building this, it will just be removed. but for now needs to remain in tact and accessible. Lets encrypt is setup on this. and https://myurl works fine, showing content from the public folder of course.

if i go to https://myurl:8001 then chrome says "site can't be reached". If i go to http://myurl:8001 it works fine. I think this is because https default port is 443. I have VPS not dedicated so i don't think i can alter that. And surely if i did alter the ssl port then it wont work for the public folder??

i'll show you the basics of whats going on;

app.js;

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

app.get('/',function(req, res) {
    res.sendFile(__dirname + '/client/index.html');
});
app.use('/client',express.static(__dirname + '/client'));

serv.listen(8001);
console.log("Server started.");

var SOCKET_LIST = {};

var io = require('socket.io')(serv,{});
io.sockets.on('connection', function(socket){
    socket.id = Math.random();
    socket.x = 0;
    socket.y = 0;
    socket.number = "" + Math.floor(10 * Math.random());
    SOCKET_LIST[socket.id] = socket;

    socket.on('disconnect',function(){
        delete SOCKET_LIST[socket.id];
    });

});

setInterval(function(){
    var pack = [];
    for(var i in SOCKET_LIST){
        var socket = SOCKET_LIST[i];
        socket.x++;
        socket.y++;
        pack.push({
            x:socket.x,
            y:socket.y,
            number:socket.number
        });
    }
    for(var i in SOCKET_LIST){
        var socket = SOCKET_LIST[i];
        socket.emit('newPositions',pack);
    }

},1000/25);
</code>```

client/index.html;

```<code><canvas id="ctx" width="500" height="500" style="border:1px solid #000000;"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>

<script>
    var ctx = document.getElementById("ctx").getContext("2d");
    ctx.font = '30px Arial';

    var socket = io.connect('http://www.myurl:8001', {path: "/socket.io"});

    socket.on('newPositions',function(data){
        ctx.clearRect(0,0,500,500);
        for(var i = 0 ; i < data.length; i++)
            ctx.fillText(data[i].number,data[i].x,data[i].y);
    });
</script>
</code>```

It works fine as the code is but only over http. I need this to work over SSL

i need this line to work when its https;

```<code>var socket = io.connect('https://www.myurl:8001', {path: "/socket.io"});
</code>```

How is this possible?

any help is greatly appreciated.

答:
Ok this was a bit embarrasing... the actual problem i had was because of the following.

If you can follow this lol...

So in dreamhost they allow you to run apache and serve content in the usual way. there is a /public folder for this. fairly standard stuff.
Because i'm trying to branch out into being able to use sockets (please don't lecture me on using sockets with PHP... let it go!) So i was using dreamhost which allows a person to proxy a node.js app through a port. eg. port xxxx ends up at thewebsiteurl/whateverfolderyouchoose/

ok so in my node.js i was using express. now in express you can specify routing really easy. For some bizzare reason, i cant be bothered to actually find out why, if you know please enlighten me... i had to put double forward slash in the routing, like so "//whateverroute/". all the examples i was learning from use a single forward slash. eg "/whateverroute/" but that didn't work. if you know why, please tell us. So before i figured this out, i couldn't actually route anything correctly, hence having to use the url with the port number at the end. of course that messes up the https. example, https://www.theurl.com:xxxx wasnt secure,  because the node.js app wasnt running an https res req server. Actually i did set up the https node server and thought that was the solution to the problem at first.

So the solution to this bizarre problem was the node.js routing. ofcourse its stupidly complicated because, hey life's like that when your learning from google and not someone who actually knows your exact setup.

What turns out to be funny is, i cant stand node.js. I can see the benefit to using it. But it seems like alot of ball ache for something as simple as what i'm making. Also i have now discovered phone/gap so php actually is ok for what i want to do. Ok so i'm hitting the server way to many times with AJAX requests but it's coping with a few hundred users right now and when it hits the 10'000  mark when the site probably wont work very well, i should be making enough to get a real node.js programmer in to learn from.... hopefully.

I do appreciate the help tho guys.

Body:
This is frustrating me like crazy!

i'm using a proxy so that any requests that go to myurl/APP/ are answered by node.js at myurl:8001

I now need this to work over https. easy.... i thought.

i have Apache serving up the old version from the public folder. That is stand alone, and when i'm done building this, it will just be removed. but for now needs to remain in tact and accessible. Lets encrypt is setup on this. and https://myurl works fine, showing content from the public folder of course.

if i go to https://myurl:8001 then chrome says "site can't be reached". If i go to http://myurl:8001 it works fine. I think this is because https default port is 443. I have VPS not dedicated so i don't think i can alter that. And surely if i did alter the ssl port then it wont work for the public folder??

i'll show you the basics of whats going on;

app.js;

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

app.get('/',function(req, res) {
    res.sendFile(__dirname + '/client/index.html');
});
app.use('/client',express.static(__dirname + '/client'));

serv.listen(8001);
console.log("Server started.");

var SOCKET_LIST = {};

var io = require('socket.io')(serv,{});
io.sockets.on('connection', function(socket){
    socket.id = Math.random();
    socket.x = 0;
    socket.y = 0;
    socket.number = "" + Math.floor(10 * Math.random());
    SOCKET_LIST[socket.id] = socket;

    socket.on('disconnect',function(){
        delete SOCKET_LIST[socket.id];
    });

});

setInterval(function(){
    var pack = [];
    for(var i in SOCKET_LIST){
        var socket = SOCKET_LIST[i];
        socket.x++;
        socket.y++;
        pack.push({
            x:socket.x,
            y:socket.y,
            number:socket.number
        });
    }
    for(var i in SOCKET_LIST){
        var socket = SOCKET_LIST[i];
        socket.emit('newPositions',pack);
    }

},1000/25);

client/index.html;

<canvas id="ctx" width="500" height="500" style="border:1px solid #000000;"></canvas>

It works fine as the code is but only over http. I need this to work over SSL

i need this line to work when its https;

var socket = io.connect('https://www.myurl:8001', {path: "/socket.io"});

How is this possible?

any help is greatly appreciated.


问:
How to save a Button drawable when rotating screen
I just read this: Saving Android Activity state using Save Instance State

this: Android - Open resource from @drawable String

My situation is: I have a Button background set when pressing it to be green with

```<code>button.setBackgroundResource(R.drawable.greenbutton);
</code>```

How can I store this information with onSaveInstanceState and onRestoreInstanceState?

I tried: How to maintain a button style and click state after screen rotation? and worked but maybe there is something better than a three-nested-if-conditionals procedure? I mean I have to do this for 4+ Button and I think it a lot of work for just a simple cause :)

Thank you

EDIT: this is the code so far

```<code>package com.example.android.testbutton;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.change);
    }

    Button button;
    Boolean click;

    public void changeColor(View view) {
        click = true;
        button.setBackgroundResource(R.drawable.greenbutton);
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {

        // Save UI state changes to the savedInstanceState.
        // This bundle will be passed to onCreate if the process is
        // killed and restarted.

        savedInstanceState.putBoolean("buttonClicked", click);
        // etc.

        super.onSaveInstanceState(savedInstanceState);
    }

//onRestoreInstanceState

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {

        super.onRestoreInstanceState(savedInstanceState);

        // Restore UI state from the savedInstanceState.
        // This bundle has also been passed to onCreate.

        Boolean firstAnswer = savedInstanceState.getBoolean("buttonClicked");
        {
            if (savedInstanceState != null) {
                if (savedInstanceState.containsKey("buttonClicked")) {
                    if (savedInstanceState.getBoolean("buttonClicked"))
                        button.setBackgroundResource(R.drawable.greenbutton);

                    //some codes to make the button becomes clicked.
                }
            }
        }
    }
}
</code>```

答:
set a variable on your activity too, and then save that and restore it with your state.

```<code>public class MyActivity extends Activity {

public static final String KEY_BUTTON_IS_GREEN = "isGreen";
boolean buttonIsGreen;

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putBoolean(KEY_BUTTON_IS_GREEN, buttonIsGreen);
    super.onSaveInstanceState(outState);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    buttonIsGreen = savedInstanceState.getBoolean(KEY_BUTTON_IS_GREEN, false);
    if (buttonIsGreen){
        // find the button and set it green.
    }
}
</code>```

you'll need to add to your method that sets the button green and also set your variable = true if the button is green.

Body:
I just read this: Saving Android Activity state using Save Instance State

this: Android - Open resource from @drawable String

My situation is: I have a Button background set when pressing it to be green with

button.setBackgroundResource(R.drawable.greenbutton);

How can I store this information with onSaveInstanceState and onRestoreInstanceState?

I tried: How to maintain a button style and click state after screen rotation? and worked but maybe there is something better than a three-nested-if-conditionals procedure? I mean I have to do this for 4+ Button and I think it a lot of work for just a simple cause :)

Thank you

EDIT: this is the code so far

package com.example.android.testbutton;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.change);
    }

    Button button;
    Boolean click;

    public void changeColor(View view) {
        click = true;
        button.setBackgroundResource(R.drawable.greenbutton);
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {

        // Save UI state changes to the savedInstanceState.
        // This bundle will be passed to onCreate if the process is
        // killed and restarted.

        savedInstanceState.putBoolean("buttonClicked", click);
        // etc.

        super.onSaveInstanceState(savedInstanceState);
    }

//onRestoreInstanceState

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {

        super.onRestoreInstanceState(savedInstanceState);

        // Restore UI state from the savedInstanceState.
        // This bundle has also been passed to onCreate.

        Boolean firstAnswer = savedInstanceState.getBoolean("buttonClicked");
        {
            if (savedInstanceState != null) {
                if (savedInstanceState.containsKey("buttonClicked")) {
                    if (savedInstanceState.getBoolean("buttonClicked"))
                        button.setBackgroundResource(R.drawable.greenbutton);

                    //some codes to make the button becomes clicked.
                }
            }
        }
    }
}

Body:
set a variable on your activity too, and then save that and restore it with your state.

public class MyActivity extends Activity {

public static final String KEY_BUTTON_IS_GREEN = "isGreen";
boolean buttonIsGreen;

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putBoolean(KEY_BUTTON_IS_GREEN, buttonIsGreen);
    super.onSaveInstanceState(outState);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    buttonIsGreen = savedInstanceState.getBoolean(KEY_BUTTON_IS_GREEN, false);
    if (buttonIsGreen){
        // find the button and set it green.
    }
}

you'll need to add to your method that sets the button green and also set your variable = true if the button is green.


问:
Safari and bootstrap 4 flexbox error
Bootstrap 4 - Safari Version 10.1.2 display:table; and display:table-cell; vertical-align:center; not working on a 100% height div.

```<code><div class="test-slider">
    <div class="slide">
        <div class="row no-gutters">
            <div class="col-12 col-xs-12 col-sm-12 col-md-7 col-lg-7">
                <img src=""/>
            </div>
            <div class="col-12 col-xs-12 col-sm-12 col-md-5 col-lg-5">
                 <div style="display:table; height:100%;">
                        <div style="display:table-cell; vertical-align: middle;">
                        <h2>Test center</h2>
                        <p>Should be centered</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

If I render in chrome the height is inherited from the .test-slider class that has a fixed height whilst in safari it takes the contents height rather than filling the height of the div. Any ideas? I am using slick slider.

答:
Well, currently I have Safari 11.0.1, but if I set the below stlye, it does center the text vertically to me.

```<code>.test-slider .row {
    height: 500px;
}
</code>```

Setting the height only to .test-slider is not enough, since the children do not know that they should fill in that height. The 100% height set on the "table" is calculated from the height of it's parent, the .col-md-5 div. Which, in your case does not know about the height of the .test-slider.

Other than that, please note that col-12 col-xs-12 col-sm-12 col-md-7 col-lg-7 is totally equivalent to simply writing col-md-7. The same stands for col-md-5 of course.

Also, instead of using tables, I would recommend to use the flexbox utility classes already available in Bootstrap. That makes the markup lighter. This is an example:

.test-slider .row {
    height: 300px;
}

.test {
    background-color: lightgray;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="test-slider">
    <div class="slide">
        <div class="row no-gutters">
            <div class="col-md-7">
                <img src=""/>
            </div>
            <div class="test col-md-5 d-flex align-items-center">
                <div>
                    <h2 class="mb-0">Test center</h2>
                    <p class="mb-0">Should be centered</p>
                </div>
            </div>
        </div>
    </div>
</div>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css"></code>```

Title: Safari and bootstrap 4 flexbox error

Body:
Bootstrap 4 - Safari Version 10.1.2 display:table; and display:table-cell; vertical-align:center; not working on a 100% height div.

Test center

Should be centered

If I render in chrome the height is inherited from the .test-slider class that has a fixed height whilst in safari it takes the contents height rather than filling the height of the div. Any ideas? I am using slick slider.

Body:
Well, currently I have Safari 11.0.1, but if I set the below stlye, it does center the text vertically to me.

.test-slider .row {
    height: 500px;
}

Setting the height only to .test-slider is not enough, since the children do not know that they should fill in that height. The 100% height set on the "table" is calculated from the height of it's parent, the .col-md-5 div. Which, in your case does not know about the height of the .test-slider.

Other than that, please note that col-12 col-xs-12 col-sm-12 col-md-7 col-lg-7 is totally equivalent to simply writing col-md-7. The same stands for col-md-5 of course.

Also, instead of using tables, I would recommend to use the flexbox utility classes already available in Bootstrap. That makes the markup lighter. This is an example:

.test-slider .row {
    height: 300px;
}

.test {
    background-color: lightgray;
}

<div class="test-slider">
    <div class="slide">
        <div class="row no-gutters">
            <div class="col-md-7">
                <img src=""/>
            </div>
            <div class="test col-md-5 d-flex align-items-center">
                <div>
                    <h2 class="mb-0">Test center</h2>
                    <p class="mb-0">Should be centered</p>
                </div>
            </div>
        </div>
    </div>
</div>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">


问:
SIMD Program slow runtime
I'm starting with SIMD programming but i don't know what to do at this moment. I'm trying to diminish runtime but its doing it the other way.

This is my basic code:
https://codepaste.net/a8ut89

```<code>void blurr2(double * u, double * r) {

    int i;
    double dos[2] = { 2.0, 2.0 };

    for (i = 0; i < SIZE - 1; i++) {
        r[i] = u[i] + u[i + 1];
    }
}
</code>```

blurr2: 0.43s

```<code>int contarNegativos(double * u) {

    int i;
    int contador = 0;

    for (i = 0; i < SIZE; i++) {
        if (u[i] < 0) {
            contador++;
        }
    }
    return contador;
}
</code>```

negativeCount: 1.38s

```<code>void ord(double * v, double * u, double * r) {

    int i;

    for (i = 0; i < SIZE; i += 2) {
        r[i] = *(__int64*)&(v[i]) | *(__int64*)&(u[i]);
    }
}
</code>```

ord: 0.33

And this is my SIMD code:

https://codepaste.net/fbg1g5

```<code>void blurr2(double * u, double * r) {

    __m128d rp2;
    __m128d rdos;
    __m128d rr;
    int i;
    int sizeAux = SIZE % 2 == 1 ? SIZE : SIZE - 1;
    double dos[2] = { 2.0, 2.0 };

    rdos = *(__m128d*)dos;

    for (i = 0; i < sizeAux; i += 2) {
        rp2 = *(__m128d*)&u[i + 1];
        rr = _mm_add_pd(*(__m128d*)&u[i], rp2);
        *((__m128d*)&r[i]) = _mm_div_pd(rr, rdos);
    }
}
</code>```

blurr2: 0.42s

```<code>int contarNegativos(double * u) {

    __m128d rcero;
    __m128d rr;
    int i;
    double cero[2] = { 0.0, 0.0 };
    int contador = 0;

    rcero = *(__m128d*)cero;

    for (i = 0; i < SIZE; i += 2) {
        rr = _mm_cmplt_pd(*(__m128d*)&u[i], rcero);
        if (((__int64 *)&rr)[0]) {
            contador++;
        };
        if (((__int64 *)&rr)[1]) {
            contador++;
        };
    }
    return contador;
}
</code>```

negativeCount: 1.42s

```<code>void ord(double * v, double * u, double * r) {

    __m128d rr;
    int i;

    for (i = 0; i < SIZE; i += 2) {
        *((__m128d*)&r[i]) = _mm_or_pd(*(__m128d*)&v[i], *(__m128d*)&u[i]);
    }
}
</code>```

ord: 0.35s

**Differents solutions.

Can you explain me what i'm doing wrong? I'm a bit lost...

答:
Use _mm_loadu_pd instead of pointer-casting and dereferencing a __m128d.  Your code is guaranteed to segfault on gcc/clang where __m128d is assumed to be aligned.

blurr2: multiply by 0.5 instead of dividing by 2.  It will be much faster.  (I commented the same thing on a question with the exact same code in the last day or two, was that also you?)

negativeCount: _mm_castpd_si128 the compare result to integer, and accumulate it with _mm_sub_epi64.  (The bit pattern is all-zero or all-one, i.e. 2's complement 0 / -1).

```<code>#include <immintrin.h>
#include <stdint.h>

static const size_t SIZE = 1024;

uint64_t countNegative(double * u) {
    __m128i counts = _mm_setzero_si128();
    for (size_t i = 0; i < SIZE; i += 2) {
        __m128d cmp = _mm_cmplt_pd(_mm_loadu_pd(&u[i]), _mm_setzero_pd());
        counts = _mm_sub_epi64(counts, _mm_castpd_si128(cmp));
    }

    //return counts[0] + counts[1];  // GNU C only, and less efficient
    // horizontal sum
    __m128i hi64  = _mm_shuffle_epi32(counts, _MM_SHUFFLE(1, 0, 3, 2));
    counts = _mm_add_epi64(counts, hi64);

    uint64_t scalarcount = _mm_cvtsi128_si64(counts);
    return scalarcount;
}
</code>```

To learn more about efficient vector horizontal sums, see Fastest way to do horizontal float vector sum on x86.  But the first rule is to do it outside the loop.

(source + asm on the Godbolt compiler explorer)

From MSVC (which I'm guessing you're using, or you'd get segfaults from *(__m128d*)foo), the inner loop is:

```<code>$LL4@countNegat:
    movups   xmm0, XMMWORD PTR [rcx]
    lea      rcx, QWORD PTR [rcx+16]
    cmpltpd xmm0, xmm2
    psubq    xmm1, xmm0
    sub      rax, 1
    jne      SHORT $LL4@countNegat
</code>```

It could maybe go faster with unrolling (and maybe two vector accumulators), but this is fairly good and might go close to 1.25 clocks per 16 bytes on Sandybridge/Haswell.  (Bottleneck on 5 fused-domain uops).

Your version was actually unpacking to integer inside the inner loop!  And if you were using MSVC -Ox, it was actually branching instead of using a branchless compare + conditional add.  I'm surprised it wasn't slower than the scalar version.

Also, (int64_t *)&rr violates strict aliasing.  char* can alias anything, but it's not safe to cast other pointers onto SIMD vectors and expect it to work.  If it does, you got lucky.  Compilers usually generate similar code for that or intrinsics, and usually not worse for proper intrinsics.

Title: SIMD Program slow runtime

Body:
I'm starting with SIMD programming but i don't know what to do at this moment. I'm trying to diminish runtime but its doing it the other way.

This is my basic code:
https://codepaste.net/a8ut89

void blurr2(double * u, double * r) {

    int i;
    double dos[2] = { 2.0, 2.0 };

    for (i = 0; i < SIZE - 1; i++) {
        r[i] = u[i] + u[i + 1];
    }
}

blurr2: 0.43s

int contarNegativos(double * u) {

    int i;
    int contador = 0;

    for (i = 0; i < SIZE; i++) {
        if (u[i] < 0) {
            contador++;
        }
    }
    return contador;
}

negativeCount: 1.38s

void ord(double * v, double * u, double * r) {

    int i;

    for (i = 0; i < SIZE; i += 2) {
        r[i] = *(__int64*)&(v[i]) | *(__int64*)&(u[i]);
    }
}

ord: 0.33

And this is my SIMD code:

https://codepaste.net/fbg1g5

void blurr2(double * u, double * r) {

    __m128d rp2;
    __m128d rdos;
    __m128d rr;
    int i;
    int sizeAux = SIZE % 2 == 1 ? SIZE : SIZE - 1;
    double dos[2] = { 2.0, 2.0 };

    rdos = *(__m128d*)dos;

    for (i = 0; i < sizeAux; i += 2) {
        rp2 = *(__m128d*)&u[i + 1];
        rr = _mm_add_pd(*(__m128d*)&u[i], rp2);
        *((__m128d*)&r[i]) = _mm_div_pd(rr, rdos);
    }
}

blurr2: 0.42s

int contarNegativos(double * u) {

    __m128d rcero;
    __m128d rr;
    int i;
    double cero[2] = { 0.0, 0.0 };
    int contador = 0;

    rcero = *(__m128d*)cero;

    for (i = 0; i < SIZE; i += 2) {
        rr = _mm_cmplt_pd(*(__m128d*)&u[i], rcero);
        if (((__int64 *)&rr)[0]) {
            contador++;
        };
        if (((__int64 *)&rr)[1]) {
            contador++;
        };
    }
    return contador;
}

negativeCount: 1.42s

void ord(double * v, double * u, double * r) {

    __m128d rr;
    int i;

    for (i = 0; i < SIZE; i += 2) {
        *((__m128d*)&r[i]) = _mm_or_pd(*(__m128d*)&v[i], *(__m128d*)&u[i]);
    }
}

ord: 0.35s

**Differents solutions.

Can you explain me what i'm doing wrong? I'm a bit lost...

Body:
Use _mm_loadu_pd instead of pointer-casting and dereferencing a __m128d.  Your code is guaranteed to segfault on gcc/clang where __m128d is assumed to be aligned.

blurr2: multiply by 0.5 instead of dividing by 2.  It will be much faster.  (I commented the same thing on a question with the exact same code in the last day or two, was that also you?)

negativeCount: _mm_castpd_si128 the compare result to integer, and accumulate it with _mm_sub_epi64.  (The bit pattern is all-zero or all-one, i.e. 2's complement 0 / -1).

#include <immintrin.h>
#include <stdint.h>

static const size_t SIZE = 1024;

uint64_t countNegative(double * u) {
    __m128i counts = _mm_setzero_si128();
    for (size_t i = 0; i < SIZE; i += 2) {
        __m128d cmp = _mm_cmplt_pd(_mm_loadu_pd(&u[i]), _mm_setzero_pd());
        counts = _mm_sub_epi64(counts, _mm_castpd_si128(cmp));
    }

    //return counts[0] + counts[1];  // GNU C only, and less efficient
    // horizontal sum
    __m128i hi64  = _mm_shuffle_epi32(counts, _MM_SHUFFLE(1, 0, 3, 2));
    counts = _mm_add_epi64(counts, hi64);

    uint64_t scalarcount = _mm_cvtsi128_si64(counts);
    return scalarcount;
}

To learn more about efficient vector horizontal sums, see Fastest way to do horizontal float vector sum on x86.  But the first rule is to do it outside the loop.

(<a href="https://gcc.godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(j:1,source:'%23include+%3Cimmintrin.h%3E%0A%23include+%3Cstdint.h%3E%0A%0Astatic+const+size_t+SIZE+%3D+1024%3B%0A%0Auint64_t+countNegative(double+*+u)+%7B%0A++++__m128i+counts+%3D+_mm_setzero_si128()%3B%0A++++for+(size_t+i+%3D+0%3B+i+%3C+SIZE%3B+i+%2B%3D+2)+%7B%0A++++++++__m128d+cmp+%3D+_mm_cmplt_pd(_mm_loadu_pd(%26u%5Bi%5D),+_mm_setzero_pd())%3B%0A++++++++counts+%3D+_mm_sub_epi64(counts,+_mm_castpd_si128(cmp))%3B%0A++++%7D%0A%0A++++//return+counts%5B0%5D+%2B+counts%5B1%5D%3B++//+GNU+C+only,+and+less+efficient%0A++++//+horizontal+sum%0A++++__m128i+hi64++%3D+_mm_shuffle_epi32(counts,+_MM_SHUFFLE(1,+0,+3,+2))%3B%0A++++counts+%3D+_mm_add_epi64(counts,+hi64)%3B%0A%0A++++uint64_t+scalarcount+%3D+_mm_cvtsi128_si64(counts)%3B%0A++++return+scalarcount%3B%0A%7D%0A%0A%0Aint+contarNegativos(double+*+u)+%7B%0A%0A++++__m128d+rcero%3B%0A++++__m128d+rr%3B%0A++++int+i%3B%0A++++double+cero%5B2%5D+%3D+%7B+0.0,+0.0+%7D%3B%0A++++int+contador+%3D+0%3B%0A++++%0A++++rcero+%3D+*(__m128d*)cero%3B%0A++++%0A++++for+(i+%3D+0%3B+i+%3C+SIZE%3B+i+%2B%3D+2)+%7B%0A++++++++rr+%3D+_mm_cmplt_pd(*(__m128d*)%26u%5Bi%5D,+rcero)%3B%0A++++++++if+(((int64_t+*)%26rr)%5B0%5D)+%7B%0A++++++++++++contador%2B%2B%3B%0A++++++++%7D%3B%0A++++++++if+(((int64_t+*)%26rr)%5B1%5D)+%7B%0A++++++++++++contador%2B%2B%3B%0A++++++++%7D%3B%0A++++%7D%0A++++return+contador%3B%0A%7D%0A'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:38.35151961172038,l:'4',m:100,n:'0',o:'',s:0,t:'0'),(g:!((h:compiler,i:(compiler:cl19_64,filters:(b:'0',binary:'1',commentOnly:'0',demangle:'0',directives:'0',execute:'1',intel:'0',trim:'1'),fontScale:0.8957951999999999,libs:!(),options:'-Ox',source:1),l:'5',n:'0',o:'x86-64+MSVC+19+2017+RTW+(Editor+%231,+Compiler+%232)',t:'0')),k:37.58093266434423,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((h:compiler,i:(compiler:g72,filters:(b:'0',binary:'1',commentOnly:'0',demangle:'0',directives:'0',execute:'1',intel:'0',trim:'1'),fontScale:0.8957951999999999,libs:!(),options:'-xc+-O3+-Wall',source:1),l:'5',n:'0',o:'x86-64+gcc+7.2+(Editor+%231,+Compiler+%231)',t:'0')),header:(),k:24.067547723935387,l:'4',n:'0',o:'',s:0,t:'0')),l:'2',n:'0',o:'',t:'0')),version:4" rel="nofollow noreferrer">source + asm on the Godbolt compiler explorer)

From MSVC (which I'm guessing you're using, or you'd get segfaults from *(__m128d*)foo), the inner loop is:

$LL4@countNegat:
    movups   xmm0, XMMWORD PTR [rcx]
    lea      rcx, QWORD PTR [rcx+16]
    cmpltpd xmm0, xmm2
    psubq    xmm1, xmm0
    sub      rax, 1
    jne      SHORT $LL4@countNegat

It could maybe go faster with unrolling (and maybe two vector accumulators), but this is fairly good and might go close to 1.25 clocks per 16 bytes on Sandybridge/Haswell.  (Bottleneck on 5 fused-domain uops).

Your version was actually unpacking to integer inside the inner loop!  And if you were using MSVC -Ox, it was actually branching instead of using a branchless compare + conditional add.  I'm surprised it wasn't slower than the scalar version.

Also, (int64_t *)&rr violates strict aliasing.  char* can alias anything, but it's not safe to cast other pointers onto SIMD vectors and expect it to work.  If it does, you got lucky.  Compilers usually generate similar code for that or intrinsics, and usually not worse for proper intrinsics.


问:
Child Theme not overriding Parent CSS
I've created a child theme of the Renovation theme. In the child's theme folder I have a "style.css" and a "functions.php" file. My style.css looks like this:

```<code>/*
Theme Name: Renovation Child
Theme URI: http://renovation.thememove.com/
Author: ThemeMove
Author URI: http://thememove.com/
Version: 2.0.4
Template: tm-renovation
*/

/*
 * @charset "UTF-8";
*/

.vc_custom_1438936121266 {
    margin-bottom: 70px!important;
    padding-top: 65px!important;
    padding-bottom: 35px!important;
}
</code>```

My functions.php looks like this:

```<code><?php
// Exit if accessed directly
if ( !defined( 'ABSPATH' ) ) exit;

// BEGIN ENQUEUE PARENT ACTION

if ( !function_exists( 'renovation_enqueue_scripts' ) ):
    function renovation_enqueue_scripts() {
        wp_enqueue_style( 'renovation-child-style', trailingslashit( get_stylesheet_directory_uri() ) . 'style.css' );
    }
endif;
add_action( 'wp_enqueue_scripts', 'renovation_enqueue_scripts' );

// END ENQUEUE PARENT ACTION
</code>```

Unsing the inspector I see that the parent css is being loaded first and it looks like this:

```<code>.vc_custom_1438936121266 {
    margin-bottom: 70px!important;
    padding-top: 30px!important;
    padding-bottom: 35px!important;
}
</code>```

My CSS is being loaded after the parent CSS and it looks like this, except it's all crossed out:

```<code>.vc_custom_1438936121266 {
    margin-bottom: 70px!important;
    padding-top: 65px!important;           <-- MY CHANGE
    padding-bottom: 35px!important;
}
</code>```

I've read alot of threads about specificity, and I noticed that my css and the parent css are identical, except for the "padding-top" change I made. Since the child is loaded last, I expected my css to take precedence, but it's not. My css is crossed out in the inspector and the parent is being used.

This doesn't seem right to me, and I was hoping that someone could clarify my understanding of the parent/child relationship and help me fix this problem. Thank you.

答: if you are only going to override one element and not apply this to multiple it might be best to use an id instead of a class. The id is always overwrites a class.</p>

Title: Child Theme not overriding Parent CSS

Body:
I've created a child theme of the Renovation theme. In the child's theme folder I have a "style.css" and a "functions.php" file. My style.css looks like this:

/*
Theme Name: Renovation Child
Theme URI: http://renovation.thememove.com/
Author: ThemeMove
Author URI: http://thememove.com/
Version: 2.0.4
Template: tm-renovation
*/

/*
 * @charset "UTF-8";
*/

.vc_custom_1438936121266 {
    margin-bottom: 70px!important;
    padding-top: 65px!important;
    padding-bottom: 35px!important;
}

My functions.php looks like this:

<?php
// Exit if accessed directly
if ( !defined( 'ABSPATH' ) ) exit;

// BEGIN ENQUEUE PARENT ACTION

if ( !function_exists( 'renovation_enqueue_scripts' ) ):
    function renovation_enqueue_scripts() {
        wp_enqueue_style( 'renovation-child-style', trailingslashit( get_stylesheet_directory_uri() ) . 'style.css' );
    }
endif;
add_action( 'wp_enqueue_scripts', 'renovation_enqueue_scripts' );

// END ENQUEUE PARENT ACTION

Unsing the inspector I see that the parent css is being loaded first and it looks like this:

.vc_custom_1438936121266 {
    margin-bottom: 70px!important;
    padding-top: 30px!important;
    padding-bottom: 35px!important;
}

My CSS is being loaded after the parent CSS and it looks like this, except it's all crossed out:

.vc_custom_1438936121266 {
    margin-bottom: 70px!important;
    padding-top: 65px!important;           <-- MY CHANGE
    padding-bottom: 35px!important;
}

I've read alot of threads about specificity, and I noticed that my css and the parent css are identical, except for the "padding-top" change I made. Since the child is loaded last, I expected my css to take precedence, but it's not. My css is crossed out in the inspector and the parent is being used.

This doesn't seem right to me, and I was hoping that someone could clarify my understanding of the parent/child relationship and help me fix this problem. Thank you.


问:
Problems with texture deformation in OpenGL ES 1.1 on quad made out of triangle strips
I'm using triangle strips to create a quad. The problem is when I try to paint it using a rectangular texture that I want to have evenly interpolated over the shape.

As long as the shape is a rectangle or an affine transform of a rectangle, I'll have two identical triangles that build the shape and everything goes well. But with arbitrary shapes, the triangles have different shapes and a distortion naturally occurs along the common edge of the triangles.

```<code>   _____       ______       _____
  |     |     /     /       \   /
  |_____|    /_____/         \_/

    Ok         Ok           Not Ok
</code>```

I imagine it would be fairly straightforward to work around this with custom shaders in ES 2.0, but how do I achieve it in ES 1.1?

答:
Put bluntly, the hardware can only do linear interpolation of texture coordinates if you don't provide it with perspective/depth information.

Linear interpolation does not allow to properly handle the case that causes you problems.

To have a proper interpolation on you edge, you have to introduce perspective information in your quad.

You should find more information in this NVidia whitepaper : Projective Texture Mapping.

Body:
I'm using triangle strips to create a quad. The problem is when I try to paint it using a rectangular texture that I want to have evenly interpolated over the shape.

As long as the shape is a rectangle or an affine transform of a rectangle, I'll have two identical triangles that build the shape and everything goes well. But with arbitrary shapes, the triangles have different shapes and a distortion naturally occurs along the common edge of the triangles.

   _____       ______       _____
  |     |     /     /       \   /
  |_____|    /_____/         \_/

    Ok         Ok           Not Ok

I imagine it would be fairly straightforward to work around this with custom shaders in ES 2.0, but how do I achieve it in ES 1.1?


问:
Algorithm/C++ code for extracting patterns from text file

A file containing a large switch case is given as input. The cases are incremented from 0 to n. Each case has some specific elements (a, b, etc).

Output will consist of three things: a vector containing all the unique elements, a second vector containing the first position (case) where the element is used and lastly, a third vector containing the periodicity of the elements.

Input will be a text file like this:

```<code>//standard comment useful for parsing file
switch something
{

case 0:
    a;
    b;
    c;
    break;

case 1:
    break;

case 2:
    a;
    break;

case 3:
    d;
    break;

case 4:
    a;
    d;
    break;

}
</code>```

Output:

Vector 1 will be {a, b, c, d}

Vector 2 will be {0, 0, 0, 3}

Vector 3 will be {2, 0, 0, 1} *Note: 0 is for non-cyclic elements, 2 is the
    difference of the cases between two consecutive appearances of the element
    (case 4 - case 2 = case 2 - case 0 = 2). This difference will repeat itself
    so we only need to compare whichever two consecutive appearances.

Also, this algorithm should work for very large files numbering hundreds of thousands of lines of code.

答:
Considering that format of the text file is consistent and is exactly how it is described in the question, one way to do it would be by reading lines and parsing as you go. I am sure there is a better way of doing it, but without getting too involved, here is what I've got:

```<code>#include <fstream>
#include <sstream>
#include <string>
#include <vector>

int main()
{
    std::ifstream inputFile("cases.txt");

    std::vector<char> uniqueChars;
    std::vector<int> firstCase;
    std::vector<int> periodicity;

    std::string inputLine;
    while (std::getline(inputFile, inputLine, '\n'))
    {
        if (inputLine.compare(0, 5, "case ") == 0)
        {
            int caseN = std::stoi(inputLine.substr(5));
            while (std::getline(inputFile, inputLine, '\n') && inputLine != "    break;")
            {
                std::istringstream iss(inputLine);
                char c, semi;
                while (iss >> c >> semi)
                {
                    auto found = std::find(uniqueChars.begin(), uniqueChars.end(), c);
                    if (found == uniqueChars.end())
                    {
                        uniqueChars.push_back(c);
                        firstCase.push_back(caseN);
                        periodicity.push_back(0);
                    }
                    else
                    {
                        size_t charPos = std::distance(uniqueChars.begin(), found);
                        if (periodicity[charPos] == 0)
                        {
                            periodicity[charPos] = std::abs(caseN - firstCase[charPos]);
                        }
                    }
                }
            }
        }
    }

    // print

    for (auto c : uniqueChars)
        std::cout << c << " ";
    std::cout << std::endl;

    for (auto i : firstCase)
        std::cout << i << " ";
    std::cout << std::endl;

    for (auto p : periodicity)
        std::cout << p << " ";
    std::cout << std::endl;

    return 0;
}
</code>```

Output for the sample file:

Body:
A file containing a large switch case is given as input. The cases are incremented from 0 to n. Each case has some specific elements (a, b, etc).

Output will consist of three things: a vector containing all the unique elements, a second vector containing the first position (case) where the element is used and lastly, a third vector containing the periodicity of the elements.

Input will be a text file like this:

//standard comment useful for parsing file
switch something
{

case 0:
    a;
    b;
    c;
    break;

case 1:
    break;

case 2:
    a;
    break;

case 3:
    d;
    break;

case 4:
    a;
    d;
    break;

}

Output:

Vector 1 will be {a, b, c, d}

Vector 2 will be {0, 0, 0, 3}

Vector 3 will be {2, 0, 0, 1} *Note: 0 is for non-cyclic elements, 2 is the
    difference of the cases between two consecutive appearances of the element
    (case 4 - case 2 = case 2 - case 0 = 2). This difference will repeat itself
    so we only need to compare whichever two consecutive appearances.

Also, this algorithm should work for very large files numbering hundreds of thousands of lines of code.

Body:
Considering that format of the text file is consistent and is exactly how it is described in the question, one way to do it would be by reading lines and parsing as you go. I am sure there is a better way of doing it, but without getting too involved, here is what I've got:

#include <fstream>
#include <sstream>
#include <string>
#include <vector>

int main()
{
    std::ifstream inputFile("cases.txt");

    std::vector<char> uniqueChars;
    std::vector<int> firstCase;
    std::vector<int> periodicity;

    std::string inputLine;
    while (std::getline(inputFile, inputLine, '\n'))
    {
        if (inputLine.compare(0, 5, "case ") == 0)
        {
            int caseN = std::stoi(inputLine.substr(5));
            while (std::getline(inputFile, inputLine, '\n') && inputLine != "    break;")
            {
                std::istringstream iss(inputLine);
                char c, semi;
                while (iss >> c >> semi)
                {
                    auto found = std::find(uniqueChars.begin(), uniqueChars.end(), c);
                    if (found == uniqueChars.end())
                    {
                        uniqueChars.push_back(c);
                        firstCase.push_back(caseN);
                        periodicity.push_back(0);
                    }
                    else
                    {
                        size_t charPos = std::distance(uniqueChars.begin(), found);
                        if (periodicity[charPos] == 0)
                        {
                            periodicity[charPos] = std::abs(caseN - firstCase[charPos]);
                        }
                    }
                }
            }
        }
    }

    // print

    for (auto c : uniqueChars)
        std::cout << c << " ";
    std::cout << std::endl;

    for (auto i : firstCase)
        std::cout << i << " ";
    std::cout << std::endl;

    for (auto p : periodicity)
        std::cout << p << " ";
    std::cout << std::endl;

    return 0;
}

Output for the sample file:


问:
Passing a class object to different functions
really I am looking for a bit of advice as to the best way to achieve something. I am working in pure PHP without any libraries.  I have a simple Config class

```<code><?php

class Config
{
   //define my constants
}
</code>```

This class is in a folder outside of the web root.  Within my web root, I have a simple PHP file that will act as a script, no need for it to be a class.  Instead of showing bit by bit, I will just show my thought process

```<code><?php

require __DIR__ . "/../config/Config.php";

$config = new Config();
execute($config);

function execute($config) {
    $textFile = $this->obtainTextFile($config);
    $transferFile = $this->transferFile($config, $textFile);
}

function obtainTextFile($config) {
    //connect to database and write results to text file

    return $textFile;  //path to the generated file
}

function transferFile($config, $textFile) {
    //return whether the file was successfully SFTP
}
</code>```

So firstly I require the config file.  I then create a $config object which I pass to the execute function.  The execute function essentially acts as the entry point.  Now this function has the object, it needs to pass it to another couple of functions that need the object.  To me this seems a bit strange because if it was a class, I could just refer to the class variable.

Is this the normal way of doing things when not using a class?  Is there a better way of doing this whereby I dont have to keep passing the object around, without using a class?

Any advice appreciated

答:
How about that, create two classes. One is the Config and the other one is the Application that does all the magic.
And then you have one script file that uses both classes.

Application class

```<code>class Application {

    /** @var Config **/
    private $config;

    public function __construct(Config $config) {
        $this->config = $config;
    }

    public function execute() {
        $this->transferFile($this->obtainTextFile());
    }

    private function obtainTextFile() {
        //connect to database and write results to text file

        return $textFile;  //path to the generated file
    }

    private function transferFile($textFile) {
        //return whether the file was successfully SFTP
    }
}
</code>```

Script file

```<code><?php
require __DIR__ . "/../config/Config.php";
require __DIR__ . "/../Application.php";

$config = new Config();
$app = new Application($config);
$app->execute();
</code>```

Body:
really I am looking for a bit of advice as to the best way to achieve something. I am working in pure PHP without any libraries.  I have a simple Config class

<?php

class Config
{
   //define my constants
}

This class is in a folder outside of the web root.  Within my web root, I have a simple PHP file that will act as a script, no need for it to be a class.  Instead of showing bit by bit, I will just show my thought process

<?php

require __DIR__ . "/../config/Config.php";

$config = new Config();
execute($config);

function execute($config) {
    $textFile = $this->obtainTextFile($config);
    $transferFile = $this->transferFile($config, $textFile);
}

function obtainTextFile($config) {
    //connect to database and write results to text file

    return $textFile;  //path to the generated file
}

function transferFile($config, $textFile) {
    //return whether the file was successfully SFTP
}

So firstly I require the config file.  I then create a $config object which I pass to the execute function.  The execute function essentially acts as the entry point.  Now this function has the object, it needs to pass it to another couple of functions that need the object.  To me this seems a bit strange because if it was a class, I could just refer to the class variable.

Is this the normal way of doing things when not using a class?  Is there a better way of doing this whereby I dont have to keep passing the object around, without using a class?

Any advice appreciated

Body:
How about that, create two classes. One is the Config and the other one is the Application that does all the magic.
And then you have one script file that uses both classes.

Application class

class Application {

    /** @var Config **/
    private $config;

    public function __construct(Config $config) {
        $this->config = $config;
    }

    public function execute() {
        $this->transferFile($this->obtainTextFile());
    }

    private function obtainTextFile() {
        //connect to database and write results to text file

        return $textFile;  //path to the generated file
    }

    private function transferFile($textFile) {
        //return whether the file was successfully SFTP
    }
}

Script file

<?php
require __DIR__ . "/../config/Config.php";
require __DIR__ . "/../Application.php";

$config = new Config();
$app = new Application($config);
$app->execute();


问:
Provide arguments with a method
Is there a way in Java to create a method that would return the list of parameters of another method such that I am able to call

```<code>anotherMethod(method())
</code>```

where anotherMethod has arbitrary arguments like

```<code>public void anotherMethod(int a, int b, String c)
</code>```

And what is if the types stay the same, like with

```<code>public int add(int a, int b, int c)
</code>```

If there is no such way, how could I model the list of parameters such that it would work? Is it a List or an array or something else?

答:
Varargs

Java has a built-in feature to denote a variable length of arguments. It is called varargs (documentation) (variable arguments) and it only works if the type stays the same. The syntax for a method is like this:

```<code>public int add(int... values)
</code>```

Note the int... values which denotes varargs. A caller can now call the method like

```<code>add(null)        // Passing null
add(values)      // Passing an int[]
add()            // No arguments
add(a)           // One int
add(a, b)        // Two ints
add(a, b, c)     // Three ints
add(a, b, c, d)  // Four ints
...
</code>```

Note the three special cases null, int[] and empty.

What Java does is it will convert the arguments into an array. So inside the method values will be a regular int[]. You could thus implement the method like

```<code>public int add(int... values) {
    int sum = 0;
    for (int value : values) {
        sum += value;
    }
    return sum;
}
</code>```

If you, as a caller, want to pass the return value of a function you just need to make sure that it returns an array like int[]. So the following would work:

```<code>public int[] valueProvider() {
    int[] values = ...

    return values;
}
</code>```

and then call it like

```<code>int sum = add(valueProvider());
</code>```

Collection, Iterable and Stream

Besides that, if you don't want to use varargs or arrays, you can use Collections (documentation). A collection may be a List or a Set and so on. For example you could declare

```<code>public int add(Collection<Integer> values)
</code>```

and feed it like

```<code>Collection<Integer> values = new ArrayList<>();
values.add(1);
values.add(2);
int sum = add(values);
</code>```

An Iterable<Integer>, in contrast to Collection<Integer> would even be more flexible.

Using a Stream (documentation) would also work like a charm and is probably one of the most flexible variants since the source of a stream could be anything and nearly anything of the standard library supports a stream representation.

Changing type

Now note that what you searched for in the beginning, a method that is able to feed arbitrary arguments, is not possible in Java.

The main problem is that the types may change, so you may have a method like

```<code>public void doSomething(int first, String second, File third)
</code>```

and you won't be able to feed the method with varargs, Collections or any of the presented methods.

In that case you will need a wrapper class like

```<code>public class DoSomethingArguments {
    private int mFirst;
    private String mSecond;
    private File mThird;

    public DoSomethingArguments(int first; String second, File third) {
        this.mFirst = first;
        this.mSecond = second;
        this.mThird = third;
    }

    // Some getters
}
</code>```

(or a generic tuple class, a triple in this case)

But then you would need to change the method to

```<code>public void doSomething(DoSomethingArguments arguments)
</code>```

what is probably not what you wanted since you probably intended to not change the signature of doSomething.

But unfortunately there is no way to feed a method like this in such a way.

Title: Provide arguments with a method

Body:
Is there a way in Java to create a method that would return the list of parameters of another method such that I am able to call

anotherMethod(method())

where anotherMethod has arbitrary arguments like

public void anotherMethod(int a, int b, String c)

And what is if the types stay the same, like with

public int add(int a, int b, int c)

If there is no such way, how could I model the list of parameters such that it would work? Is it a List or an array or something else?

Body:
Varargs

Java has a built-in feature to denote a variable length of arguments. It is called varargs (documentation) (variable arguments) and it only works if the type stays the same. The syntax for a method is like this:

public int add(int... values)

Note the int... values which denotes varargs. A caller can now call the method like

add(null)        // Passing null
add(values)      // Passing an int[]
add()            // No arguments
add(a)           // One int
add(a, b)        // Two ints
add(a, b, c)     // Three ints
add(a, b, c, d)  // Four ints
...

Note the three special cases null, int[] and empty.

What Java does is it will convert the arguments into an array. So inside the method values will be a regular int[]. You could thus implement the method like

public int add(int... values) {
    int sum = 0;
    for (int value : values) {
        sum += value;
    }
    return sum;
}

If you, as a caller, want to pass the return value of a function you just need to make sure that it returns an array like int[]. So the following would work:

public int[] valueProvider() {
    int[] values = ...

    return values;
}

and then call it like

int sum = add(valueProvider());

Collection, Iterable and Stream

Besides that, if you don't want to use varargs or arrays, you can use Collections (documentation). A collection may be a List or a Set and so on. For example you could declare

public int add(Collection<Integer> values)

and feed it like

Collection<Integer> values = new ArrayList<>();
values.add(1);
values.add(2);
int sum = add(values);

An Iterable<Integer>, in contrast to Collection<Integer> would even be more flexible.

Using a Stream (documentation) would also work like a charm and is probably one of the most flexible variants since the source of a stream could be anything and nearly anything of the standard library supports a stream representation.

Changing type

Now note that what you searched for in the beginning, a method that is able to feed arbitrary arguments, is not possible in Java.

The main problem is that the types may change, so you may have a method like

public void doSomething(int first, String second, File third)

and you won't be able to feed the method with varargs, Collections or any of the presented methods.

In that case you will need a wrapper class like

public class DoSomethingArguments {
    private int mFirst;
    private String mSecond;
    private File mThird;

    public DoSomethingArguments(int first; String second, File third) {
        this.mFirst = first;
        this.mSecond = second;
        this.mThird = third;
    }

    // Some getters
}

(or a generic tuple class, a triple in this case)

But then you would need to change the method to

public void doSomething(DoSomethingArguments arguments)

what is probably not what you wanted since you probably intended to not change the signature of doSomething.

But unfortunately there is no way to feed a method like this in such a way.


问:
How to make a simple JSONP asynchronous request in Angular 2?
I'm trying to convert the following Angular 1 code to Angular 2:

```<code>$http.jsonp('https://accounts.google.com/logout');
</code>```

It needs to be a JSONP request to skip the CORS policy issue.

答:
In Angular 4.3 and up you should use HttpClientModule because the JsonpModule is deprecated.

Import HttpClientModule and HttpClientJsonpModule into your module.

Inject HttpClient into your service.

Pass the callback key as the second argument for the jsonp method.

app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
// Import relevant http modules
import { HttpClientModule, HttpClientJsonpModule } from '@angular/common/http';

import { AppComponent } from './app.component';

import { ExampleService } from './example.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    // Import relevant http modules
    HttpClientModule,
    HttpClientJsonpModule
  ],
  providers: [ExampleService],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

example.service.ts

```<code>import { Injectable } from '@angular/core';
// Import HttpClient class
import { HttpClient } from '@angular/common/http';

@Injectable()
export class ExampleService {

  // Inject HttpClient class
  constructor(private http: HttpClient) { }

  getData() {
    const url = "https://archive.org/index.php?output=json&callback=archive";

    // Pass the key for your callback (in this case 'callback')
    // as the second argument to the jsonp method
    return this.http.jsonp(url, 'callback');
  }
}
</code>```

Body:
I'm trying to convert the following Angular 1 code to Angular 2:

$http.jsonp('https://accounts.google.com/logout');

It needs to be a JSONP request to skip the CORS policy issue.

Body:
In Angular 4.3 and up you should use HttpClientModule because the JsonpModule is deprecated.

Import HttpClientModule and HttpClientJsonpModule into your module.

Inject HttpClient into your service.

Pass the callback key as the second argument for the jsonp method.

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
// Import relevant http modules
import { HttpClientModule, HttpClientJsonpModule } from '@angular/common/http';

import { AppComponent } from './app.component';

import { ExampleService } from './example.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    // Import relevant http modules
    HttpClientModule,
    HttpClientJsonpModule
  ],
  providers: [ExampleService],
  bootstrap: [AppComponent]
})
export class AppModule { }

example.service.ts

import { Injectable } from '@angular/core';
// Import HttpClient class
import { HttpClient } from '@angular/common/http';

@Injectable()
export class ExampleService {

  // Inject HttpClient class
  constructor(private http: HttpClient) { }

  getData() {
    const url = "https://archive.org/index.php?output=json&callback=archive";

    // Pass the key for your callback (in this case 'callback')
    // as the second argument to the jsonp method
    return this.http.jsonp(url, 'callback');
  }
}


问:
d3 selection confusion with exit() and remove()
So I'm working through some d3 tutorials and learning a bit about why things work the way they do, and I've run into a peculiar instance of selection not behaving as expected. So I'm wondering if anyone can explain this to me.

```<code>var sales = [
    { product: 'Hoodie',  count: 7 },
    { product: 'Jacket',  count: 6 },
    { product: 'Snuggie', count: 9 },
];

var rects = svg.selectAll('rect')
  .data(sales).enter();

var maxCount = d3.max(sales, function(d, i) {
    return d.count;
});
var x = d3.scaleLinear()
    .range([0, 300])
    .domain([0, maxCount]);
var y = d3.scaleBand()
    .rangeRound([0, 75])
    .domain(sales.map(function(d, i) {
        return d.product;
    }));

rects.append('rect')
    .attr('x', x(0))
    .attr('y', function(d, i) {
        return y(d.product);
    })
    .attr('height', y.bandwidth())
    .attr('width', function(d, i) {
        return x(d.count);
    });
</code>```

This all works good and fine, generates 3 horizontal bars that correspond to the data in sales, but here's where I'm seeing the ambiguity:

```<code>sales.pop();

rects.data(sales).exit().remove();
</code>```

The last line is supposed to remove the bar that was popped, from the visual but it doesn't work. I think that there must be something going on with the d3 selection that I'm missing, because this does work:

```<code>d3.selectAll('rect').data(sales).exit().remove();
</code>```

Also when I break out the first one that doesn't work, it does appear to be selecting the correct element on exit, but just doesn't seem to be removing it. Anyway if anyone can explain what's going on here that would be very helpful, thanks!

Note: using d3 v4

答: rects is already a d3 selection, so you only need rects.exit().remove()

Body:
So I'm working through some d3 tutorials and learning a bit about why things work the way they do, and I've run into a peculiar instance of selection not behaving as expected. So I'm wondering if anyone can explain this to me.

var sales = [
    { product: 'Hoodie',  count: 7 },
    { product: 'Jacket',  count: 6 },
    { product: 'Snuggie', count: 9 },
];

var rects = svg.selectAll('rect')
  .data(sales).enter();

var maxCount = d3.max(sales, function(d, i) {
    return d.count;
});
var x = d3.scaleLinear()
    .range([0, 300])
    .domain([0, maxCount]);
var y = d3.scaleBand()
    .rangeRound([0, 75])
    .domain(sales.map(function(d, i) {
        return d.product;
    }));

rects.append('rect')
    .attr('x', x(0))
    .attr('y', function(d, i) {
        return y(d.product);
    })
    .attr('height', y.bandwidth())
    .attr('width', function(d, i) {
        return x(d.count);
    });

This all works good and fine, generates 3 horizontal bars that correspond to the data in sales, but here's where I'm seeing the ambiguity:

sales.pop();

rects.data(sales).exit().remove();

The last line is supposed to remove the bar that was popped, from the visual but it doesn't work. I think that there must be something going on with the d3 selection that I'm missing, because this does work:

d3.selectAll('rect').data(sales).exit().remove();

Also when I break out the first one that doesn't work, it does appear to be selecting the correct element on exit, but just doesn't seem to be removing it. Anyway if anyone can explain what's going on here that would be very helpful, thanks!

Note: using d3 v4


问:
A = ( ( b <= c) || (b > c) )
I'm working on simple logical quiz lately and faced with this. Been working around integer but i can't find the answer. What would be the value of A if Given A = ( ( b <= c) || (b > c) )?</p>

<p>*Edit : I'm sorry for the unclear description. The condition that asked is like this </p>

```<code>    If ( var1 <= 10 || var1 > 10){
        print "wrong"
    }else{
        print "true"
</code>```

答: In C, your code will always give 'false', since the first condition covers all possible values of var1.</p>

Title: A = ( ( b <= c) || (b > c) )

Body:
I'm working on simple logical quiz lately and faced with this. Been working around integer but i can't find the answer. What would be the value of A if Given A = ( ( b <= c) || (b > c) )?

*Edit : I'm sorry for the unclear description. The condition that asked is like this

    If ( var1 <= 10 || var1 > 10){
        print "wrong"
    }else{
        print "true"


问:
Adding a video url to an sms or mms using twilio
I can add a youtube link to a new message's body like below and it will send the message, but adding the link to the media_url gives an mime type error. Idk how I feel about this method.

```<code>client = Twilio::REST::Client.new 'Axx', 'xx'
message = client.messages.create
    from: '+1xxxxxxxxxx',
    to: 'xxxxxxxxxx',
    body: "Learning to send SMS you are. \n https://www.youtube.com/watch?v=aBlKPLeLU_s"
</code>```

Is there a better way of adding youtube links to a new message?

EDIT

Adding the url to the media_url key like

```<code>client = Twilio::REST::Client.new 'Axx', 'xx'
message = client.messages.create
    from: '+1xxxxxxxxxx',
    to: 'xxxxxxxxxx',
    body: "Learning to send SMS you are."
    media_url: "https://www.youtube.com/watch?v=aBlKPLeLU_s"
</code>```

Gives the error from twilio

Msg=Attempt+to+retrieve+MediaUrl+returned+an+unsupported+Content-Type.&EmailNotification=false&contentType=text%2Fhtml&LogLevel=ERROR&url=https%3A%2F%2Fwww.youtube.com%2Fembed%2FaBlKPLeLU_s

答:
Twilio developer evangelist here.

When you send media via an MMS message with Twilio, you need to link to the media file itself. In your example, you are just linking to the YouTube page, not to the video file.

Some other things to note. The list of MIME types that Twilio will accept is listed here. Also, Twilio will not send media messages that are over 5MB total size.

Hope this helps.

Body:
I can add a youtube link to a new message's body like below and it will send the message, but adding the link to the media_url gives an mime type error. Idk how I feel about this method.

client = Twilio::REST::Client.new 'Axx', 'xx'
message = client.messages.create
    from: '+1xxxxxxxxxx',
    to: 'xxxxxxxxxx',
    body: "Learning to send SMS you are. \n https://www.youtube.com/watch?v=aBlKPLeLU_s"

Is there a better way of adding youtube links to a new message?

EDIT

Adding the url to the media_url key like

client = Twilio::REST::Client.new 'Axx', 'xx'
message = client.messages.create
    from: '+1xxxxxxxxxx',
    to: 'xxxxxxxxxx',
    body: "Learning to send SMS you are."
    media_url: "https://www.youtube.com/watch?v=aBlKPLeLU_s"

Gives the error from twilio

Msg=Attempt+to+retrieve+MediaUrl+returned+an+unsupported+Content-Type.&EmailNotification=false&contentType=text%2Fhtml&LogLevel=ERROR&url=https%3A%2F%2Fwww.youtube.com%2Fembed%2FaBlKPLeLU_s


问:
Neural Network simulator in FPGA?
To learn FPGA programming, I plan to code up a simple Neural Network in FPGA (since it's massively parallel; it's one of the few things where an FPGA implementation might have a chance of being faster than a CPU implementation).

Though I'm familiar with C programming (10+ years). I'm not so sure with FPGA development stuff. Can you provide a guided list of what I should do / learn / buy?

Thanks!

答:
I would recommend looking into xilinx high-level synthesis, especially if you are coming from a C background. It abstracts away the technical details in using a hdl so the designer can focus on the algorithmic implementation.

The are restriction in the type of C code you can write. For example, you can't use dynamically sized data structures, as that would infer dynamically sized hardware.

Title: Neural Network simulator in FPGA?


问:
Where to get php_mcrypt.dll for PHP 7.2?
I need Mcrypt extension for my CMS to work. It's not distributed with PHP windows build, and I can't find any compiles. I downloaded sources, and compile php with key --enable-mcrypt=shared, but it show error:

```<code>Enabling extension ext\standard
Checking for mcrypt.h ...  <not found>
Checking for mcrypt.h ...  <not found>
WARNING: mcrypt not enabled; libraries and headers not found
</code>```

Here is config.w32:

```<code>// $Id$
// vim:ft=javascript

ARG_WITH("mcrypt", "mcrypt support", "no");

if (PHP_MCRYPT != "no") {

    if (CHECK_HEADER_ADD_INCLUDE('mcrypt.h', 'CFLAGS_MCRYPT') &&
            CHECK_LIB('libmcrypt_a.lib;libmcrypt.lib', 'mcrypt') &&
            CHECK_LIB('Advapi32.lib', 'mcrypt')
            ) {

        EXTENSION('mcrypt', 'mcrypt.c mcrypt_filter.c', false, "/DZEND_ENABLE_STATIC_TSRMLS_CACHE=1");
        AC_DEFINE('HAVE_LIBMCRYPT', 1);
        AC_DEFINE('HAVE_LIBMCRYPT24', 1);
    } else {
        WARNING("mcrypt not enabled; libraries and headers not found");
    }
}
</code>```

It looks for mcrypt.h, but in which folder? And it is not in the mcrypt package file downloaded from PECL. Unfortunately I'm not familiar with C++ compiling

答:
http://php.net/manual/en/migration71.deprecated.php

The mcrypt extension has been abandonware for nearly a decade now, and was also fairly complex to use. It has therefore been deprecated in favour of OpenSSL, where it will be removed from the core and into PECL in PHP 7.2.

Body:
I need Mcrypt extension for my CMS to work. It's not distributed with PHP windows build, and I can't find any compiles. I downloaded sources, and compile php with key --enable-mcrypt=shared, but it show error:

Enabling extension ext\standard
Checking for mcrypt.h ...  <not found>
Checking for mcrypt.h ...  <not found>
WARNING: mcrypt not enabled; libraries and headers not found

Here is config.w32:

// $Id$
// vim:ft=javascript

ARG_WITH("mcrypt", "mcrypt support", "no");

if (PHP_MCRYPT != "no") {

    if (CHECK_HEADER_ADD_INCLUDE('mcrypt.h', 'CFLAGS_MCRYPT') &&
            CHECK_LIB('libmcrypt_a.lib;libmcrypt.lib', 'mcrypt') &&
            CHECK_LIB('Advapi32.lib', 'mcrypt')
            ) {

        EXTENSION('mcrypt', 'mcrypt.c mcrypt_filter.c', false, "/DZEND_ENABLE_STATIC_TSRMLS_CACHE=1");
        AC_DEFINE('HAVE_LIBMCRYPT', 1);
        AC_DEFINE('HAVE_LIBMCRYPT24', 1);
    } else {
        WARNING("mcrypt not enabled; libraries and headers not found");
    }
}

It looks for mcrypt.h, but in which folder? And it is not in the mcrypt package file downloaded from PECL. Unfortunately I'm not familiar with C++ compiling


问:
Cannot use ssh to clone git repository with Concourse

We are using a Concourse instance deployed to and EC2 instance using docker-compose, as outlined here.

Things are mostly working well. However, we can't seem to clone git resources using SSH. We get this error:

```<code>resource script '/opt/resource/check []' failed: exit status 128

stderr:
Identity added: /tmp/git-resource-private-key (/tmp/git-resource-private-key)
Cloning into '/tmp/git-resource-repo-cache'...
fatal: Could not read from remote repository.

Please make sure you have the correct access rights and the repository exists.
</code>```

We've used Concourse in the past, so we're reasonably sure that we have the resource configured correctly, but I've attached a sample as well.

```<code>- name: vision_build
  type: git
  source:
    private_key: |
      -----BEGIN RSA PRIVATE KEY-----
      ***************************
      -----END RSA PRIVATE KEY-----
    uri: git@github.com:someorg/someapp.git
</code>```

Cloning works correctly with username/password authentication, but we'd like to use read only deploy keys.

Another symptom that we are seeing is the inability to hijack our jobs. It's unclear if they are connected, but seems possible given that they both have to do with SSH. Hijack comes back with this message:

```<code>error: websocket: bad handshake
</code>```

答:
Upgrading my comment to an answer.

is your private key's corresponding puiblic key configured on the github side under someorg/someapp ? Either as a deployment key, or as a user in your org dedicated to that activity? Sounds to me like you didn't add access for the key in github.

Body:
We are using a Concourse instance deployed to and EC2 instance using docker-compose, as outlined here.

Things are mostly working well. However, we can't seem to clone git resources using SSH. We get this error:

resource script '/opt/resource/check []' failed: exit status 128

stderr:
Identity added: /tmp/git-resource-private-key (/tmp/git-resource-private-key)
Cloning into '/tmp/git-resource-repo-cache'...
fatal: Could not read from remote repository.

Please make sure you have the correct access rights and the repository exists.

We've used Concourse in the past, so we're reasonably sure that we have the resource configured correctly, but I've attached a sample as well.

- name: vision_build
  type: git
  source:
    private_key: |
      -----BEGIN RSA PRIVATE KEY-----
      ***************************
      -----END RSA PRIVATE KEY-----
    uri: git@github.com:someorg/someapp.git

Cloning works correctly with username/password authentication, but we'd like to use read only deploy keys.

Another symptom that we are seeing is the inability to hijack our jobs. It's unclear if they are connected, but seems possible given that they both have to do with SSH. Hijack comes back with this message:

error: websocket: bad handshake


问:
Pass an Angular variable to the directive
I'm building a pagination in angular, here is my directive:

```<code>app.directive('postsGenreLink', function() {
    return {
        restrict: 'EA',
        templateUrl: myLocalized.partials + 'posts-genre-link.html',
        controller: ['$scope', '$element', '$routeParams', function($scope, $element, $routeParams) {
            var currentGenrePage = (!$routeParams.page) ? 1 : parseInt($routeParams.page),
                linkPrefix = (!$routeParams.slug) ? 'page/' : 'genre/' + $routeParams.slug + '/page/';

            $scope.postsGenreLink = {
                prevLink: linkPrefix + (currentGenrePage - 1),
                hopLink: linkPrefix + (currentGenrePage),
                nextLink: linkPrefix + (currentGenrePage + 1),
                sep: (!$element.attr('sep')) ? '|' : $element.attr('sep'),
                prevLabel: (!$element.attr('prev-label')) ? 'Previous Page' : $element.attr('prev-label'),
                nextLabel: (!$element.attr('next-label')) ? 'Next Page' : $element.attr('next-label'),
                hopLabel: (!$element.attr('Jump')) ? 'Jump' : $element.attr('Jump')
            };
        }]
    };
});
</code>```

and here is the posts-genre-link.html I want to display:

```<code><nav aria-label="...">
  <ul class="pagination pt-3">
    <li class="page-item" ng-class="{'disabled' : currentGenrePage == 1}">
      <a class="page-link" href="{{postsGenreLink.prevLink}}">Previous</a>
    </li>
    <li ng-repeat="i in [].constructor(totalPages) track by $index" class="page-item" ng-class="{'active' : currentGenrePage == $index + 1}"><a class="page-link" href="{{postsGenreLink.hopLink}}">{{$index + 1}}</a></li>

    <li class="page-item" ng-class="{'disabled' : currentGenrePage >= totalPages}">
      <a class="page-link" href="{{postsGenreLink.nextLink}}">Next</a>
    </li>
  </ul>
</nav>
</code>```

It works great except for the href inside the ng-repeat. I would like that hopLink is the value of linkPrefix plus $index + 1. How can I achieve this?

答:
I've fixed this changing the hopLink to hopLink: linkPrefix, and inside the href I did: href="{{postsGenreLink.hopLink}}{{$index + 1}}".
This was way more simple than passing the $index value to the controller through a ng-click.

Body:
I'm building a pagination in angular, here is my directive:

app.directive('postsGenreLink', function() {
    return {
        restrict: 'EA',
        templateUrl: myLocalized.partials + 'posts-genre-link.html',
        controller: ['$scope', '$element', '$routeParams', function($scope, $element, $routeParams) {
            var currentGenrePage = (!$routeParams.page) ? 1 : parseInt($routeParams.page),
                linkPrefix = (!$routeParams.slug) ? 'page/' : 'genre/' + $routeParams.slug + '/page/';

            $scope.postsGenreLink = {
                prevLink: linkPrefix + (currentGenrePage - 1),
                hopLink: linkPrefix + (currentGenrePage),
                nextLink: linkPrefix + (currentGenrePage + 1),
                sep: (!$element.attr('sep')) ? '|' : $element.attr('sep'),
                prevLabel: (!$element.attr('prev-label')) ? 'Previous Page' : $element.attr('prev-label'),
                nextLabel: (!$element.attr('next-label')) ? 'Next Page' : $element.attr('next-label'),
                hopLabel: (!$element.attr('Jump')) ? 'Jump' : $element.attr('Jump')
            };
        }]
    };
});

and here is the posts-genre-link.html I want to display:

      Previous

{{$index + 1}}

= totalPages}">
      Next

It works great except for the href inside the ng-repeat. I would like that hopLink is the value of linkPrefix plus $index + 1. How can I achieve this?