text:
Q: How could I modify the formula of A star algorithm to what I need below? I'm working on A star algorithm. I'm trying to build a trajectory for drone depending on A star. I have implemented my code below. I need to consider the height of obstacles and modify my equation :
F= G+H to F=H+G+E
E: represents the elevation of obstacles. We have the drone is flying in a specific altitude over a map, if the obstacle was very high(it means its risk very high) the distance between the obstacle and the drone is too close, so the drone will prefer to fly over the short obstacle. If the obstacle higher than the altitude of the drone, it will turn around.
I added an elevation map with random height generation and drone_altitude, but it doesn't work with me. Could I get some assistance, please?.
The A-star Python Code:
import numpy

grid = [[0, 1, 0, 0, 0, 0],
        [0, 1, 0, 0, 0, 0],
        [0, 1, 0, 0, 0, 0],
        [0, 1, 0, 0, 0, 0],
        [0, 0, 0, 0, 1, 0]]

heuristic = [[9, 8, 7, 6, 5, 4],
             [8, 7, 6, 5, 4, 3],
             [7, 6, 5, 4, 3, 2],
             [6, 5, 4, 3, 2, 1],
             [5, 4, 3, 2, 1, 0]]

init = [0,0]
goal = [len(grid)-1,len(grid[0])-1]

delta = [[-1 , 0],   #up
         [ 0 ,-1],   #left
         [ 1 , 0],   #down
         [ 0 , 1]]   #right

delta_name = ['^','<','V','>']  #The name of above actions

cost = 1   #Each step costs you one

drone_height = 60

def search():
    #open list elements are of the type [g,x,y]

    closed = [[0 for row in range(len(grid[0]))] for col in range(len(grid))]

    action = [[-1 for row in range(len(grid[0]))] for col in range(len(grid))]
    #We initialize the starting location as checked
    closed[init[0]][init[1]] = 1

    expand=[[-1 for row in range(len(grid[0]))] for col in range(len(grid))]

    elvation = numpy.random.randint(0, 100+1, size=(5, 6))
    print(elvation)
    # we assigned the cordinates and g value
    x = init[0]
    y = init[1]
    g = 0
    h = heuristic[x][y]
    e = elvation[x][y]
    f = g + h + e

    #our open list will contain our initial value
    open = [[f, g, h, x, y]]

    found  = False   #flag that is set when search complete
    resign = False   #Flag set if we can't find expand
    count = 0

    #print('initial open list:')
    #for i in range(len(open)):
            #print('  ', open[i])
    #print('----')

    while found is False and resign is False:

        #Check if we still have elements in the open list
        if len(open) == 0:    #If our open list is empty, there is nothing to expand.
            resign = True
            print('Fail')
            print('############# Search terminated without success')
            print()
        else:
            #if there is still elements on our list
            #remove node from list
            open.sort()
            open.reverse()          #reverse the list
            next = open.pop()
            #print('list item')
            #print('next')

            x = next[3]
            y = next[4]
            g = next[1]

            expand[x][y] = count
            count+=1

            #Check if we are done
            if x == goal[0] and y == goal[1]:
                found = True
                print(next) #The three elements above this "if".
                print('############## Search is success')
                print()

            else:
                #expand winning element and add to new open list
                for i in range(len(delta)):
                    x2 = x + delta[i][0]
                    y2 = y + delta[i][1]

                    #if x2 and y2 falls into the grid
                    if x2 >= 0 and x2 < len(grid) and y2 >=0 and y2 <= len(grid[0])-1:
                        #if x2 and y2 not checked yet and there is not obstacles
                        if closed[x2][y2] == 0 and grid[x2][y2] == 0 and e < drone_height:
                            g2 = g + cost             #we increment the cose
                            h2 = heuristic[x2][y2]
                            e2 = elvation[x2][y2]
                            f2 = g2 + h2 + e2

                            open.append([f2,g2,h2,x2,y2])   #we add them to our open list
                            #print('append list item')
                            #print([g2,x2,y2])
                            #Then we check them to never expand again
                            closed[x2][y2] = 1
                            action[x2][y2] = i
    for i in range(len(expand)):
        print(expand[i])
    print()
    policy=[[' ' for row in range(len(grid[0]))] for col in range(len(grid))]
    x=goal[0]
    y=goal[1]
    policy[x][y]='*'
    while x !=init[0] or y !=init[1]:
        x2=x-delta[action[x][y]][0]
        y2=y-delta[action[x][y]][1]
        policy[x2][y2]= delta_name[action[x][y]]
        x=x2
        y=y2
    for i in range(len(policy)):
        print(policy[i])

search()


text:
Q: Why my backgroundWorker does not work? i tried to implement a backgroudworker but is does not work in second thread and the form still loking and e can't call the event of my button 2, someone tell me why its happening?
my code:
public Form1()
{
  InitializeComponent();
  backgroundWorker1.DoWork +=
    new DoWorkEventHandler(backgroundWorker1_DoWork);
  backgroundWorker1.ProgressChanged +=
    new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
  backgroundWorker1.RunWorkerCompleted +=
    new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
  backgroundWorker1.WorkerReportsProgress = true;
}

void backgroundWorker1_RunWorkerCompleted(object sender,
  RunWorkerCompletedEventArgs e)
{
  MessageBox.Show("Work is done");
}

void backgroundWorker1_ProgressChanged(object sender,
  ProgressChangedEventArgs e)
{
  this.progressBar1.Value = e.ProgressPercentage;
}

void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
  ThreadProc();
}

private void button1_Click(object sender, EventArgs e)
{
  backgroundWorker1.RunWorkerAsync();
}

void ThreadProc()
{
  //simulate work
  for (int i = 0; i < 100000; ++i)
  {
    int total = i / 1000;
    backgroundWorker1.ReportProgress(total);
  }
}

private void button2_Click(object sender, EventArgs e)
{
  MessageBox.Show("Another thread");
}

tks;

A: Looks like you may be reporting progress back to the form at a very rapid rate which would result in the form getting locked up.
Try changing the ThreadProc method like so... for demonstration purposes only, of course:
void ThreadProc ()
{
    //simulate work
    for ( int i = 0; i < 100000; ++i )
    {
        Thread.Sleep( 1 ); // this should allow the form to breath a little :)
        int total = i / 1000;
        backgroundWorker1.ReportProgress( total );
    }
}

A: I think that because you are continuously updating your UI thread by letting your thread report progress 100000 times, your UI thread is too occupied to accept the click event from Button 2. I would lower the amount of reports significantly and see if this has any affect.
Since ProgressBar.Value is an int, this should make no differenece:
  for (int i = 0; i < 100; i++)
  {
    backgroundWorker1.ReportProgress(i);
  }

A: For starters I can say that the background worker will be on another thread allocated from the ThreadPool.  It is still possible to lock up your UI though, because when you call the ProgressChanged or RunWorkerCompleted events, they are marshalled back onto the UI thread.  Only the DoWork event works on another ThreadPool thread.
If you are not on the UI thread, you cannot access UI elements, like button 2 without a little extra work.  To access UI elements from other threads, you need to use Control.Invoke to marshal the call back to the UI thread.

redpajama_set_name: RedPajamaStackExchange


text:
Q: getopt not working correctly when run from unix command line I wrote (copied and pasted from Google and simplified) a C program to use getopt to print out the values of the arguments passed in from the Unix command line.
From Unix command line:
./myprog -a 0 -b 1 -c 2

My C code is:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    int i;

    while ((i = getopt(argc, argv, "abc")) != -1) {
        switch (i) {
            case 'a':
               printf("A = %s\n", optarg);
               break;

            case 'b':
               printf("B = %s\n", optarg);
               break;

            case 'c':
               printf("C = %s\n", optarg);
               break;

            default:
                break;
        }
    }

    return 0;
}

I want to program to print out each of the values passed e.g.
A = 0
B = 1
C = 2

However it is not printing out anything at all.

A: You forget about ":" after any option with argument. If you will change one line
while ((i = getopt(argc, argv, "a:b:c:")) != -1) {

you will get working variant.
Read properly man 3 getopt, it said about third argument of getopt that
… optstring is a string containing the legitimate option characters.  If such a character is followed by  a  colon,  the  option  requires  an  argument,  so
       getopt()  places a pointer to the following text in the same argv-element, or the text of the following argv-element, in optarg.  Two colons mean an option
       takes an optional arg; if there is text in the current argv-element (i.e., in the same word as the option name itself, for example, "-oarg"),  then  it  is
       returned  in optarg, otherwise optarg is set to zero. …


text:
Q: What would be best approach to work with two hashes of arrays in this scenario? What would be the best approach to process these two hashes of arrays?  The 1st data set contains xml data and 2nd is from csv file, the idea is to check if the filename from 2nd dataset is in the first one and if so, calculate the delay in file delivery.  Im not sure how to best produce the workable hash that i can work with (or change existing ones to have filenames as their keys or maybe somehow merge these together), any feedback would be greatly appreciated
dataset 1 (xml data):
$VAR1 = [
      {
        'StartTimestamp' => 1478146371,
        'EndTimestamp' => 1478149167,
        'FileName' => 'a3_file_20161024.req',
        'Stage' => 'SentUserResponse'
      },
      {
        'StartTimestamp' => 1478146375,
        'EndTimestamp' => 1478149907,
        'FileName' => 'a2_file_20161024.req',
        'Stage' => 'SentUserResponse'
      },
      {
        'StartTimestamp' => 1478161030,
        'EndTimestamp' => 1478161234,
        'FileName' => 'file_DEX_0.req',
        'Stage' => 'SentUserResponse'
      },

Data Set 2 from csv file:
$VAR1 = [
      {
        'FileName' => 'a3_file_20161024.req',
        'ExpectedTime' => '20:04:07'
      },
      {
        'FileName' => 'a2_file_20161024.req',
        'ExpectedTime' => '20:14:39'
      },
      {
        'FileName' => 'file_DEX_0.req',
        'ExpectedTime' => '20:48:40'
      },

code used:
sub Demo {
my $api_ref = GetData($apicall);
my $csvdata = ReadDataFile();
print Dumper($api_ref);
print "-------------------------*********--------------************------------------\n";
print Dumper ($csvdata);
print "#####################\n";

}
sub ReadDataFile {
    my $parser = Text::CSV::Simple->new;
    $parser->field_map(qw/FileName ExpectedTime/);
    my @csv_data = $parser->read_file($datafile);
    return \@csv_data;

}
sub GetData {
my ($xml) = @_;
my @api_data;
my %request;
my $t = XML::Twig->new(
    twig_handlers => {
        '//UserRequest' => sub {
            push @api_data, {%request} if %request;
            %request = ();
            $_->purge;    # free memory
        },
        '//UserRequest/HomeFileName' => sub {
            $request{FileName} = $_->trimmed_text;
        },
        '//UserRequest/Stage' => sub {
            $request{Stage} = $_->trimmed_text;
        },
        '//UserRequest/StartTimestamp' => sub {
            $request{StartTimestamp} = str2time(substr($_->trimmed_text, -8));
        },
        '//UserRequest/EndTimestamp' => sub {
            $request{EndTimestamp} = str2time(substr($_->trimmed_text, -8));
        },
    },
);
$t->xparse($xml);
$t->purge;
return \@api_data;

}

A: I am assuming, that you can map the elements of the first array to the elements of the second array by comparing by the filename and that relation is an 1:1 relation, I would perform the following steps:

*

*Sort the lists by filename or generate a index hash

*Combine both sets into a single array of hashs or use the index to process through your data set

*Do whatever you need to do with the data sets

Just a litte example:
#!/usr/bin/env perl

use strict;
use warnings;

my $api_ref = [
    {
        'StartTimestamp' => 1478146371,
        'EndTimestamp'   => 1478149167,
        'FileName'       => 'a3_file_20161024.req',
        'Stage'          => 'SentUserResponse'
    },
    {
        'StartTimestamp' => 1478146375,
        'EndTimestamp'   => 1478149907,
        'FileName'       => 'a2_file_20161024.req',
        'Stage'          => 'SentUserResponse'
    },
    {
        'StartTimestamp' => 1478161030,
        'EndTimestamp'   => 1478161234,
        'FileName'       => 'file_DEX_0.req',
        'Stage'          => 'SentUserResponse'
    }
];

my $csvdata = [
    {
        'FileName'     => 'a3_file_20161024.req',
        'ExpectedTime' => '20:04:07'
    },
    {
        'FileName'     => 'a2_file_20161024.req',
        'ExpectedTime' => '20:14:39'
    },
    {
        'FileName'     => 'file_DEX_0.req',
        'ExpectedTime' => '20:48:40'
    }
];

# generate the index
my %index = ();

for ( my $i = 0 ; $i < @{$api_ref} ; $i++ ) {
    $index{ $api_ref->[$i]{FileName} }{api_idx} = $i;
}

for ( my $i = 0 ; $i < @{$csvdata} ; $i++ ) {
    $index{ $csvdata->[$i]{FileName} }{csv_idx} = $i;
}

# filter for elements not present in both data sets
my @filename_intersection =
  grep { exists $index{$_}{api_idx} && exists $index{$_}{csv_idx} }
  ( keys %index );

foreach my $filename (@filename_intersection) {

    # do something with
    my $api_entry = $api_ref->[ $index{$filename}{api_idx} ];
    my $csv_entry = $csvdata->[ $index{$filename}{csv_idx} ];

# example convert ExpectedTime into seconds and compare it to Start/End time difference
    $csv_entry->{ExpectedTime} =~ /^(\d{2}):(\d{2}):(\d{2})$/;
    my $exp_sec  = ( $1 * 60 + $2 ) * 60 + $3;
    my $real_sec = $api_entry->{EndTimestamp} - $api_entry->{StartTimestamp};

    my $msg = "";
    if ( $exp_sec >= $real_sec ) {
        $msg = "in time:";
    }
    else {
        $msg = "late:";
    }

    printf
      "Filename %s was %s; expected time: %d seconds, real time: %d seconds\n",
      $filename, $msg, $exp_sec, $real_sec;
}

Best,
Frank


text:
Q: Convert string to its lower case ascii hexadecimal representation I'm creating a sha-256 hash for a payment integration
The requirements are (from the bank's instructions) :
Step 1: Create the string
eg 987654321012013:07:16-09:57:081.00826TopSecret
Step 2: Convert the created string to its ascii hexadecimal representation
eg 3938373635343332313031323031333a30373a31362d30393a35373a3038312e3030383236546f70536563726574
Step 3: generate sha-256 hash of the converted string
eg 3d7e75aa0b4e0e1d4a7ac87e451e64692cced46f4358ef35a69d96721341243c
The problem:
Step 2 in my code gives upper-case A,D,E,F etc which then produces a different sha-256 to the given example.  I need to produce the byte array with lower case hex representation.
here is my code (in .NET 4.5.2):
string hash = createHash( inputstring );

public static string createHash(string inputString)
{
      SHA256 sha256 = SHA256Managed.Create();
      byte[] bytes = Encoding.ASCII.GetBytes(inputString);
      // need my bytes to be lower case
      byte[] hash = sha256.ComputeHash(bytes);
      return GetStringFromHash(hash).ToLower();
}

Thank you for any help.

A: You've hashed this:

987654321012013:07:16-09:57:081.00826TopSecret

Not the ascii hexadecimal representation of it

I suspect you want to replace
// need my bytes to be lower case

With something like
var inputToHash = BitConverter.ToString(bytes).Replace("-","").ToLower();

Or perhaps something like
var inputToHash = string.Concat(bytes.Select(b => b.ToString("x2")));

And then hash inputToHash (GetBytes it again), not bytes

If you need this to be higher performance, perhaps use a stringbuilder rather than bitconverter or linq

A: The missing step is the conversion to a string in hexadecimal representation. We can convert the characters of the string to an int and then format it as hexadecimal with .ToString("x2").
//Step 1: Create the string
string secret = "987654321012013:07:16-09:57:081.00826TopSecret";

//Step 2: Convert the created string to its ascii hexadecimal representation
string hexString = String.Concat(secret.Select(c => ((int)c).ToString("x2")));
// Has already lower case hex digits here. No action required.

//Step 3: generate sha-256 hash of the converted string
byte[] bytes = Encoding.ASCII.GetBytes(hexString);
SHA256 sha256 = SHA256Managed.Create();
byte[] hash = sha256.ComputeHash(bytes);

// Return the hash bytes as hexadecimal string
return GetStringFromHash(hash);

Note that a string is an enumeration of characters. I.e., the String Class implements IEnumerable<char>. Therefore, we can use LINQ Select to convert the characters of the input string. Note that in C# the char type is considered to be a 16 bit numeric type. Therefore you can convert it from and to int (32-bit).

You can implement GetStringFromHash like this:
private static string GetStringFromHash(byte[] hash)
{
    return String.Concat(hash.Select(b => b.ToString("x2")));
}

Note that .ToString("x2") generates lower case hexadecimal digits. So, no further .ToLower() is required.

Note that the requirement of using ASCII restricts the character set to the range (char)1 .. (char)127. (char)0 is excluded, because it can be misinterpreted as string terminator in certain APIs. So, it is not sure, whether this restriction concerns the secret input string or the hex string or both. It might be sufficient to limit the secret string to the range (char)1 .. (char)255, which would include some diacritics, but would certainly exclude Chinese character for example.


text:
Q: Private DHCP through a switch using two eth interfaces? Right now, I have an Scientific Linux blade connected to the internet on eth3, and connected to a 48 port Cisco switch on eth2. This Cisco switch is connected to the eth2 of 24 blank blades (which are not connected to the internet).
I want to be able to assign the 24 blades private IPs based on their hostname so my main blade can connect to them, while keeping them fenced off from the internet. However, because there are so many, I also want to install kickstarted CentOS on them via PXE from the main blade. To do this I would need them to be assigned an IP first via DHCP, right?
So how would I go about doing all this? Any pointers would be appreciated.

A: This is just a basic DHCP/PXE boot environment.

*

*Build your PXE Boot resources as per CentOS documentation.

*Setup DHCP and TFTP on SL.

*Configure SL DHCP to serve leases with PXE booting options.

The "private" blades will not have access to the internet unless you enable routing etc on the SL blade (1).
There is nothing overly special about what you're doing. You'll need to statically assign a private address to eth2 on the SL blade, then configure the corresponding subnet block in dhcpd.conf
(1) Unless SL does something stupid like automatically enabling routing, which I doubt.


text:
Q: Limit a left join to latest date in View I've got a query that's connected to a table which I only want to see the last entered result based on the dtm.
This is my query:
CREATE OR REPLACE VIEW vwc_students AS
SELECT u_students.stud_id,u_students.stud_firstname, u_students.stud_middlename,u_students.stud_lastname, CONCAT_WS(' ',u_userse.user_firstname,u_userse.user_lastname) AS stud_editeduser, u_students.stud_edited, u_tbleeditlog.editedDtm
FROM u_students
JOIN u_studsites ON u_studsites.uss_studid = u_students.stud_id
JOIN u_locations ON u_locations.loc_id = u_students.stud_base
JOIN u_users ON u_users.user_id = u_students.stud_loggedid
LEFT JOIN (SELECT editedID, editedDtm FROM u_tbleeditlog WHERE editSite = 1 AND editType = 1 ORDER BY editedDtm DESC LIMIT 1) u_tbleeditlog ON u_tbleeditlog.editedID = u_students.stud_id
LEFT JOIN u_users AS u_userse ON u_userse.user_id = u_tbleeditlog.editedID
WHERE u_studsites.uss_siteid = '1'

but I'm getting the error #1349 - View's SELECT contains a subquery in the FROM clause
I got the code examples from Limiting a left join to returning one result? and MySQL JOIN Multiple Tables With LIMIT Last Table By DateTime per result
Is what I am trying to do possible, and if so how?
Update
I now have the following two views as suggested:
CREATE OR REPLACE VIEW vwc_students AS
SELECT u_students.stud_id,u_students.stud_firstname, u_students.stud_middlename,u_students.stud_lastname, u_userse.editedEditor AS stud_editeduser, u_userse.editedDtm AS stud_edited
FROM u_students
JOIN u_studsites ON u_studsites.uss_studid = u_students.stud_id
JOIN u_locations ON u_locations.loc_id = u_students.stud_base
JOIN u_users ON u_users.user_id = u_students.stud_loggedid
LEFT JOIN vwu_editlog AS u_userse ON u_userse.editTypeID = u_students.stud_id AND u_userse.editType = 1
WHERE u_studsites.uss_siteid = '1'

and
CREATE OR REPLACE VIEW vwu_editlog AS
SELECT u_tbleeditlog.*, CONCAT_WS(' ',u_users.user_firstname,u_users.user_lastname) AS editedEditor
FROM u_tbleeditlog
JOIN u_users ON u_users.user_id = u_tbleeditlog.editedID
ORDER BY u_tbleeditlog.editedDtm DESC LIMIT 1

But this last view is limiting the entire thing to 1 result! How would I limit each unique ID to 1? I also get the message Current selection does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available., even though in the original table it is there.

A: Duplicate of:
View's SELECT contains a subquery in the FROM clause
As per documentation:
MySQL Docs

*

*The SELECT statement cannot contain a subquery in the FROM clause.

Your workaround would be to create a view for each of your subqueries.
Then access those views from within your view view_credit_status
So maybe you'd first do something like this:
CREATE OR REPLACE VIEW u_tbleeditlog AS
 SELECT editedID, editedDtm
  FROM u_tbleeditlog
  WHERE editSite = 1
  AND editType = 1
  ORDER BY editedDtm DESC
  LIMIT 1;

A: You are missing the fact that views in MySQL do not allow subqueries in the from clause. They are allowed in the select and where and having clauses, however.
The documentation:http://dev.mysql.com/doc/refman/5.0/en/create-view.html is quite clear:
Subqueries cannot be used in the FROM clause of a view.
In your case, you can probably rewrite the from clause as a correlated subquery in the select clause. You can also use multiple layers of views to do what you want.
Create a separate view for each of the FROM clause.


text:
Q: Getting a 404 on angular.js on a MEAN app using gulp I am attempting to setup a new MEAN app using gulp and bower but I keep getting 404 errors on my bower dependencies when I start my app. I used express-generator to get my folder structure, but I wanted to use gulp to inject my frontend dependencies from bower and my javascript files into my index file.
Folder structure:
.
+-- bin
|   +-- www
+-- lib (bower_components)
|   +-- angular
|   +-- angular-ui-router
+-- node_modules
|   +-- ...
+-- public
|   +-- javascripts
|   |   +-- angularApp.js
+-- routes
|   +-- index.js
|   +-- users.js
+-- views
|   +-- index.ejs
+-- app.js
+-- gulpfile.js
+-- bower.json
+-- package.json

And my gulpfile:
'use strict';

var gulp = require('gulp'),
    browserSync = require('browser-sync'),
    inject = require('gulp-inject'),
    nodemon = require('gulp-nodemon'),
    wiredep = require('wiredep').stream,
    reload = browserSync.reload;

var paths = {
    scripts: ['public/javascripts/**/*.js']
};

var nodemonOptions = {
    script: 'bin/www',
    ext: 'js',
    env: { 'NODE_ENV': 'development' },
    verbose: false,
    ignore: [],
    watch: ['bin/*', 'routes/*', 'app.js']
};

gulp.task('inject', function(){
    return gulp.src('./views/index.ejs')
        .pipe(inject(gulp.src(paths.scripts, {read:false})))
        .pipe(gulp.dest('./views'));
});

gulp.task('wiredep', function(){
    gulp.src('./views/index.ejs')
        .pipe(wiredep({
            directory: './lib',
            bowerJson: require('./bower.json')
        }))
        .pipe(gulp.dest('./views/'));
});

gulp.task('start', function(){
    nodemon({
        script: 'bin/www',
        ext: 'js',
        env: { 'NODE_ENV': 'development' },
        verbose: false,
        ignore: [],
        watch: ['bin/*', 'routes/*', 'app.js']
    })
        .on('restart');
});

gulp.task('default', ['inject', 'wiredep', 'start'], function(){
    gulp.watch(paths.scripts, ['inject', reload]);
});

I know my gulpfile is injecting angular, angular-ui-router, and angularApp.js into my index.ejs file, they show up as:
<script src="../lib/angular/angular.js"></script>
<script src="../lib/angular-ui-router/release/angular-ui-router.js"></script>
<script src="/public/javascripts/angularApp.js"></script>

but when I start the app, nothing shows up on localhost:3000 and instead there are 3 errors in the console giving me GET 404 errors on localhost:3000/lib/angular/angular.js and so on for the other 2 files.
Apologies if this isn't formatted correctly or if I haven't provided enough information, let me know if I need to provide more code/info.

A: I haven't used express-generator, but in your app.js server code, are you telling Express to serve the files located in your lib?  Try something like:
app.use('/lib', express.static(process.cwd() + '/lib'));


text:
Q: A curious approximation to $\cos (\alpha/3)$ The following curious approximation
$\cos\left ( \frac{\alpha}{3} \right ) \approx \frac{1}{2}\sqrt{\frac{2\cos\alpha}{\sqrt{\cos\alpha+3}}+3}$
is accurate for an angle $\alpha$ between $0^\circ$ and $120^\circ$
In fact, for $\alpha = 90^\circ$, the result is exact.
How can we derive it?

A: Let $y = \cos \alpha$ and $x = \cos(\alpha/3)$ then we know that
$$y = x(4x^{2} - 3)\tag{1}$$
Your approximation says that
$$x \approx \frac{1}{2}\sqrt{\frac{2y}{\sqrt{y + 3}} + 3}\tag{2}$$
or using $(1)$ we get $$\frac{y}{x} = 4x^{2} - 3 \approx \frac{2y}{\sqrt{y + 3}}\tag{3}$$ Canceling $y$ we get $$\frac{1}{x}\approx \frac{2}{\sqrt{y + 3}}\tag{4}$$ or $$4x^{2} \approx y + 3$$ or $$y \approx 4x^{2} - 3$$ Comparing with $(1)$ we see that the above approximation is true if $x = 1$ and is good enough if $x$ is near $1$. So the overall approximation is good enough if $\alpha$ is near $0$. The approximation is also correct if $y = 0$ because in this case the LHS and RHS of $(3)$ are equal to $0$.

A: Close but not exact even with regard to the linear term. With $x$ and $y$ as per Paramanand Singh's answer, if $x=1-\delta$, then, ignoring $o(\delta)$ throughout,
$$\begin{align}
y&=(1-\delta)[4(1-2\delta)-3]\\
&=(1-\delta)(4-8\delta-3)\\
&=(1-\delta)(1-8\delta)\\
&=1-9\delta.
\end{align}$$
By Paramanand Singh's equation (2),
$$\begin{align}
x&\approx \frac12\sqrt{\frac{2(1-9\delta)}{\sqrt{1-9\delta+3}}+3}\\
&\approx \frac12\sqrt{\frac{2(1-9\delta)}{\sqrt{4-9\delta}}+3}\\
&\approx \frac12\sqrt{\frac{1-9\delta}{\sqrt{1-9\delta/4}}+3}\\
&\approx \frac12\sqrt{\frac{1-72\delta/8}{1-9\delta/8}+3}\\
&\approx \frac12\sqrt{1-63\delta/8+3}\\
&\approx \frac12\sqrt{4-63\delta/8}\\
&\approx \sqrt{1-63\delta/32}\\
&\approx 1-63\delta/64.
\end{align}$$


text:
Q: How do I give reason while Restarting Windows via bat file I was using bat file to restart my windows server.. While restarting the server it is asking for restart reason, how can i give the reason through the same batch file.
Command which i am using in bat file is shutdown.exe -r -t 00.

A: Here is an example that I use:
shutdown -r /t 5 /d u:0:0 /c "Blah Blah Process is running slow" /m \\MyServer

The /c allows you to specify comment
and /d allows you to give the reason
    /d [p|u:]xx:yy  Provide the reason for the restart or shutdown.
               p indicates that the restart or shutdown is planned.
               u indicates that the reason is user defined.
               If neither p nor u is specified the restart or shutdown is
               unplanned.
               xx is the major reason number (positive integer less than 256).
               yy is the minor reason number (positive integer less than 65536).

Reasons on this computer:
(E = Expected U = Unexpected P = planned, C = customer defined)
Type    Major   Minor   Title

 U      0       0       Other (Unplanned)
E       0       0       Other (Unplanned)
E P     0       0       Other (Planned)
 U      0       5       Other Failure: System Unresponsive
E       1       1       Hardware: Maintenance (Unplanned)
E P     1       1       Hardware: Maintenance (Planned)
E       1       2       Hardware: Installation (Unplanned)
E P     1       2       Hardware: Installation (Planned)
E       2       2       Operating System: Recovery (Planned)
E P     2       2       Operating System: Recovery (Planned)
  P     2       3       Operating System: Upgrade (Planned)
E       2       4       Operating System: Reconfiguration (Unplanned)
E P     2       4       Operating System: Reconfiguration (Planned)
  P     2       16      Operating System: Service pack (Planned)
        2       17      Operating System: Hot fix (Unplanned)
  P     2       17      Operating System: Hot fix (Planned)
        2       18      Operating System: Security fix (Unplanned)
  P     2       18      Operating System: Security fix (Planned)
E       4       1       Application: Maintenance (Unplanned)
E P     4       1       Application: Maintenance (Planned)
E P     4       2       Application: Installation (Planned)
E       4       5       Application: Unresponsive
E       4       6       Application: Unstable
 U      5       15      System Failure: Stop error
 U      5       19      Security issue (Unplanned)
E       5       19      Security issue (Unplanned)
E P     5       19      Security issue (Planned)
E       5       20      Loss of network connectivity (Unplanned)
 U      6       11      Power Failure: Cord Unplugged
 U      6       12      Power Failure: Environment
  P     7       0       Legacy API shutdown


text:
Q: Why does the if block get executed after else? import os
pid = os.fork()
if pid == 0:
        print("This is the child")
else:
        print("the child is pid %d" % pid)

In the output for the above code, both the if and else blocks get executed. The else first, followed by the if. Is this behavior expected?

A: The behaviour is effectively unspecified.
As you (probably) know fork() copies the current process. In one instance it returns 0, in the other it returns the pid of the new process.
So both parts are taken, because you're actually executing it twice.
Which one goes first? That depends on which of the two processes the OS chooses to schedule first. Depending on the OS there might be a tendency, or it might always be the same, but you should not depend on that behaviour.


text:
Q: Strange behavior with debounced/throttled function I have a function that I need to call, every time a textbox value changes.  However, it initializes an AJAX call, so I need to not run the script on every keystroke.
I wrote the following function as a proof of concept:
$(document).ready(function() {
    var scheduledChange;
    function triggerLinkChange(value, debounce) {
        clearTimeout(scheduledChange);
        scheduledChange = setTimeout(function(val) {
            alert("value: "+val);
        }(value), debounce);
    }
    $('input').keyup(function(){
        triggerLinkChange($(this).val(),3000);
    });
});

Unfortunately, the delay seems to not be working, properly.  I'm not sure exactly what the issue is, as it appears to have a slight delay for the first call (maybe), but then fires with every keypress.
Any ideas?

A: You're calling the function that you declare in the timeout immediately, instead of passing it to the function.
However, it will actually work without binding or passing value to the function, because the variable is in scope anyway:
    scheduledChange = setTimeout(function() {
        alert("value: " + value);
    }, debounce);

Here's an example: http://jsfiddle.net/RbLRu/

A: Seems too complicated ?
$('input').keyup(function(){
    var self = this;

    clearTimeout( $(this).data('timer') );

    $(this).data('timer', setTimeout(function(){
        // do ajax, 3 seconds seems like lot here

        $.get('url', {value : self.value}, callback);

    }, 3000));

});

A: A much simpler way is to have a variable like this (pseudo-code because I am just typing it out here):
    var myTrigger;

    $('input').keyup(function(){
            // Cancel the countdown to do the ajax
            window.clearTimeout(myTrigger);
            // Now reset it to trigger in 3 seconds unless another key is pressed
            myTrigger = window.setTimeout(function () { DoAjax(); }, 3000);
         }
    });


text:
Q: Mapping Enum value with Hibernate I want to map Enum's value with hibernate for fetching data from DB.
In DB column **EASE_RATING** is number[1]. I'm able to save data in DB as Numeric.
But When I retrieve data by Criteria.list() I get easeRating=Two instead of easeRating=2.
My  question is How can I get Data in form of Ordinal Or Enums's Value.
public enum Rating {

    Zero(0), // [No use] Taken Zero B'Coz Ordinal starts with 0
    One(1),
    ...
    Five(5);

    private final int value;

    Rating(int value){
        this.value = value;
    }

    public int getValue(){
        return this.value;
    }

    public static Rating getRating(int x) {
        switch(x) {
            case 1: return One; ...
            case 5: return Five;
        }
        return One;
    }
}

POJO:
@Enumerated(EnumType.ORDINAL)
@Column(name = "EASE_RATING", nullable = false)
private Rating easeRating;

UPDATE
I want this value in int[ordinal()] in Hibernate List().
I'm hitting DB through hibernate.
List<CustomerFeedback> result = criteria.list();

I can achieve value throgh **getValue()**
System.out.println(Rating.Five.getValue()); // 5
System.out.println(Rating.Five);            // Five
System.out.println(Rating.Five.name());     // Five

But How would I get this in Hibernate list()

A: Hibernate is working fine. you question is about Enum.
toString() default implementation returns the name of the enum. The name is the literal of the enum: "One", "Two", etc...
If you want to obtain the ordinal of a enum stating with 1, you have to create a new method, sincel ordinal() is final:
    /**
     * One-starting index enumeration
     */
    public enum Rating {

        One, Two, Three, Four;

        public int position() {
            return ordinal() + 1;
        }

        public static Rating getRating(int x) {
            return Rating.values()[x - 1];
        }

        public static void main(String args[]) {
            Rating one = Rating.One;
            System.out.println("ToString() (name): " + one);
            System.out.println("Ordinal position stating in 1: " + one.position());
        }

    }

Answer to update 1:
Why don't just map Rating list to a value list?
    List<Rating> ratings = Arrays.asList(Rating.values());
    List<Integer> ints = ratings.stream()
            .mapToInt(Rating::position)
            .boxed()
            .collect(Collectors.toList());

A: I am not sure why you need raw database data; my recommendation is that you should always use Rating enum and take the ordinal/value from its instances in use cases where you need it.
However, one of the solutions to meet your requirements could be to map another entity to the same table with the following mapping:
@Column(name = "EASE_RATING", nullable = false)
private Integer easeRating;

Also include any other desired columns in this entity (columns which you use in this use case). Then use this entity in the query.


text:
Q: It seems obvious, but how to prove it formally? Let $f$ be a not decreasing, Lebesgue integrable function with finite integral over $[0,+\infty)$.
It seems obvious to me that $\lim_{b\rightarrow\infty}\int_b^{\infty}f(x)\,dx=0$ then.
But how can one very formally show it?
And assumption about monotonicity is crucial here, yes?

A: Be
$$F = \int_0^\infty f(x)\,\mathrm dx.$$
We have from the general rules of integration:
$$F = \int_0^\infty f(x)\,\mathrm dx = \int_0^b f(x) \,\mathrm dx
+ \int_b^\infty f(x) \,\mathrm dx.$$
Therefore
$$\int_b^\infty f(x) \,\mathrm dx = F - \int_0^b f(x) \,\mathrm dx$$
and thus
$$\lim_{b\to\infty} \int_b^\infty f(x) \,\mathrm dx = F - \lim_{b\to\infty}\int_0^b f(x) \,\mathrm dx = F - \int_0^\infty f(x)\,\mathrm dx = F - F = 0.$$

A: Lebesgue dominated convergence theorem.


text:
Q: Chromium: Corporate HTTPS-Proxy and HPKP Chromium version 58.0.3000.4 (64-bit) still works fine, but since 58.0.3029.6 (64-bit) I get NET::ERR_CERT_COMMON_NAME_INVALID for every HTTPS connection.
Clicking "Advanced" shows the following explanation (emphasis not mine):

This server could not prove that it is gmx.de; its security
  certificate is from gmx.de. This may be caused by a misconfiguration
  or an attacker intercepting your connection. Learn more.

We have a corporate proxy (Astaro) that MITMs https, thus giving me its own certificate (which is trusted in the cert store).
IE in multiple versions works flawlessly and, as mentioned above, the minor release before does, too.
What may be the reason for this error in chromium? Could this be related to HPKP?


text:
Q: Java stream match as many predicates as possible Looking to filter a list depending on some criterias define as Predicate (below are just examples):
Predicate<Person> agePredicate = p -> p.age < 30;
Predicate<Person> dobPredicate = p -> p.dateOfBirth < 1980;
Predicate<Person> namePredicate = p -> p.name.startWith("a");

List<Predicate<Person>> predicates = Arrays.asList(agePredicate, dobPredicate, namePredicate);

List<Person> shortListPersons = listPersArrays.asList(listPersons).stream().filter(p -> predicates.stream().allMatch(f -> f.test(p))).limit(10).collect(Collectors.toList());

In the situation I cannot find anyone/enough people, how can I get a list of people who match as many criterias as possible - a sort of ranking.
My other option is to call again the same function as above but using a anyMatch instead but it won't be very accurate.
Any idea? Thanks!

A: Starting with the code given from your question:
List<Predicate<Person>> predicates = Arrays.asList(agePredicate, dobPredicate, namePredicate);

We can sort a list of people by the count of predicates they match:
List<Person> sortedListOfPeopleByPredicateMatchCOunt =
  listPersArrays
    .asList(listPersons)
    .stream()
    .sorted(
      Comparator.comparingLong(p -> predicates.stream().filter(predicate -> predicate.test(p)).count()))
       // Reverse because we want higher numbers to come first.
       .reversed())
    .collect(Collectors.toList());

A: Just an extension to the above answer, if your goal is to filter a collection matching as many criteria as possible, you can create a composite Predicate<Person> and then use it for filtering.
Given your list of predicates:
List<Predicate<Person>> predicates = Arrays.asList(agePredicate, dobPredicate, namePredicate);

Composite predicates can be created like this:
Predicate<Person> compositPredicate = predicates.stream()
                .reduce(predicate -> false, Predicate::or);

NOTE: As reduction operation requires an identity value and or
  operation of Predicate<> class doesn't apply any further predicates if
  any one predicate turns out to be true, I've used predicate -> false as
  an identity value.

Now, filtering the collection becomes easier and cleaner:
List<Person> shortListPersons = persons.stream()
                                       .filter(compositPredicate)
                                       .collect(Collectors.toList());


text:
Q: Jquery-UI radio button I am using two groups of radio buttons
Group 1:

*

*State

*City

Group 2:

*

*A-C

*D-H

*I-M

*N-R

*S-Z

When I toggle between state and city, I want A-C from group 2 to be set to checked while the others are set to unchecked.
I have it working in this fiddle here fiddle
HTML:

    <input type="radio" id="byState" name="sort-radio" checked="checked"/>By State
    <input type="radio" id="byCity" name="sort-radio"/>By City

<input type="radio" id="A-C" name="alphabet-radio" checked="checked"/>
    A-C
<input type="radio" id="D-H" name="alphabet-radio"/>
    D-H
<input type="radio" id="I-M" name="alphabet-radio"/>
    I-M
<input type="radio" id="N-R" name="alphabet-radio"/>
    N-R
<input type="radio" id="S-Z" name="alphabet-radio"/>
    S-Z

JavaScript:
$(function () {
    $("#sort-radio").buttonset();
});

$(function () {
    $("#alphabet-radio").buttonset().find('label').css('width', '19.4%');
});

document.getElementById("byState").addEventListener("click", function () {
    document.getElementById("A-C").checked = true;
    document.getElementById("D-H").checked = false;
    document.getElementById("I-M").checked = false;
    document.getElementById("N-R").checked = false;
    document.getElementById("S-Z").checked = false;
}, false);

document.getElementById("byCity").addEventListener("click", function () {
    document.getElementById("A-C").checked = true;
    document.getElementById("D-H").checked = false;
    document.getElementById("I-M").checked = false;
    document.getElementById("N-R").checked = false;
    document.getElementById("S-Z").checked = false;
}, false);

However, when I use this exact code in my website, it does not work (it leaves the previously selected button from group 2 selected).  I am using jquery-ui-1.10.1.custom.css which displays the radio buttons nicely, as found here: jquery ui button.
Any clue why this would affect it?  When I remove the line <link rel="stylesheet" href="jquery-ui-1.10.1.custom.css" /> from my index.php, it works beautifully.

A: A few problems:

*

*The button widget works by responding to click events on the radio button's label. This means that the click event you are listening to on the radio buttons themselves won't get fired, since you actually aren't clicking the radio buttons themselves, but their labels. You can work around this by using the change event.

*You need to call .buttonset('refresh') after manually updating the checked state of a radio button.

*Just setting the checked attribute on one radio button in a group is enough to make the rest become unchecked automatically. You shouldn't need to set the checked property on each one.

*You should put your event handlers inside the document.ready handler as well. You can also just use one instead of two.
With all of those things in mind, here are the changes I would make:
$(function () {
    $("#sort-radio").buttonset();
    $("#alphabet-radio").buttonset().find('label').css('width', '19.4%');

    document.getElementById("byState").addEventListener("change", function () {
        document.getElementById("A-C").checked = true;
        $("#alphabet-radio").buttonset("refresh");
    }, false);

    document.getElementById("byCity").addEventListener("change", function () {
        document.getElementById("A-C").checked = true;
        $("#alphabet-radio").buttonset("refresh");
    }, false);
});

Example: http://jsfiddle.net/Fzq8L/2/

A: Since you are using jQuery, you can simplify this a great deal by adding a class to the radio buttons - of which only one can be "set" SO listen to the change event on those.  Remove the extra function at the start, pick one of the "array" of buttons to click from the second group. (since only one can be picked)
Simpler version markup :

    <input type="radio" class="picker" id="byState" name="sort-radio" checked='true'
    />
    By State
    <input type="radio" class="picker" id="byCity" name="sort-radio"
    />
    By City

    <input type="radio" class="secondgroup" id="A-C" name="alphabet-radio"
    checked='true' />
    A-C
    <input type="radio" class="secondgroup" id="D-H" name="alphabet-radio"
    />
    D-H
    <input type="radio" class="secondgroup" id="I-M" name="alphabet-radio"
    />
    I-M
    <input type="radio" class="secondgroup" id="N-R" name="alphabet-radio"
    />
    N-R
    <input type="radio" class="secondgroup" id="S-Z" name="alphabet-radio"
    />
    S-Z

Code:
$(document).ready(function () {
    $("#sort-radio").buttonset();
    $("#alphabet-radio").buttonset().find('label').css('width', '19.4%');
});
$(".picker").change(function () {
    $('.secondgroup').eq($('.picker').index(this)).prop("checked", true);
    $('#alphabet-radio').buttonset('refresh');
});

Working example:http://jsfiddle.net/MarkSchultheiss/8x28x/2/
Set back second group, first to item when either of first group is changed:
$(document).ready(function () {
    $("#sort-radio").buttonset();
    $("#alphabet-radio").buttonset().find('label').css('width', '19.4%');
});
$(".picker").change(function () {
    $('.secondgroup').eq(0).prop("checked", true);
    $("#alphabet-radio").buttonset("refresh");
});

Fiddle for that:  http://jsfiddle.net/MarkSchultheiss/8x28x/3/


text:
Q: Regex, how to ignore numbers' period? I want to split by period as an end of a sentence, but it split numbers as well ex: 3.25.
I have this regex (?![0-9])\.(?![0-9]) but it ignores sentences that start or end by numbers.
Edit:
and if possible abbreviations like U.S.A, like @Bamar mentioned.
thank you,


text:
Q: Pygame text processing I am trying to write a python/pygame program to simply display text. I want it to work so that when you type, for example, the letter "A", it appears on screen (kinda like gedit/notepad/whatever). I am doing this by appending the letter to a string which then gets rendered and put onto the screen. However, I have problems with actually getting user input. I know that there is the pygame.key.get_pressed() function, but I can only figure out how to use it if you actually know what key you want the user to be pressing (for example W to go forward), but not if I don't know. If that is confusing, here is my code:
import pygame
import sys
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((600,500))
myfont = pygame.font.Font(None, 60)
inp = ""

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()

    keys = pygame.key.get_pressed()
    inp = inp + #THE PRESSED KEY
    screen.fill((0,0,200))
    txt = myfont.render(inp, True, (255,255,255))
    screen.blit(txt, (100,100))
    pygame.display.update()

I want to figure out how to get the "pressed key" to get appended to the string.

A: You could use the KEYDOWN event for this because pygame.key.get_pressed() will give you results at the speed of the current FPS.
Here is a working example modified from your code:
import pygame
import sys
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((600,500))
myfont = pygame.font.Font(None, 60)
inp = ""

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()
        if event.type == pygame.KEYDOWN:
            inp += event.unicode

    screen.fill((0,0,200))
    txt = myfont.render(inp, True, (255,255,255))
    screen.blit(txt, (100,100))
    pygame.display.update()

Only changed this:

*

*Removed you pygame.key.get_pressed() call

*Added the pygame.KEYDOWN event check


text:
Q: How do you save the "Java Console" Log when a program crashes? I have enable tracing and logging and show console enabled but the program I am using is crashing Java in a matter of minutes, is there anyway I can save the log directly to a file so when it crashes I can see what the last error was that was causing this? Also I have no access to the source code of this program.

A: Please add this in while starting java -XX:ErrorFile=filename%p.log.


text:
Q: Understanding CNAME in displaydns On Windows, I do ipconfig /displaydns
One record is:
 na4.salesforce.com
 ----------------------------------------
 Record Name . . . . . : na4.salesforce.com
 Record Type . . . . . : 5
 Time To Live  . . . . : 8
 Data Length . . . . . : 8
 Section . . . . . . . : Answer
 CNAME Record  . . . . : na4-was.salesforce.com

I see no IP for it.
How does Windows resolve the IP for this then?
Note: there is no other entry for na-4-was.salesforce.com.

A: CNames or canonical names basically let you alias one domain name to another - this makes it simpler if you have lots of domain names pointing at the same server - for example, you had seperate domain names for FTP, different domain names for vhosts and so on.In this case na4.salesforce.com points at na4-was.salesforce.com, which then points at somewhere else.
If you run tracert on na4.salesforce.com, it'll look up na4-was.salesforce.com
and you get
C:\Users\geek>tracert na4.salesforce.com

Tracing route to na4-was.g.salesforce.com [96.43.150.52]
over a maximum of 30 hops:

Which means it simply resolves the ip address for the domain na4-was.g.salesforce.com when you ask for na4-was.g.salesforce.com.


text:
Q: Estimate_richness for all phyla in phyloseq Is there an easy way to get ASV richness for each Phylum for each Station using the estimate_richness function in phyloseq? Or is there another simple way of extracting the abundance data for each taxonomic rank and calculating richness that way?
So far I have just been subsetting individual Phyla of interest using for example:
ps.Prymnesiophyceae <- subset_taxa(ps, Phylum == "Prymnesiophyceae")
alpha_diversity<-estimate_richness(ps.Prymnesiophyceae,measure=c("Shannon","Observed"))
H<-alpha_diversity$Shannon
S1<-alpha_diversity$Observed
S<-log(S1)
evenness<-H/S
alpha<-cbind(Shannon=H,Richness=S1,Evenness=evenness,sample_data(Prymnesiophyceae))

But this is rather a pain when having to do it for e.g. the top 20 phyla.
EDIT:
suggestion by @GTM works well until last step. See comment + dput:
> dput(head(sample_names(ps.transect), n=2)) c("2-1-DCM_S21_L001_R1_001.fastq", "2-1-SA_S9_L001_R1_001.fastq" )
> dput(head(alpha, n=2)) structure(list(Observed = c(31, 25), Shannon = c(2.84184012598765,
2.53358345702604), taxon = c("Prymnesiophyceae", "Prymnesiophyceae" ), sample_id = c("X2.1.DCM_S21_L001_R1_001.fastq", "X2.1.SA_S9_L001_R1_001.fastq" ), S = c(3.43398720448515,
3.2188758248682), evenness = c(0.827562817437384,
0.787101955736294)), row.names = c("X2.1.DCM_S21_L001_R1_001.fastq",  "X2.1.SA_S9_L001_R1_001.fastq"), class = "data.frame")
> dput(head(smpl_data, n=1)) new("sample_data", .Data = list("001_DCM", 125L, structure(1L, .Label = "DCM", class = "factor"), structure(1L, .Label = "Transect", class = "factor"), structure(1L, .Label = "STZ", class = "factor"),
    structure(1L, .Label = "STFW", class = "factor"), "Oligotrophic",
    16L, -149.9978333, -29.997, 130.634, 17.1252, 35.4443, 1025.835008,
    1.1968, 1e-12, 5.387, 2.8469, 52.26978546, 98.0505, 0, 0,
    0.02, 0.9, 0, 0, 2069.47, 8.057, 377.3), names = c("Station_neat",  "Depth_our", "Depth_bin", "Loc", "Front", "Water", "Zone", "Bottle",  "Lon", "Lat", "pressure..db.", "Temperature", "Salinity", "Density_kgm.3",  "Fluorescence_ugL", "PAR", "BottleO2_mLL", "CTDO2._mLL", "OxygenSat_.",  "Beam_Transmission", "N_umolL", "NO3_umolL", "PO4_umolL", "SIL_umolL",  "NO2_umolL", "NH4_umolL", "DIC_uMkg", "pH", "pCO2_matm"), row.names = "2-1-DCM_S21_L001_R1_001.fastq",
    .S3Class = "data.frame")

A: You can wrap your code in a for loop to do so. I've slightly modified your code to make it a bit more flexible, see below.
require("phyloseq")
require("dplyr")

# Calculate alpha diversity measures for a specific taxon at a specified rank.
# You can pass any parameters that you normally pass to `estimate_richness`
estimate_diversity_for_taxon <- function(ps, taxon_name, tax_rank = "Phylum", ...){

  # Subset to taxon of interest
  tax_tbl <- as.data.frame(tax_table(ps))
  keep <- tax_tbl[,tax_rank] == taxon_name
  keep[is.na(keep)] <- FALSE
  ps_phylum <- prune_taxa(keep, ps)

  # Calculate alpha diversity and generate a table
  alpha_diversity <- estimate_richness(ps_phylum, ...)
  alpha_diversity$taxon <- taxon_name
  alpha_diversity$sample_id <- row.names(alpha_diversity)
  return(alpha_diversity)
}

# Load data
data(GlobalPatterns)
ps <- GlobalPatterns

# Estimate alpha diversity for each phylum
phyla <- get_taxa_unique(ps,
                         taxonomic.rank = 'Phylum')
phyla <- phyla[!is.na(phyla)]
alpha <- data.frame()
for (phylum in phyla){
  a <- estimate_diversity_for_taxon(ps = ps,
                                    taxon_name = phylum,
                                    measure = c("Shannon", "Observed"))
  alpha <- rbind(alpha, a)
}

# Calculate the additional alpha diversity measures
alpha$S <- log(alpha$Observed)
alpha$evenness <- alpha$Shannon/alpha$S

# Add sample data
smpl_data <- as.data.frame(sample_data(ps))
alpha <- left_join(alpha,
                   smpl_data,
                   by = c("sample_id" = "X.SampleID"))

This is a reproducible example with GlobalPatterns. Make sure to alter the code to match your data by replacing X.SampleID in the left join with the name of the column that contains the sample IDs in your sample_data. If there is no such column, you can create it from the row names:
smpl_data <- as.data.frame(sample_data(ps))
smpl_data$sample_id < row.names(smpl_data)
alpha <- left_join(alpha,
                   smpl_data,
                   by = c("sample_id" = "sample_id"))


text:
Q: How to extract userId from curl on Jenkins build url using jq? I have the following output from curling Jenkins $BUILD_URL/api/json:
itai@Itais-MBP ~ -  $ curl -s --insecure -u itaig:password  https://ip.us-west-2.compute.amazonaws.com/job/Company-Analytics-Prod-Deploy_New/24/api/json |
   jq -r '.actions[]'
{
  "_class": "hudson.model.CauseAction",
  "causes": [
    {
      "_class": "hudson.model.Cause$UserIdCause",
      "shortDescription": "Started by user Itai Ganot",
      "userId": "itaig",
      "userName": "Itai Ganot"
    }
  ]
}
{
  "_class": "hudson.model.CauseAction",
  "causes": [
    {
      "_class": "com.sonyericsson.rebuild.RebuildCause",
      "shortDescription": "Rebuilds build #23",
      "upstreamBuild": 23,
      "upstreamProject": "Company-Analytics-Prod-Deploy_New",
      "upstreamUrl": "view/Prod-US%20Deploy/job/Company-Analytics-Prod-Deploy_New/"
    }
  ]
}
{
  "_class": "hudson.model.ParametersAction",
  "parameters": [
    {
      "_class": "eu.markov.jenkins.plugin.mvnmeta.MavenMetadataParameterValue",
      "name": "Version"
    },
    {
      "_class": "hudson.model.StringParameterValue",
      "name": "region",
      "value": "us-east-1"
    },
    {
      "_class": "hudson.model.StringParameterValue",
      "name": "StackName",
      "value": "Company-Prd-21"
    },
    {
      "_class": "hudson.model.StringParameterValue",
      "name": "autostart",
      "value": "No"
    }
  ]
}
{}
{}
{
  "_class": "hudson.plugins.git.util.BuildData",
  "buildsByBranchName": {
    "refs/remotes/origin/master": {
      "_class": "hudson.plugins.git.util.Build",
      "buildNumber": 24,
      "buildResult": null,
      "marked": {
        "SHA1": "0e71efeac11c9909838453f4f103457ec3b04d27",
        "branch": [
          {
            "SHA1": "0e71efeac11c9909838453f4f103457ec3b04d27",
            "name": "refs/remotes/origin/master"
          }
        ]
      },
      "revision": {
        "SHA1": "0e71efeac11c9909838453f4f103457ec3b04d27",
        "branch": [
          {
            "SHA1": "0e71efeac11c9909838453f4f103457ec3b04d27",
            "name": "refs/remotes/origin/master"
          }
        ]
      }
    }
  },
  "lastBuiltRevision": {
    "SHA1": "0e71efeac11c9909838453f4f103457ec3b04d27",
    "branch": [
      {
        "SHA1": "0e71efeac11c9909838453f4f103457ec3b04d27",
        "name": "refs/remotes/origin/master"
      }
    ]
  },
  "remoteUrls": [
    "git@git.assembla.com:company.ci.git"
  ],
  "scmName": ""
}
{
  "_class": "hudson.plugins.git.GitTagAction"
}
{}
{}
{}
{}
{}
itai@Itais-MBP ~ -  $

I'm trying to extract the "userId" who started the build job as the current available Jenkins plugins which are supposed to do it don't work for some reason.
This is what I tried but it gives me an error:
itai@Itais-MBP ~ -  $ curl -s --insecure -u itaig:password  https://ip.us-west-2.compute.amazonaws.com/job/Company-Analytics-Prod-Deploy_New/24/api/json |
 jq -r '.actions[].causes[] | .userId'
itaig
null
jq: error (at <stdin>:0): Cannot iterate over null (null)
itai@Itais-MBP ~ -  $

I think it's related to the fact that there's no ".causes[]" in some of the ".actions[]" blocks, and if that's the case, is it possible to extract the "userId"?

A: Using jq, you can protect against non-existence using the post-fix "?" operator, e.g. in your case:
.actions[].causes[]?.userId? | select(.)

A: Jenkins has it own api syntax which allows you to filter the api output. You can use the xml version and specify an xpath. In your case, the following url should get you the userId.
curl -g https://ip.us-west-2.compute.amazonaws.com/job/Company-Analytics-Prod-Deploy_New/24/api/xml?xpath=//*/action[1]/cause/userId

A: what about gerpping and trimming the output :
$ curl -s --insecure -u itaig:password  https://ip.us-west-2.compute.amazonaws.com/job/Company-Analytics-Prod-Deploy_New/24/api/json |
   jq -r '.actions[]' | grep userId | cut -d ":" -f2 | tr -d '"," '


text:
Q: date is null and crashing on a few devices I am using the this code to convert date time to unixtime gmt . It is working fine on most of the devices but it is crashing in a few . I am unable to determine the cause. How can I fix it ?
int gmtOffset = TimeZone.getDefault().getRawOffset() + TimeZone.getDefault().getDSTSavings();
        String dt="11-01-2016 5:8 AM";
        DateFormat format = new SimpleDateFormat("dd-MM-yyyy hh:mm a");
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        Date date = null;
        try {
            date = format.parse(dt);
            System.out.println("Date ->" + date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        long unixtime = (date.getTime() -(gmtOffset))/1000;

error:
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.Date.getTime()' on a null object reference

A: When the locale is not set to US English, the locale's Am/pm marker may be different. For example, in Chinese, the AM/PM maker will be 上午/下午.
Thus, to force use of AM/PM, you'd need to use a US date format:
DateFormat format = new SimpleDateFormat("dd-MM-yyyy hh:mm a", Locale.US)

I ran this code when in the US locale, and it worked fine. When I switched to Chiense, I got the message:

java.text.ParseException: Unparseable date: "11-01-2016 5:8 AM" (at
  offset 15)

Offset 15 is the AM/PM marker. Thus, when exiting the try/catch block, the date object will remain null, causing the NullPointerException when calling the getTime() method.
By the way, you might consider using Joda DateTime to get the Unix epoch, something along the lines of: Joda DateTime to Unix DateTime.

A: Maybe the dtStart doesn't have the same format always (in this case it is hardcoded). If the format of dtStart is not correct after try catch block "date" is null and the app crashes at the last line because the date is null. (date.getTime())

A: The exception is throw when date is null.
And date will be null if dtStart can't be parsed.
Try like this:
int gmtOffset = TimeZone.getDefault().getRawOffset() + TimeZone.getDefault().getDSTSavings();
String dtStart="11-01-2016 5:8 AM";
DateFormat format = new SimpleDateFormat("dd-MM-yyyy hh:mm a");
format.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = null;
long unixtime = 0;
try {
    date = format.parse(dtStart);
    System.out.println("Date ->" + date);
    unixtime = (date.getTime() -(gmtOffset))/1000;
} catch (Exception e) {
    e.printStackTrace();
}


text:
Q: ESMTP error malformed address: ORCPT=rfc822 when trying to send a mail out I am seeing the folowing error in the maillog
client address has been obfuscated
Apr  5 18:15:18 my.mailserver.co.uk postfix-01/smtp[10626]: 1234567: to=<client@client.address.com>, relay=mail3.gridhost.co.uk[95.142.156.18]:25, delay=1.4, delays=0.15/0/1/0.24, dsn=5.0.0, status=bounced (host mail3.gridhost.co.uk[95.142.156.18] said: 501 <client@client.address.com> ORCPT=rfc822;client@client.address.com: malformed address: ORCPT=rfc822;client@clie may not follow <client@client.address.com>  (in reply to RCPT TO command))
I performed the following manunal test and was able to reproduce the error
$ telnet mail3.gridhost.co.uk 25
Trying 95.142.156.28...
Connected to mail3.gridhost.co.uk.
Escape character is '^]'.
220 mail-lb-002.london.gridhost.co.uk ESMTP ready
EHLO mydomain.co.uk
250-mail-lb-002.london.gridhost.co.uk
250-SIZE 50485760
250-ENHANCEDSTATUSCODES
250-8BITMIME
250-DSN
250-AUTH PLAIN LOGIN
250 STARTTLS
MAIL FROM: test@domain.co.uk
250 2.0.0 OK

RCPT TO: <client@client.address.com> NOTIFY=SUCCESS,FAILURE,DELAY ORCPT=rfc822;client@client.address.com
501 <client@client.address.com> NOTIFY=SUCCESS,FAILURE,DELAY ORCPT=rfc822;client@client.address.com: malformed address: NOTIFY=SUCCESS,FAILURE,DELAY ORC may not follow <client@client.address.com>

Without the DSN response request it works ok
RCPT TO: client@client.address.com
250 Accepted
^]

if I try without the
using postfix-2.6.6-2.el6.x86_64 on centos 6.8
any help appreciated, thanks


text:
Q: Calling multiple functions with different signatures concurrently I'd like some feedback on the implementation details of what I'm trying to build. What I want to achieve is have multiple functions with different signatures that can be called concurrently.
Calling the functions in coroutines sequentially works fine, but I'm wondering if there's a way to do this in a more idiomatic way, e.g. iterate over a slice of functions.
Since each function has different arguments and return values though, I have trouble figuring out what the best approach would be. An example that is a bit similar to my goal can be seen here: Golang - How do you create a slice of functions with different signatures?, but there the code just calls the functions and doesn't account for any return values.
Is what I have in mind even possible?

A: You can use code from linked question and just wrap the v.Call(params) into an anonymous function executing in its own goroutine like this:
...
// WaitGroup to wait on goroutines to finish their execution
var wg sync.WaitGroup

for a, v := range f {
    v := reflect.TypeOf(v)
    //calling the function from reflect
    val := reflect.ValueOf(f[a])
    params := make([]reflect.Value, v.NumIn())
    if v.NumIn() == 1 {
        params[0] = reflect.ValueOf(1564)
    } else if v.NumIn() == 2 {
        params[0] = reflect.ValueOf("Test FROM reflect")
        params[1] = reflect.ValueOf(float32(123456))
    }

    // Run them in parallel
    wg.Add(1)
    go func() {
        defer wg.Done()
        val.Call(params)
    }()
}
wg.Wait()

See it on Go Playground
As for return values Value.Call() returns []Value which is slice of return values - so you are covered here too. Your question doesn't specify what you intend to do with results but given they will be generated in parallel you'll probably need to send them through a channel(s) - you can do that in anonymous function (after processing return slice) too.

A: go func() { MyPackage.MyFunc(with, whatsoever, signature); }() - roughtly, that's what you need. You span as many goroutines (using the go keyword) as there are concurrent functions.
There is no notion of "returned value" from goroutine. For that you have to use channels. They are primary communication mechanism. So, you span a new goroutine with some function f of arbitrary signature and when it's done and you got some result, you send it to some channel shared between goroutines for communication.
Channels are thread-safe and were carefully designed to handle such a communication gracefully. Go, as programming language, provides few keywords that deal with reading/writing to/from channels. So there are pretty fundamental to (concurrent) programming in Go.
However, of course, you can handle it differently. Sharing some mutable memory protected by some kind of locking, or relying upon lockless compareAndSet fashion. Arguably, that's less idiomatic way and generally have to be avoided. Always prefer channels.


text:
Q: Rename column only if exists PostgreSQL does not allow
ALTER TABLE t RENAME COLUMN IF EXISTS c1 TO c2

...or anything like that.  However, it's very convenient to be able to write scripts which modify DB structure which can be run again without first checking if it has already been run.
How do I write a PostgreSQL function to do exactly this?

A: Please read this article on codingvila.com for a detailed explanation.
Rename Column Only If Exists in PostgreSQL
DO $$
BEGIN
  IF EXISTS(SELECT *
    FROM information_schema.columns
    WHERE table_name='your_table' and column_name='your_column')
  THEN
      ALTER TABLE "public"."your_table" RENAME COLUMN "your_column" TO "your_new_column";
  END IF;
END $$;

A: Better to have two functions, one calling the other:
CREATE OR REPLACE FUNCTION column_exists(ptable TEXT, pcolumn TEXT)
  RETURNS BOOLEAN AS $BODY$
DECLARE result bool;
BEGIN
    -- Does the requested column exist?
    SELECT COUNT(*) INTO result
    FROM information_schema.columns
    WHERE
      table_name = ptable and
      column_name = pcolumn;
    RETURN result;
END$BODY$
  LANGUAGE plpgsql VOLATILE;

CREATE OR REPLACE FUNCTION rename_column_if_exists(ptable TEXT, pcolumn TEXT, new_name TEXT)
  RETURNS VOID AS $BODY$
BEGIN
    -- Rename the column if it exists.
    IF column_exists(ptable, pcolumn) THEN
        EXECUTE FORMAT('ALTER TABLE %I RENAME COLUMN %I TO %I;',
            ptable, pcolumn, new_name);
    END IF;
END$BODY$
  LANGUAGE plpgsql VOLATILE;

A: @NessBird 2 function approach is good but the Column_Exists function can be reduced to a select exists, avoiding counting, and as an SQL function instead of a plpgsql function.
create or replace function
column_exists(ptable text, pcolumn text, pschema text default 'public')
  returns boolean
  language sql stable strict
as $body$
    -- does the requested table.column exist in schema?
    select exists
         ( select null
             from information_schema.columns
             where table_name=ptable
               and column_name=pcolumn
               and table_schema=pschema
         );
$body$;

I added the schema parameter to handle multiple schema with the same table name.
The rename_column_if_exists remains unchanged except for the possible addition of schema.

A: You can simply handle the error that may be raised in an anonymous code block:
DO
$$
    BEGIN
        ALTER TABLE t
            RENAME COLUMN c1 TO c2;
    EXCEPTION
        WHEN undefined_column THEN RAISE NOTICE 'column t.c1 does not exist';
    END;
$$;

You can omit the text after THEN to do nothing:
DO
$$
    BEGIN
        ALTER TABLE t
            RENAME COLUMN c1 TO c2;
    EXCEPTION
        WHEN undefined_column THEN
     END;
$$;

You will probably only be getting a number when the error happens. You can find the condition name (the error name after the WHEN) from here. Make sure you are on the right version for your database.

A: Thank you everybody for the great suggestions!
I've compiled a production ready solution for running migrations. I use the same function for checking if the column exists, but I've replaced the rename_table_if_exists function with a procedure:
CREATE OR REPLACE FUNCTION "product".column_exists (ptable text, pcolumn text, pschema text DEFAULT 'public')
    RETURNS boolean
    LANGUAGE sql
    STABLE STRICT
    AS $BODY$
    -- does the requested table.column exist in schema?
    SELECT
        EXISTS (
            SELECT
                NULL
            FROM
                information_schema.columns
            WHERE
                table_name = ptable
                AND column_name = pcolumn
                AND table_schema = pschema);
$BODY$;

CREATE OR REPLACE PROCEDURE "product".rename_column_if_exists (ptable TEXT, pcolumn TEXT, new_name TEXT, pschema text DEFAULT 'public')
LANGUAGE plpgsql
AS $$
BEGIN
    -- Rename the column if it exists.
    IF product.column_exists (ptable,
        pcolumn,
        pschema) THEN
    EXECUTE FORMAT('ALTER TABLE %I.%I RENAME COLUMN %I TO %I;', pschema, ptable, pcolumn, new_name);
END IF;
END
$$;

It can be used like this:
CALL <schema?>.rename_column_if_exists ('users', 'name', 'first_name', <schema name - optional>);


text:
Q: How to run a function in turtle from python 3 I am creating an art show with turtle graphics. This is what I have. I am able to run the code by separately entering in each line. Each separate chunk of code draws one item (sky, flower, grass, etc.) How can I put all of this into one function that will run? Or is that not possible?
from turtle import *

def art_show():
    speed(30)
    penup()
    goto(-100,160)
    pensize(30)
    pencolor('deep sky blue')
    pendown()
    fd(500)
    penup()
    goto(-100,175)
    pendown()
    fd(500)
    penup()
    goto(-100,190)
    pendown()
    fd(500)

    penup()
    goto(60,170)
    pencolor('yellow')
    pendown()
    circle(10)

    penup()
    goto(-100,-100)
    pencolor('forest green')
    pendown()
    fd(500)
    penup()
    goto(-100,-85)
    pendown()
    fd(500)
    penup()
    goto(-100,-70)
    pendown()
    fd(500)

    penup()
    goto(-75,-75)
    pendown()
    pensize(3)
    pencolor('dark green')
    lt(90)
    fd(100)
    penup()
    goto(-40,-90)
    pendown()
    fd(200)

    penup()
    goto(-75, 25)
    pendown()

    for i in range(6):
        pencolor("slateblue")
        circle(25)
        lt(60)

    for i in range(6):
        pencolor('dodgerblue')
        circle(15)
        lt(60)

    for i in range(6):
        pencolor('deeppink')
        circle(5)
        lt(60)

    penup()
    goto(-40, 110)
    pendown()

    for i in range(6):
        pencolor("red")
        circle(25)
        lt(60)

    for i in range(6):
        pencolor('pink')
        circle(15)
        lt(60)

    for i in range(6):
        pencolor('yellow')
        circle(5)
        lt(60)

    penup()
    goto(20,-60)
    pencolor('brown')
    pendown()
    rt(90)
    fd(140)
    lt(90)
    fd(100)
    lt(45)
    fd(100)
    lt(90)
    fd(100)
    lt(45)
    fd(100)

    penup()
    goto(20, 40)
    pendown()
    lt(90)
    fd(140)
    penup()
    goto(70,-60)
    pendown()
    lt(90)
    pencolor('black')
    fd(45)
    rt(90)
    fd(30)
    rt(90)
    fd(45)

A: just add:
if __name__ == '__main__':
    art_show()

to the bottom of your file.  Then it works for me.

A: You simply need to call art_show() after you define art_show().  Below is a rework of your code to simplify it some and address some coding style issues:
from turtle import *

def jump(x, y):
    penup()
    goto(x, y)
    pendown()

def art_show():
    pensize(30)
    pencolor('deep sky blue')  # sky
    jump(-100, 160)
    fd(500)
    jump(400, 175)
    bk(500)
    jump(-100, 190)
    fd(500)

    pencolor('yellow')  # sun
    jump(60, 170)
    circle(10)

    pencolor('forest green')  # lawn
    jump(-100, -100)
    fd(500)
    jump(400, -85)
    bk(500)
    jump(-100, -70)
    fd(500)

    pensize(3)
    pencolor('dark green')  # stems
    jump(-75, -75)
    lt(90)
    fd(100)
    jump(-40, -90)
    fd(200)

    pencolor("slateblue")  # left flower
    jump(-75, 25)

    for _ in range(6):
        circle(25)
        lt(60)

    pencolor('dodgerblue')

    for _ in range(6):
        circle(15)
        lt(60)

    pencolor('deeppink')

    for _ in range(6):
        circle(5)
        lt(60)

    pencolor("red")  # right flower
    jump(-40, 110)

    for _ in range(6):
        circle(25)
        lt(60)

    pencolor('pink')

    for _ in range(6):
        circle(15)
        lt(60)

    pencolor('yellow')

    for _ in range(6):
        circle(5)
        lt(60)

    pencolor('brown')  # house
    jump(20, -60)
    rt(90)
    fd(140)

    for _ in range(2):
        lt(90)
        fd(100)
        lt(45)
        fd(100)

    jump(20, 40)
    lt(90)
    fd(140)

    pencolor('black')  # door
    jump(70, -60)
    lt(90)
    fd(45)
    rt(90)
    fd(30)
    rt(90)
    fd(45)

speed('fastest')  # if number, only 0 - 10 make sense

art_show()

hideturtle()

mainloop()


text:
Q: Dagger 2 - Can't initialize When I compile my Android project, I catch such error:
Error:(15, 13) error: android.content.Context cannot be provided without an @Provides-annotated method.
android.content.Context is provided at com......di.components.AppComponent.getContext()
My component:
@Singleton
@Component(modules = {AppModule.class})
public interface AppComponent {
    Context getContext();
    DataManager getDataManager();
}

My module:
@Module
public class AppModule {
    protected final Application mApplication;

    public AppModule(Application application) {
        mApplication = application;
    }

    @Provides
    @Singleton
    Application provideApplication() {
        return mApplication;
    }

    @Provides
    @ApplicationContext
    @Singleton
    Context provideContext() {
        return mApplication;
    }

    @Provides
    @Singleton
    DataManager provideDataManager() {
        return new DataManager();
    }
}

A: Your component says it can provide a Context:
@Singleton
@Component(modules = {AppModule.class})
interface AppComponent {
  Context getContext();
}

When all it knows about is a @ApplicationContext Context (notice the qualifier?):
@Module
class AppModule {

  @Provides
  @Singleton
  @ApplicationContext
  Context provideContext() {
    return mApplication;
  }
}

You can either remove the @ApplicationContext qualifier and just provide a Context from your module, which could get in the way if you try to also provide your activities context, or you keep your qualifier and actually provide the qualified context:
@Singleton
@Component(modules = {AppModule.class})
interface AppComponent {
  @ApplicationContext
  Context getContext();
}

If you try to use / inject the application context you will also need to use the qualifier:
@ApplicationContext @Inject Context mContext;


text:
Q: Upload de arquivo em php para outro servidor Upload de aquivos pesados para outro servidor, utilizando PHP
Enviar arquivos do Autocad, e esses arquivos são pesados...queria saber se tem como o usuário entrar no site, no setor para enviar esses arquivos, ou seja, vai ter um formulário onde o usuário vai enviar esse arquivo e vai mandar para um servidor dentro da empresa.

A: Você pode utilizar a função ftp_put caso queira realizar upload pelo FTP destes arquivos.
<?php
$file = 'somefile.txt';
$remote_file = 'readme.txt';

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// upload a file
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
 echo "successfully uploaded $file\n";
} else {
 echo "There was a problem while uploading $file\n";
}

// close the connection
ftp_close($conn_id);
?>

Fonte: Manual PHP disponível em http://php.net/manual/en/function.ftp-put.php
Como são arquivos pesados considere utilizar ajax nas suas requisições e a função set_time_limit no lado do servidor.


text:
Q: JavaFX Application name in Mac Os With Swing apps i've used setProperty() method, but it looks like it doen't work with FX Applications, are there any other ways to configure apps name from source code?

A: Bad news for you.  You can't change it.  Here's a link to the JIRA where you can go and add your disappointment at it not being fixed yet.
https://javafx-jira.kenai.com/browse/RT-22988


text:
Q: How can I create objective-C Framework for iOS Application I am in the middle of creating some generic classes that can be reusable for lot of application.
For Eg: Share Functions -  if we need this functionality in a project then we currently I need to add a group of classes into that project and display the view-controller in that group of files, In this view controller there is buttons and what all need to handle sharing.
what my idea is if a project need such a functionality they need to add a framework and call a function in it or display the specified view in framework ie. no code level access given to whom you do that project. so if any issue is found in that generic classes (framework) I need to fix it and recreate the framework and change in the all project that uses this framework without affecting the existing project.
I am think not only the sharing function. More like a Image Slider,  a PDF Viewer , a Browser. a Cover Flow. Currently I have code for all this Functions. But it take too much time to others to integrate it and use it. If any issue found we need to change the all project source classes.
I go through several links in google
Can I develop my own objective-C Framework for Cocoa Touch Applications?
http://www.cocoanetics.com/2010/04/universal-static-libraries/
A Guide for Creating your own Library for Cocoa(touch) development
I cannot understand how it use and some of them have not explain it fully. some missing in those links.
thanks in advance

A: Check out this guide on creating static iOS frameworks:
https://github.com/jverkoey/iOS-Framework

A: We created Framework in Objective c, It's work Perfect.
By Follow Below Simple Steps to create Framework
1) Create new framework as ,
In xcode select
 file =>New =>Project =>cocoatouchframework =>Next =>GiveframeworkName =>Create

2) Add .h and .m files in project, which is used for create Framework.
3) Add files in Public Headers in build phases, this file will display in your framework.

4) Click on project name DemoFramework then select + button then
select
Cross-platform =>Aggregate

5) Add Run Script

6) Add below code in Run script to Aggregate(marge)iPhone and simulator framework.
   #  ============Script Start==============
   if [ "${ACTION}" = "build" ]
   then
   # Set the target folders and the final framework product.
   INSTALL_DIR=${SYMROOT}/DemoFramework.framework
   DEVICE_DIR=${SYMROOT}/Debug-iphoneos
   SIMULATOR_DIR=${SYMROOT}/Debug-iphonesimulator

  # Create and renews the final product folder.
  mkdir -p "${INSTALL_DIR}"
  rm -rf "${INSTALL_DIR}"
  rm -rf "${INSTALL_DIR}/DemoFramework"

 # Copy the header files to the final product folder.
 ditto "${DEVICE_DIR}/DemoFramework.framework/Headers"
 "${INSTALL_DIR}/Headers"

 # Copy the info.plist file to the final product folder
 ditto "${DEVICE_DIR}/DemoFramework.framework/info.plist"
"${INSTALL_DIR}"

# Copy the ResoureBundle.bundle file to the final product folder
ditto "${DEVICE_DIR}/DemoFramework.framework/ResourceBundle.bundle"
"${INSTALL_DIR}/ResourceBundle.bundle"

# Use the Lipo Tool to merge both binary files (i386 + armv6/armv7)
 into one Universal final product.
 lipo -create "${DEVICE_DIR}/DemoFramework.framework/DemoFramework"
"${SIMULATOR_DIR}/DemoFramework.framework/DemoFramework" -output
"${INSTALL_DIR}/DemoFramework"
 fi
 #  ============Script End==============

7) Now build the project in Three steps
1) Build for iPhone device .

You will see framework is created for iPhone device and framework location is show in derived data of project as below .

2) Build for simulator.

You will see framework is created for Simulator and framework location is show in derived data of project as below .

3) This is final step to create framework,
select Aggregate in build option and build the application see screen shot as below .

Finally your framework is created use this framework in any application, The Framework location is in derived data as below.

Hopes this easy steps help someone to create framework in objective C.

A: I'm guessing that what you are asking for is how to create a shared dynamic library for iOS; and the long and short of it is: You can't.
The only kind of library supported is the static library; so whenever you make changes to your library; every application that uses it needs to be recompiled.

A: http://accu.org/index.php/journals/1594 offers detailed instructions.
OCHamcrest does it by taking a copy of the OS X version of the framework, and replacing its dynamic library with an iOS static library. (Xcode 4 version coming soon.)

A: I built Xcode 4 templates to do this. See my answer here: Can I develop my own objective-C Framework for Cocoa Touch Applications?

A: Objective-C consumer -> Objective-C dynamic framework
Xcode version 10.2.1
Create Objective-C framework
Follow Create Objective-C framework
Objective-C consumer with Objective-C framework
Follow Swift consumer with Objective-C framework
Import module to the Objective-C client code[module_name]
@import module_name;

//or umbrella or public header
#import <module_name/module_name.h>

Call a framework's code[Use of undeclared identifier]
[More examples]


text:
Q: Where is the reaction force of an object that has just flung out from a circular motion? An object in a circular motion will fly out tangentially when released. As per Newton's Third Law of motion, there is a reaction in every action. The moment the object is released, where is the reaction force?

A: This is part of why centrifugal forces are often called "fictitious." Newton's laws of motion only apply in an inertial reference frame. The moment you move into accelerating reference frames you introduce "fictitious" forces. Such "forces" are better described as fixes to your coordinate system than actual forces because they don't obey Newton's second law.
Point being, from the view of an inertial frame the object that is being "flung out" is simply moving in a straight line at constant velocity. If it had been moving in circular motion before that, then something was exerting a centripetal force on it to make it do so, and it was the cessation of that force that lead to the appearance of it being flung out.
Now, all reference frames are valid, but some principles, like conservation of energy and momentum, only apply in inertial frames. Think about it: if I'm moving along at 60 km/hr on the road, in my frame the whole world is rotating underneath me in a way that has a tremendous amount of kinetic energy. When I come to a stop, though, that energy is all gone. Where did it go? The answer is: it wasn't there in the first place. To identify the things that are "real" you need to find quantities that all observers agree on. That's where things like "proper time," "proper length," and "center of mass energy" come in.

A: While an object is in uniform circular motion, the force that is acting upon it is directed to the center. This force is what prevents the object moving linearly if the force suddenly vanished. If this were the case, the object will move in a (straight) line tangent to the circle with constant velocity.
Hence it would be wrong to assume that there is a force that acts tangential. That is, there would be no reaction force in that direction since as stated, you can think of the object trying to move in a straight line with no force$^1$ (by virtue of it's own inertia), in which case Newton's third law is not applicable since this law applies to forces (paired forces).
$^1$ Of course not including the force toward the center which keeps it in uniform circular motion.

A: If you're wondering how momentum is conserved in this situation, consider two objects bound together by a string/force and spinning, in a vacuum, with their shared center of mass at rest (zero momentum). Both bodies orbit this common barycenter, and when the string/force connecting them is severed, they will both proceed in straight, inertial trajectories in opposite directions with momenta that sum to zero in the original rest frame of their barycenter.
As others have explained, there's no "action-reaction pair" that forces them apart in the sense you're imagining, but that doesn't spoil the conservation of momentum, which is arguably the more important meaning of Newton's 3rd law.

A: Very short answer: in order to stay in circular motion, there had to be a force to keep it in such a trajectory. If the object is let go, that force must cease to exist. It's not a matter of some force (which you are asking about) changing the state of motion of the object, but a change of forces.


text:
Q: How to detect that Indirect GLX is needed but disabled? For a few years now, indirect GLX (IGLX) has been disabled by default in xorg and other X Servers.  I'm writing an application that will use OpenGL if available, but can fall back to other graphics if it is not.  Is there a standard way to detect that it is going to fail, other than trying it and responding to the errors?
My current test (written about 20 years ago) just checks if XOpenDisplay and glXQueryExtension work, but that's not sufficient:  things fail later when calling glXCreateContext and other functions.
I'd prefer not to try to open a window and check for success, because at the time I want to do the test I don't know if the user is going to need one.  My preference is to do an invisible test at startup so I can warn the user that they're going to be using the backup graphics methods.

A: Creating a OpenGL context with GLX doesn't require a window. Neiter glxCreateContext nor glxCreateNewContext take a drawable paramter. And even if they did, you can create a window without ever mapping it, i.e. make it visible, or even trigger some action from the window manager.
In X11 creating windows is a rather cheap operation, especially if the initial size of the window is 0×0 and the window is never mapped. You can still perform the whole range of X11 and GLX operations.
The upshot of all of this is, that to test if the OpenGL capabilities are available, the usual approach is to actually attempt to create an window and OpenGL context with the desired attributes and see, if this succeeds.
Since the X11 resources used for probing don't have to be mapped, this will not create any visible output; and apart from constantly polling the X server for the window tree, not even a window manager will take notice (since this depends on mapping the window).
Of course to keep thins cheap and fast, such tests should be programmed directly against X11 / Xlib, without any toolkits inbetween (since GLX is written against Xlib, even if Xcb is used, you'll have to use Xlib, for at least that part, but you'd have to do that anyway).


text:
Q: Incorrect Output of List Javascript My List is a list of dictionaries and i want to add another dictionary to it. But the output displays the items in the list inside each dictionary entry as [array].
dict={
 "Computer": [{"file" : "MyDirectory/A/text1.txt", "line" :[23,56]},
             {"file" :"MyDirectory/B/text5.txt", "line" :[32,91]}]
}

word="Computer"
key='123'
src="MyDirectory/C/text9.txt"

dict[word]=dict[word].concat({"file" : src, "line" : [key]})
console.log(dict)

This is the output
How can I make the output look like this:
{ "Computer":
    [ { "file":"MyDirectory/A/text1.txt", "line":[23,56]},
      { "file":"MyDirectory/B/text5.txt", "line":[32,91]},
      { "file":"MyDirectory/C/text9.txt", "line":[123]}]}

A: console.log() will only display your items to a certain depth. If you just need a pretty output try:
console.log(JSON.stringify(dict, null, 2));


text:
Q: rdtscp() without returning the core ID? I was reading the following Q:
Which inline assembly code is correct for rdtscp?
where it describes the following C++ to call rdtscp:
static inline uint64_t rdtscp( uint32_t & aux )
{
    uint64_t rax,rdx;
    asm volatile ( "rdtscp\n" : "=a" (rax), "=d" (rdx), "=c" (aux) : : );
    return (rdx << 32) + rax;
}

However, there is discussion regarding ECX and issues concerning returning the core ID. If I wasn't interested in the core ID, would it be possible to modify the above and reduce the rdtscp call overhead/effect on registers?


text:
Q: How to force upgrading module in odoo Please, i have tried to upgrade my module to make the xml changements functional. But, i have recognized that none changement has been done.
I think that the action of upgrading is not working.
Please who can hepl me

A: Restart your server and upgrade your module then it will work.


text:
Q: Changing JDK in Android Studio, Ubuntu I have a problem changing the default JDK for Android Studio on Ubuntu OS. The default version is located at /home/USER/Documents/android-studio/jre, which is Java 1.7, but I wanna use the Java 10.0.1 that I have installed but I simply can't find the path to the newer JDK (Android Studio is saying "Please choose a valid JDK directory"). I have used this tutorial to install new java: How to Install JDK 10 (on Windows, Mac OS & Ubuntu) and Get Started with Java Programming
Do you have any suggestions? Thanks in advance.

A: $ echo $JAVA_HOME
Copy the path displayed in terminal
Android studio File -> Project Structure -> Paste the copied path
more info
https://askubuntu.com/questions/467870/how-to-set-the-jdk-for-android-studio


text:
Q: How to scroll to the top of a modal window in javascript My requirement is that I need to show a modal window as a form to be filled by user. But the height of that modal should be not more then window size.
So if the entries in form are too much then the modal becomes scrollable. The problem is that while validating the entries in the form the error message is shown at the top of the modal above the first entry. If user is at last property then he will not be knowing that some validation error had occurred unless the modal is scrolled to top on the error event.
I have tried :
$(window).scrollTop();
// and
$('#modalId').scrollTop();

this is the modal code:

            <form class = "formFieldHolder" id="groupInfoForm"></form>

        <button class="btn cancelFormBtn" data-dismiss="modal" aria-hidden="true" msgkey="common.cancel.label"></button>
        <button class="btn btn-primary submitGroupFormBtn" type="submit" msgkey="common.submit.label"></button>

A: This is a solution without using JQuery, first you get your modal by the id and then, the function scrollIntoView will move to the top of the element you selected, in this case your modal.
let element = document.getElementById('groupModal');
element.scrollIntoView(true);

A: $('#modalId').scrollTop(0);
scrollTop() only returns the value; scrollTop(0) sets the value to 0 (all the way to the top)

A: To avoid rough movement to the top I would prefer to use (animated movement):
$('#modalId').animate({
        scrollTop : 0
    }, 'slow');

A: To scroll the page to the modal, select html, body and scroll to the offset top of the modal
$("html, body").scrollTop($("#modalId").offset().top);

If you want to scroll the modal div to the top use
$("#modalId").scrollTop(0);

Example on jsFiddle
You can combine both to scroll the page and the modal to a visible area for the user if needed.
References

*

*jQuery scrollTop

*jQuery offset

A:

A: You have to include "jquery-1.7.1.min.js" file in your page.
http://code.jquery.com/jquery-1.7.1.min.js


text:
Q: C# Reflection get object for GetValues in nested Property Type I have searched and tested for the last few hours and I can't seem to get the results I'm after.
I'm trying to get a value from a nested property.
I can get the Property names with no issues with the following.
public static IList<string> GetClassPropertyNames(object myObject)
 {
  List<string> propertyList = new List<string>();
     if (myObject != null)
     {
         var a = myObject.GetType().GetProperty("inobjects").PropertyType.GetProperties();
         foreach (var prop in a)
         {
             propertyList.Add(prop.Name.ToString());
         }
     }
     return propertyList;
    }

However if I then use one the of the names as string to get the property I can't get the right object or type in GetValue(Object, null) to get me the value I need.
I am using the following.
public static string GetNestedProperty(object myObject, string PropertyName)
    {
        string s = null;
        var a = myObject.GetType().GetProperty("inobjects").PropertyType.GetProperties();
        foreach (PropertyInfo pi in a)
        {
            if(pi.Name == PropertyName)
            {
                s = pi.GetValue(???, null).ToString();
            }
        }
        return s;
    }

I want to keep the actual type generic as I am using "inobjects" as a property to get alot of properties for different classes and want a single way to access the Property names and values.
I'm just not able to get the right object at the right level and as a result keep getting issues with my type not being relevant. Any help would be appreciated.

A: Your problem really boils down to the fact that you need to obtain an instance of the immediate property from which to extract the value of the nested property.
In concrete words - you need to obtain the value (instance) of the immediate property "inobjects" before you can resolve the value of the nested property propertyName.
Ideally you will cache the PropertyInfo instance but to make the code work in the simplest way possible - resolve the value like this:
...
if (pi.Name == PropertyName)
{
    var value =
        myObject.GetType()
                .GetProperty("inobjects")
                .GetValue(myObject, null);

    s = (string) pi.GetValue(value, null);
}

You might be interested to know that you do not need to manually iterate over each property and that you could use GetProperty instead (which will return null if the property does not exist). I took the liberty of refactoring your code for you:
public static string GetNestedProperty(object value, string propertyName)
{
    var type = value.GetType();
    var property = type.GetProperty("inobjects");
    value = property.GetValue(value, null);
    type = property.PropertyType;

    property = type.GetProperty(propertyName);

    if (property == null)
    {
        return null;
    }

    value = property.GetValue(value, null);
    return (string) value;
}

A: A couple of things that I can see:
1) (this may not be a problem, but won't hurt to post it) you are using a foreach loop without any sort of break when the condition is met which can cause some trouble because you might have another fulfillment to the condition.
2) this is regarding your ??? that is actually for the object that you want to get the value from. So, if you know how far in the object the nested object is, just put in a condition to extract that object and hold it until that line. If it's the "inobjects" object, just break the setting of a up so that you can get it. Something like this:
var rawNestedObject = myObject.GetType().GetProperty("inobjects");
var a = nestedObject.PropertyType.GetProperties();

then your ??? marks can get replaced with nestedObject which would be reference that gets extracted from rawNestedObject.
APPEND: Also, you are not using any flags on your GetProperty calls which default to public instance properties. I don't know what your standard is for naming public members, so feel free to disregard this paragraph if you are accessing a public instance property.

A: This Will get you the value of the inner property:
var a = obj.GetType().GetProperty("inobjects").PropertyType.GetProperties();
foreach (var item in a)
{
     if (item.Name == PropertyName)
     {
         var test = obj.GetType().GetProperty("inobjects").GetValue(obj,null);
         s = (string)test.GetType().GetProperty(PropertyName).GetValue(test, null);
     }
}

Its not the cleanest way but this example will do.


text:
Q: git push --mirror getting (pre-receive hook declined) I am working on trying to mirror a repo into a new empty one using bitbucket server. The Hooks are disabled, however on the push -mirror I am still getting pre-receive hook declined error on every branch.
What I am using
 git clone --mirror <url to old_repo>
 cd old_repo
 git push --mirror <url to new_repo>

Am curious if anyone else has had this issue using bitbucket / bash, or any insight into a work around.


text:
Q: ASP.NET Dynamic GridView Creation How can I add an Edit column in this GridView dynamically?

I have been able to create this GridView dynamically with the following code.
The aspx file:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="GridView___Test._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>

<body>
    <form id="form1" runat="server">
    <div>

        <asp:GridView ID="GridView1" runat="server" Font-Names="Verdana" Font-Size="Small" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" AutoGenerateColumns="False">
        </asp:GridView>

    </div>
    </form>
</body>

</html>

The code behind:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Ice_Web_Portal.BO;

namespace GridView___Test
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                CreateGridView();
            }
        }

        private void CreateGridView()
        {
            DataTable dataTable = Book.GetBooksDataSet().Tables[0];

            foreach (DataColumn c in dataTable.Columns)
            {
                BoundField boundField = new BoundField();

                boundField.DataField = c.ColumnName;
                boundField.HeaderText = c.ColumnName;

                GridView1.Columns.Add(boundField);
            }

            GridView1.DataSource = dataTable;
            GridView1.DataBind();
        }
    }
}

Now please tell how to add some more code to add Edit column in this GridView dynamically.

A: out of the foreach, try
CommandField c = new CommandField();
c.ShowEditButton = true;

c.Columns.Add(c);


text:
Q: Is there always a currency that goes up compared to all others? Suppose you go through every country's currencies and look at the change WRT all other currencies that day.  Assuming there is a change in value that day, does it stand to reason that there will always be a certain currency that goes up WRT all others and one that goes down WRT to all others everyday?

A: This is true and the reason is that currency exchange rates are transitive. That means if you know the exchange rate between A and B, and the rate between B and C, the you can compute the exchange rate between A and C (we are assuming no conversion fees as is the case for published conversion rates).
This transitivity also implies that if for example A increased relative to B and B increased relative to C than A must have increased relative to C as well. Once you know that it is straightforward that there every day there must be one currency that increased relative to all others (assuming all exchange rates changed).