Q: net::ERR_CONTENT_LENGTH_MISMATCH on angular 2 on docker cloud I am getting a net::ERR_CONTENT_LENGTH_MISMATCH  main.bundle.js  while running angular 2 on docker cloud ,the same however works on my local docker instance
The below is the docker file
FROM node

RUN mkdir -p /usr/src/app

WORKDIR /usr/src/app

COPY . /usr/src/app

RUN npm install

and the docker compose
version: '2'
services:
app:
 build: .
 volumes:
   - ./:/usr/src/app
 ports:
   - 4200:4200
   - 49153:49153
 command: npm start

Any clue as to why this is happening will be of much help

A: Happened to me after I updated one of the packages in node_modules. Probably integrity/checksum-related issue. The cure was to flush node_modules and run
$ npm install
again.


Q: Using the deep neural network package "Chainer" to train a simple dataset I'm trying to use the chainer package for a large project I'm working on. I have read through the tutorial on their website which gives an example of applying it to the MNIST dataset, but it doesn't seem to scale easily to other examples, and there's simply not enough documentation otherwise.
Their example code is as follows:
class MLP(Chain):
    def __init__(self, n_units, n_out):
        super(MLP, self).__init__(
            # the size of the inputs to each layer will be inferred
            l1=L.Linear(None, n_units),  # n_in -> n_units
            l2=L.Linear(None, n_units),  # n_units -> n_units
            l3=L.Linear(None, n_out),    # n_units -> n_out
        )

    def __call__(self, x):
        h1 = F.relu(self.l1(x))
        h2 = F.relu(self.l2(h1))
        y = self.l3(h2)
        return y

train, test = datasets.get_mnist()
train_iter = iterators.SerialIterator(train, batch_size=5, shuffle=True)
test_iter = iterators.SerialIterator(test, batch_size=2, repeat=False, shuffle=False)
model = L.Classifier(MLP(100, 10))  # the input size, 784, is inferred
optimizer = optimizers.SGD()
optimizer.setup(model)
updater = training.StandardUpdater(train_iter, optimizer)
trainer = training.Trainer(updater, (4, 'epoch'), out='result')
trainer.extend(extensions.Evaluator(test_iter, model))
trainer.extend(extensions.LogReport())
trainer.extend(extensions.PrintReport(['epoch', 'main/accuracy', 'validation/main/accuracy']))
trainer.extend(extensions.ProgressBar())
trainer.run()

Could someone point me in the direction of how to simple fit a straight line to a few data points in 2D? If I can understand a simple fit such as this I should be able to scale appropriately.
Thanks for the help!

A: I pasted simple regression modeling here.
You can use original train data and test data as tuple.
    train = (data, label)
Here, data.shape = (Number of data, Number of data dimesion)
And, label.shape = (Number of data,)
Both of their data type should be numpy.float32.
import chainer
from chainer.functions import *
from chainer.links import *
from chainer.optimizers import *

from chainer import training
from chainer.training import extensions
from chainer import reporter
from chainer import datasets
import numpy

class MyNet(chainer.Chain):

    def __init__(self):
        super(MyNet, self).__init__(
            l0=Linear(None, 30, nobias=True),
            l1=Linear(None, 1, nobias=True),
        )

    def __call__(self, x, t):
        l0 = self.l0(x)
        f0 = relu(l0)
        l1 = self.l1(f0)
        f1 = flatten(l1)
        self.loss = mean_squared_error(f1, t)
        reporter.report({'loss': self.loss}, self)
        return self.loss

def get_optimizer():
    return Adam()

def training_main():
    model = MyNet()

    optimizer = get_optimizer()
    optimizer.setup(model)

    train, test = datasets.get_mnist(label_dtype=numpy.float32)
    train_iter = chainer.iterators.SerialIterator(train, 50)
    test_iter = chainer.iterators.SerialIterator(test, 50,
                                                 repeat=False,
                                                 shuffle=False)

    updater = training.StandardUpdater(train_iter, optimizer)
    trainer = training.Trainer(updater, (10, 'epoch'))
    trainer.extend(extensions.ProgressBar())
    trainer.extend(extensions.Evaluator(test_iter, model))
    trainer.extend(
        extensions.PlotReport(['main/loss', 'validation/main/loss'],
                              'epoch'))
    trainer.run()

if __name__ == '__main__':
    training_main()


Q: What's behind Excel Solver Evolutionary? I have an optimization problem on Excel, using Evolutionary algorithm.
Works fine, but i'd like to understand how it gets to the solution, ie what is or are the exact method(s) used.
Is that available anywhere ?
The final purpose being to move this project from Excel to a Java program, because it gets more and more complex.
Thank you

A: Do the same optimization in LibreOffice Calc. Algorithms done in LibreOffice Calc are available as part of the open-source project.


Q: Open browser windows without menu bars (JavaScript?) The users in my community want the chat to be opened in a small window without all the control bars.
So I think a popup window without scroll bars, location bar, status bar and so on would be the best solution. Right?
What is the best way to have such a popup window? JavaScript? Can I do it like this?
BETWEEN  AND

BETWEEN  AND
Open chat

ON CHAT.HTML
<form><input type="submit" value="Close chat" onClick="window.close()"></form>

A: If you want the new window not to have the menu bars and toolbars, the only way to do it is through JavaScript as with the example you provided yourself. However keep in mind that most browsers, nowadays, ignore what you set for the status bar (always show it) and may be configured to also always show the remaining toolbars. If a browser is configured in such a way there's no escaping it, although the default should be that you'll only get the status bar and perhaps the address bar.

A: Your solution is good, but there are alternatives.
You can create the window by your own, as some kind of layer. Then you need to implement lots of things but it gives you full control over window Look And Feel. Of course you can always use some scripts like jQuery UI Dialog.

A: In short, you can't control everything that the browser displays in a pop-up window. Most browsers keep the URL visible, for example. This page explains most of the details (though it is a couple years old).


Q: Php laravel 5 fatalexception unexpected end of file I have the following code snippet to end a file in php and laravel.
 @extends('master')
 @section('content')

Hello World

 @endsection

master.blade.php file is as below
<!doctype html>

   <meta charset="UTF-8">
   <title>{{ $title }}</title>
    {{ HTML::style('css/bootstrap.css') }}
    {{ HTML::script('js/bootstrap.js') }}
    {{ HTML::script('js/jquery.js') }}

      {{ HTML::link('/','login',array('class' => 'brand')) }}

        @if(Auth::user())

{{ HTML::link('logout', 'Logout') }}

        @else

{{ HTML::link('login','login') }}

    @yield('content')

However, I get the following error:
FatalErrorException in 4d94a10943d3d038e850b4e898e794a8 line 33:
syntax error, unexpected end of file

What exactly is the syntax to end the file in laravel,php using the blade template.

A: You're missing the @endif directive. Your blade syntax needs to be:
@if(Auth::user())

{{ HTML::link('logout', 'Logout') }}

@else

{{ HTML::link('login','login') }}

@endif

Without the @endif directive, you'll get the "unexpected end of file" error.


Q: Memory for a member array in C# I have been programming for a while today and I think I need a break because I can't seem to figure this very simple thing. A help will be greatly appreciated.
I have a class (actually Form1) and there a member array int[,]f.
Now I don't manage memory for it there and then (maybe I should?).
Instead in another method, I call a function say:
myFunction(f,.....);

this function is like
void myFunction(int[,] f, ...some other arguments)
{
    //....
    f = new int[NX ,NY];
    //....
}

As you can see, I separate memory for the array f inside the function.
Now my question is; is this memory going to be garbage collected when I leave myFunction?

A: First, you have to understand a few very important things:

Garbage Collection happens randomly.

Secondly,

Only those objects that have no variables referring to them are eligible for GC

Thirdly,
f= new int[NX,NY];

You are making f refer to something else. The original f is still referenced by the Form1.f. But this new int[NX, NY] object is now created and referred to only by the local f in the method.
After the method returns, nothing should be referring to the new f (unless you assigned it to somewhere else), so the new f becomes eligible for GC. Note that I said "becomes eligible for GC" instead of "is garbage collected".
However, since Form1 is still holding a reference to the original f, the original f will not become eligible for GC before the form does (unless you set it to something else).


Q: Subtracting dates from 2 different tables with join I am trying to Select all records in the claims data where the “from_date” field is before the “eff_date” for the same “emp_ssn”, same “pt_ssn”, in the "patient data".
SELECT *
FROM CLAIM
   left join PATIENT on claim.pt_ssn = Patient.pt_ssn
WHERE (CLAIM.emp_ssn = Patient.emp_num AND Patient.pt_ssn=Claim.pt_ssn)
  AND (CLAIM.FROM_DATE < Patient.eff_date);

This is giving me undesired results also with duplicates.
I have tried left join, right join, inner join, and no join. I still cannot receive desired result.  Any help would be appreciated.

A: (CLAIM.emp_ssn = Patient.emp_num AND Patient.pt_ssn=Claim.pt_ssn)

The second part of the clause Patient.pt_ssn=Claim.pt_ssn is already mentioned in the ON clause so you don't need to mention it again.
Try this :
SELECT      CLAIM.*
FROM        CLAIM
left join   PATIENT on claim.pt_ssn = Patient.pt_ssn
WHERE       CLAIM.emp_ssn = Patient.emp_num
AND         CLAIM.FROM_DATE < Patient.eff_date

EDIT : I'm not sure what data set you have, but I think a simple group by should resolve your query.
I'll try my best to help you out :
Table : CLAIM
pt_ssn   emp_ssn   claim_name   from_date
1234        1       Claim_1     2015-05-10
2345        2       Claim_2     2015-07-10
3456        3       Claim_3     2015-09-10
4567        4       Claim_4     2015-11-10
5678        5       Claim_5     2015-12-10
5678        5       Claim_5     2015-12-04
6789        6       Claim_6     2015-12-12

Table : PATIENT
pt_ssn    emp_num        eff_date
 1234       1           2015-05-12
 2345       2           2015-07-08
 3456       3           2015-09-15
 4567       4           2015-11-07
 5678       5           2015-12-09
 5678       5           2015-12-12
 6789       6           2015-12-02

You can see that I have created duplicate records with the pt_ssn as 5678. Now, if I use the aforementioned query, namely :
SELECT      CLAIM.*
FROM        CLAIM
left join   PATIENT on claim.pt_ssn = Patient.pt_ssn
WHERE       CLAIM.emp_ssn = Patient.emp_num
AND         CLAIM.FROM_DATE < Patient.eff_date

then the result set I get is :
pt_ssn      emp_ssn claim_name  from_date
 1234       1       Claim_1     2015-05-10
 3456       3       Claim_3     2015-09-10
 5678       5       Claim_5     2015-12-04
 5678       5       Claim_5     2015-12-04       /*DUPLICATE ENTRY*/
 5678       5       Claim_5     2015-12-10

SQL Fiddle : http://sqlfiddle.com/#!9/342d0/1
You can see the duplicate entry above. If you want to exclude such duplicate entries, you'll need to use Group By as follows :
 SELECT     CLAIM.pt_ssn,
            CLAIM.emp_ssn,
            CLAIM.claim_name,
            CLAIM.from_date
FROM        CLAIM
left join   PATIENT on #claim.pt_ssn = Patient.pt_ssn
WHERE       CLAIM.emp_ssn = Patient.emp_num
AND         CLAIM.FROM_DATE < Patient.eff_date
GROUP BY    CLAIM.from_date,
            CLAIM.pt_ssn,
            CLAIM.emp_ssn,
            CLAIM.claim_name

This will give you the result set as follows :
pt_ssn  emp_ssn claim_name  from_date
 1234   1       Claim_1     2015-05-10
 3456   3       Claim_3     2015-09-10
 5678   5       Claim_5     2015-12-04
 5678   5       Claim_5     2015-12-10

SQL Fiddle : http://sqlfiddle.com/#!9/342d0/2
Observe that there are two entries for the pt_ssn : 5678. This is because they are for different dates.
Hope this helps!!!

A: I am guessing there is a patient record even if there is no claim.. so the left join should be the other order.
Try this (or even list the fields you want returned):
SELECT distinct *
FROM PATIENT left join CLAIM
on claim.pt_ssn = Patient.pt_ssn
and CLAIM.emp_ssn = Patient.emp_num
WHERE CLAIM.FROM_DATE < Patient.eff_date;


Q: How to type function calls when using Function.prototype.apply I have the following types:
type Options = 'A' | 'B' | 'C' | 'D'

type SpecificOptions = 'A' | 'B'

type OptionsValueType = {
  A: () => void,
  B: string
}

I use those to build the following class methods:
declare class MyClass {
  myFunction(option: 'A', value: OptionsValueType['A'])
  myFunction(option: 'B', value: OptionsValueType['B'])
  myFunction(option: Exclude<Options, SpecificOptions>, value: number)

}

This works great:

And I also have some code that calls myFunction inside a loop, using Function.prototype.apply, it looks something like this:
const calls = [
  ['A', 1],
  ['B', 1],
  ['C', 1],
]

for (const call of calls) {
  a.myFunction.apply(undefined, call)
}

But the code above does not shows any type error.
I cannot use as const on the calls array because it's built dynamically (and even if I could, it does not seems to work either).
How to type the code above to make sure the .apply is correctly typed?  Or is that currently not possible with Typescript?
Above code is available on this Typescript playground

A: If calls is built dynamically then no, there is no way to get a compile time error based on its value.
You can check the values at runtime and throw an error of your own.  Otherwise, JS will pass them in as function arguments regardless of their type.
If you wanted to check the types yourself you could do:
for (const call of calls) {
  if (typeof call[0] !== 'string' || typeof call[1] !== 'string') {
    throw new Error('Both arguments to myFunction must be strings');
  }
  a.myFunction.apply(undefined, call)
}


Q: Custom post type – customise single.php in child theme I’ve managed to create my first custom post type (in this case artists) but I want to customise how the single page layout look when click on ‘Read more’ about the artist? So far, I have copied the single.php from the Kalium theme to Kalium child theme, but do not know how to change the code in single.php
The page I need help with:
https://staging2.africanwomensplaywrightnetwork.org/artist/philisiwe-twijnstra/
<?php
/*
* Template Name: AWPN Featured Article
* Template Post Type: Artists
*/
/**
* Kalium WordPress Theme
*
* Single post template.
*
* @author Laborator
* @link https://kaliumtheme.com
*/
if ( ! defined( ‘ABSPATH’ ) ) {
exit; // Direct access not allowed.
}

/**
* Theme header.
*/
get_header();

/**
* Show post information if exists.
*/
if ( have_posts() ) :

while ( have_posts() ) : the_post();

/**
* kalium_blog_single_before_content
*
* @hooked kalium_blog_single_post_image_full_width – 10
**/
do_action( ‘kalium_blog_single_before_content’ );

?>
<div <?php kalium_blog_single_container_class(); ?>>

<?php
/**
* kalium_blog_single_content hook
*
* @hooked kalium_blog_single_post_image_boxed – 10
* @hooked kalium_blog_single_post_layout – 20
* @hooked kalium_blog_single_post_sidebar – 30
**/
do_action( ‘kalium_blog_single_content’ );
?>

<?php

/**
* kalium_blog_single_after_content
*
* @hooked kalium_blog_single_post_comments – 10
**/
do_action( ‘kalium_blog_single_after_content’ );

endwhile;

endif;

/**
* Theme footer.
*/
get_footer();

A: Make sure you give Template Name: AWPN Featured Article a new unique name.
Then go inside an artist's post and select from the right sidebar the new Template you created.
Write some content, publish, and check the page in the front-end.


Q: SQLite invalid conversion from ‘char’ to ‘const char*’ [-fpermissive] in CPP Need to update database by new value (Name and Address) provided by the user.The error in query is that:

*

*error: invalid conversion from ‘char’ to ‘const char*’ [-fpermissive]   sqlite3_bind_text(res, 2, *c2)

*error: too few arguments to function ‘int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int, void ()(void))’
     sqlite3_bind_text(res, 2, *c2)

my code is:
        const char *c1 = updatedName.c_str();
        const char *c2 = updatedAdd.c_str();

char *sql = ("UPDATE RECORDS SET NAME = ? AND ADDRESS = ? WHERE ACCOUNT_No = ?");
        rc = sqlite3_prepare_v2(db, sql, -1, &res, 0);
        sqlite3_bind_text(res, 1, *c1);
        sqlite3_bind_text(res, 2, *c2);
        sqlite3_bind_int(res, 3, acc);
        rc = sqlite3_step(res);
        sqlite3_finalize(res);

A: sqlite3_bind_text() wants a pointer to the entire string, not only the first character. (You need to understand how C pointers and strings (character arrays) work.)
And the sqlite3_bind_text() documentation tells you to use five parameters:
sqlite3_bind_text(res, 1, updatedName.c_str(), -1, SQLITE_TRANSIENT);


Q: Node js promise in a method I am new to asynch programming and I cannot understand Promises. I am trying to use a reverse geocoding library where lat/long is sent to Google Maps and a json detailing the location is returned.
class Geolocator
{
    constructor()
    {
        let options = {
            provider: 'google',
            httpAdapter: 'https',
            apiKey: mapsKey,
            formatter: null
        };

        this._geocoder = NodeGeocoder(options);
    }

    getLocationId(lat, lon)
    {
        this._geocoder.reverse({lat: lat, lon: lon})
            .then(function(res) {
                return this._parse(null, res);
            })
            .catch(function(err) {
                return this._parse(err, null);
            });
    }

    _parse(err, res)
    {
        if (err || !res)
            throw new Error(err);
        return res;
    }

When I call geolocator.getLocationId I get undefined. I am guessing that the method call exits and returns undefined. What is the best way to encapsulate the promise?

A: Like @smarx said, you would return the Promise at getLocationId() and execute then branch:
class Geolocator {
  // ...

  /* returns a promise with 1 argument */
  getLocationId(lat, lon) {
   return this._geocoder.reverse({ lat, lon })
  }
}

// calling from outside
geolocator
  .getLocationId(lat, lon)
  .then((res) => {
     // whatever
  })
  .catch((err) => {
    // error
  })


Q: difference between environment variables and System properties iam using the below link to understand environment variables and system properties.
https://docs.oracle.com/javase/tutorial/essential/environment/env.html
The link says environment variables are set by OS and passed to applications.
When i fetch environment variables using System.getenv() it shows me lot of properties which i never set.
So it must be OS (im using macOS) which had set these properties.
Some of the properties in System.getenv() are MAVEN_CMD_LINE_ARGS, JAVA_MAIN_CLASS_1420, JAVA_MAIN_CLASS_1430.
My question is why would OS would like to set the java specific properties in environment variables? Ideally these should be set by JVM (in System.properties()).
P.S.: From whatever i have read on net i understand that environment variables are set by OS and System.properties() are set by JVM
Also if someone can point me to a good link on environment variable and System.properties it will be very helpful. Iam very confused between the two.

A: Environment variables is an OS concept, and are passed by the program that starts your Java program.
That is usually the OS, e.g. double-click in an explorer window or running command in a command prompt, so you get the OS-managed list of environment variables.
If another program starts your Java program1, e.g. an IDE (Eclipse, IntelliJ, NetBeans, ...) or a build tool (Maven, Groovy, ...), it can modify the list of environment variables, usually by adding more. E.g. the environment variable named MAVEN_CMD_LINE_ARGS would tend to indicate that you might be running your program with Maven.
In a running Java program, the list of environment variables cannot be modified.

System properties is a Java concept. The JVM will automatically assign a lot of
system properties on startup.
You can add/override the values on startup by using the -D command-line argument.
In a running Java program, the list of system properties can be modified by the program itself, though that is generally a bad idea.

1) For reference, if a Java program wants to start another Java program, it will generally use a ProcessBuilder to set that up. The environment variables of the new Java process will by default be the same as the current Java program, but can be modified for the new Java program by calling the environment() method of the builder.


Q: "stripeErr : Error: You cannot accept payments using this API as it is no longer supported in India I got this error while using stripe, on 23 feb 2022

A: Check your account. You should provide a valid IEC export code to accept any payment.

A: As per latest RBI guidelines, Stripe has switched from Charges API to Payment Intent API. Use below API as per data :
Stripe::PaymentIntent.create(
  :customer => customer.id,
  :amount => params[:amount],
  :description => 'Rails Stripe transaction',
  :currency => 'usd',
)

It worked for me. Checkout Stripe API documentation here

A: you need to change "charges" to "paymentIntents"
example:
const payment  = await stripe.charges.create(  //Change here
  {
    amount: subTotal * 100,
    currency: "inr",
    customer: customer.id,
    receipt_email: token.email,
  },
  {
    idempotencyKey: uuidv4(),
  }
);


Q: Tech-stack for querying and alerting on GB scale (streaming and at rest) datasets Trying to scope out a project that involves data ingestion and analytics, and could use some advice on tooling and software.
We have sensors creating records with 2-3 fields, each one producing ~200 records per second (~2kb/second) and will send them off to a remote server once per minute resulting in about ~18 mil records and 200MB of data per day per sensor. Not sure how many sensors we will need but it will likely start off in the single digits.
We need to be able to take action (alert) on recent data (not sure the time period guessing less than 1 day), as well as run queries on the past data. We'd like something that scales and is relatively stable .
Was thinking about using elastic search (then maybe use x-pack or sentinl for alerting). Thought about Postgres as well. Kafka and Hadoop are definitely overkill. We're on AWS so we have access to tools like kinesis as well.
Question is, what would be an appropriate set of software / architecture for the job?

A: Have you talked to your AWS Solutions Architect about the use case? They love this kind of thing, they'll be happy to help you figure out the right architecture. It may be a good fit for the AWS IoT services?
If you don't go with the managed IoT services, you'll want to push the messages to a scalable queue like Kafka or Kinesis (IMO, if you are processing 18M * 5 sensors = 90M events per day, that's >1000 events per second. Kafka is not overkill here; a lot of other stacks would be under-kill).
From Kinesis you then flow the data into a faster stack for analytics / querying, such as HBase, Cassandra, Druid or ElasticSearch, depending on your team's preferences. Some would say that this is time series data so you should use a time series database such as InfluxDB; but again, it's up to you. Just make sure it's a database that performs well (and behaves itself!) when subjected to a steady load of 1000 writes per second. I would not recommend using a RDBMS for that, not even Postgres. The ones mentioned above should all handle it.
Also, don't forget to flow your messages from Kinesis to S3 for safe keeping, even if you don't intend to keep the messages forever (just set a lifecycle rule to delete old data from the bucket if that's the case). After all, this is big data and the rule is "everything breaks, all the time". If your analytical stack crashes you probably don't want to lose the data entirely.
As for alerting, it depends 1) what stack you choose for the analytical part, and 2) what kinds of triggers you want to use. From your description I'm guessing you'll soon end up wanting to build more advanced triggers, such as machine learning models for anomaly detection, and for that you may want something that doesn't poll the analytical stack but rather consumes events straight out of Kinesis.


Q: cosine and sine value of large numbers VHDl I want to implement a CPM modulation in VHDL and my device is Spartan 3A DSP. After the mathematical operation the provided data is the argument for a trigonometric functions and i'm trying to use CORDIC IP CORE in Xilinx 14.7 for this and the problem is that the input data for CORDIC must place between -pi to pi and i don't know how to do this that it could be synthetizable! for now i'm trying to implement the modulation in base band and only the cosine and sine value of the provided data should be send. for example i need the value of "cosine(234.56)" but i don't know how to do it!! i would appreciate if anyone could help me on this.


Q: Mysql2 Error - using COALESCE, Unknown column in where clause In my Rails 4.1 Application, I'm building a query to find records in my collection (orders) by an attribute (name) of a polymorphic relationship (buyer). There are 2 possible tables for that polymorphic, so I'm using 2 LEFT JOINS + COALESCE to merge the attributes. Then attempting use the value from the COALESCE in a where clause.
The method in my ActiveRecord model looks like this:
class Order
  ...
  scope :join_by_buyer_name, -> { select("stock_orders.*", "COALESCE(core_customers.business_name, core_entities.name) AS buyer_name")
      .joins("LEFT JOIN core_customers ON stock_orders.buyer_id = core_customers.id AND stock_orders.buyer_type='Core::Customer'")
      .joins("LEFT JOIN core_entities ON stock_orders.buyer_id = core_entities.id AND stock_orders.buyer_type='Core::Entity'")
    }
  ...

  def find_by_buyer_name(term)
    all.join_by_buyer_name.where("buyer_name LIKE ?", term)
  end

end

When the ActiveRecord query is executed it looks like this
SELECT stock_orders.*, COALESCE(core_customers.business_name, core_entities.name) AS buyer_name
FROM `stock_orders`
LEFT JOIN core_customers ON stock_orders.buyer_id = core_customers.id AND stock_orders.buyer_type='Core::Customer'
LEFT JOIN core_entities ON stock_orders.buyer_id = core_entities.id AND stock_orders.buyer_type='Core::Entity'
WHERE `stock_orders`.`type` IN ('Stock::SalesOrder') AND (buyer_name LIKE "blah")

Until recently this worked, However I've started receiving the following error:
Mysql2::Error: Unknown column 'buyer_name' in 'where clause': SELECT stock_orders.*, COALESCE etc etc etc
It works perfectly for sorting by the COALESCE value - ie collection.order("buyer_name asc") and up until recently the where query worked perfectly too...
I'm not sure what has changed and can't see anything in Rails or Mysql documentation. Can you see what's wrong here? Please help!

A: You cannot use the ALIAS in WHERE clause that is created from the SELECT clause. Use the computed column instead,
AND (COALESCE(core_customers.business_name, core_entities.name) LIKE "blah")

if you want to use the ALIAS, you have to wrap it in subquery like the query below,
SELECT *
FROM
     (
     SELECT stock_orders.*,
           COALESCE(core_customers.business_name, core_entities.name) AS buyer_name
     FROM `stock_orders`
          LEFT JOIN core_customers
                ON stock_orders.buyer_id = core_customers.id
                     AND stock_orders.buyer_type='Core::Customer'
          LEFT JOIN core_entities
                     ON stock_orders.buyer_id = core_entities.id
                     AND stock_orders.buyer_type='Core::Entity'
     ) subquery
WHERE `type` IN ('Stock::SalesOrder')
      AND (buyer_name LIKE "blah")


Q: How can send array as an data using ajax Please see attached jsfiddle link, I need to collect data from multiple forms and combined the data as Single data array send it to server(spring mvc controller) to persist using ajax.post
Please let me know best way to do it, will my array be converted to Json by ajax call or I have to do some magic on it.
Thanks
http://jsfiddle.net/6jzwR/1/
<form id="form1" name="formone" class="myclass">
    <input type="text" id="txt11" name="txt11" value="name1" />
    <input type="text" id="txt12" name="txt12" value="name2" />
</form>
<form id="form1" name="formtwo" class="myclass">
    <input type="text" id="txt21" name="txt21" value="name3" />
    <input type="text" id="txt22" name="txt22" value="name4" />
</form>
<input type="button" id="button" value="Click Me" />

(function ($) {
    $(document).ready(function () {
        alert("serialize data :" + $('.myclass').length);
        var mydata = null;
        $('#button').on('click', function (e) {

            $('.myclass').each(function () {
                alert("serialize data :" + $(this).serialize());
                if ((mydata === null) || (mydata === undefined)) {
                    mydata = $(this).serializeArray();
                    alert("My data is null");
                } else {
                    mydata = $.merge(mydata, $(this).serializeArray());
                    alert("My data final data after merger " + test);
                }
            });

        });
    });
}(jQuery));

A: Try this:
var array = $('input[type="text"]').map(function() {
    return $(this).val();
}).get();

alert(JSON.stringify(array));

Demo.

A: You can put all the forms' data in an array and join them with &
var formdata = []
$('.myclass').each(function(){
    formdata.push($(this).serialize());
});
var data = formdata.join('&');

http://jsfiddle.net/6jzwR/3/


Q: Angularjs ui sortable - Replace content of dropped item

{{ input.text }}

 place your elements here

var mainInputs = function(){
    return [
    {
        type: 'radio',
        text: 'Radio group',
        "content_to_drop": {
            type: 'radio',
            contents: [{
                text: 'radio 1',
                value: '1'
            },{
                text: 'radio 2',
                value: '2'
            },{
                text: 'radio 3',
                value: '3'
            }]
        }
    },
    {
        type: 'checkbox',
        text: 'Checkbox Input',
        "content_to_drop": {
            type: 'checkbox',
            contents: [{
                text: 'checkbox 1',
                value: '1'
            },{
                text: 'checkbox 2',
                value: '2'
            },{
                text: 'checkbox 3',
                value: '3'
            }]
        }
    }
    ];
};

This is a Drag and drop example.
One of the elements being dragged will be inserted inside column array.
My problem:
Instead of adding the whole object, I just only want the "content_to_drop" object to be added inside the column array. Is there any possibility of doing this?
For a better look:
https://jsfiddle.net/ssftkp96/

A: You can do the following:
var newObj = jQuery.extend({}, ui.item.sortable.model.content_to_drop); // clone
$scope.column.push(newObj);

Or if you want the drop target to only have a single object you must provide it in the form of an array:
var newObj = jQuery.extend({}, ui.item.sortable.model.content_to_drop);
$scope.column = [newObj];

var myApp = angular.module('myApp', ['ui.sortable']);

myApp.controller('MainCtrl', function($scope) {

  $scope.mainInputs = [];
  $scope.column = [];

  var mainInputs = function() {
    return [{
      type: 'radio',
      text: 'Radio group',
      content_to_drop: {
        type: 'radio',
        contents: [{
          text: 'radio 1',
          value: '1'
        }, {
          text: 'radio 2',
          value: '2'
        }, {
          text: 'radio 3',
          value: '3'
        }]
      }
    }, {
      type: 'checkbox',
      text: 'Checkbox Input',
      content_to_drop: {
        type: 'checkbox',
        contents: [{
          text: 'checkbox 1',
          value: '1'
        }, {
          text: 'checkbox 2',
          value: '2'
        }, {
          text: 'checkbox 3',
          value: '3'
        }]
      }
    }];
  };

  $scope.mainInputs = mainInputs();

  $scope.sortableSection = {
    connectWith: ".connected-apps-container",
    update: function(event, ui) {
      if ( // ensure we are in the first update() callback
        !ui.item.sortable.received &&
        // check that it's an actual moving between the two lists
        ui.item.sortable.source[0] !== ui.item.sortable.droptarget[0]) {
        ui.item.sortable.cancel(); // cancel drag and drop

        var newObj = jQuery.extend({}, ui.item.sortable.model.content_to_drop);
        $scope.column.push(newObj);
        // Or for a single object in the drop target, it must be provided as an Array:
        //$scope.column = [newObj];
      }
    }
  };
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

{{ input.text }}

        place your elements here

{{ column | json }}


Q: Why am I getting "no such file or directory" for an opencv file that exists when compiling in Ubuntu? I'm trying to use the OpenCV library in C++ (VSCode), so I have the statement #include <opencv4/opencv2/imgproc/imgproc.hpp>. When I try to compile using gcc in Ubuntu, however, I get the following error message:
/usr/local/include/opencv4/opencv2/imgproc/imgproc.hpp:48:10: fatal error: opencv2/imgproc.hpp: No such file or directory
 #include "opencv2/imgproc.hpp"

I'm fairly new to C++ and Ubuntu in general so I have no idea why this is happening, as I double checked and the file absolutely exists. In fact, even though it's apparently skipped the imgproc folder in finding the file, imgproc.hpp exists both in opencv2 and in the folder imgproc inside opencv2 anyway. How do I get this to work?

A: Did you try using #include "opencv4/opencv2/imgproc/imgproc.hpp" instead?


Q: Importing an old project in updated Android version While Running or importing a project in newer version of Android Studio got the following error even after successfully built
 - Could not find com.android.tools.build:aapt2:3.3.0-5013011.
Searched in the following locations:
  - file:/C:/Users/dimi1/AppData/Local/Android/Sdk/extras/m2repository/com/android/tools/build/aapt2/3.3.0-5013011/aapt2-3.3.0-5013011.pom
  - file:/C:/Users/dimi1/AppData/Local/Android/Sdk/extras/m2repository/com/android/tools/build/aapt2/3.3.0-5013011/aapt2-3.3.0-5013011-windows.jar
  - file:/C:/Users/dimi1/AppData/Local/Android/Sdk/extras/google/m2repository/com/android/tools/build/aapt2/3.3.0-5013011/aapt2-3.3.0-5013011.pom
  - file:/C:/Users/dimi1/AppData/Local/Android/Sdk/extras/google/m2repository/com/android/tools/build/aapt2/3.3.0-5013011/aapt2-3.3.0-5013011-windows.jar
  - file:/C:/Users/dimi1/AppData/Local/Android/Sdk/extras/android/m2repository/com/android/tools/build/aapt2/3.3.0-5013011/aapt2-3.3.0-5013011.pom
  - file:/C:/Users/dimi1/AppData/Local/Android/Sdk/extras/android/m2repository/com/android/tools/build/aapt2/3.3.0-5013011/aapt2-3.3.0-5013011-windows.jar
  - https://jcenter.bintray.com/com/android/tools/build/aapt2/3.3.0-5013011/aapt2-3.3.0-5013011.pom
  - https://jcenter.bintray.com/com/android/tools/build/aapt2/3.3.0-5013011/aapt2-3.3.0-5013011-windows.jar
Required by:
    project :app

This is the error message I receive. I downloaded an older project and found solutions to the other error messages. Yet, how can I fix this problem/error message?

A: According to the directories, I believe it is a problem with the Android SDK. Try reinstalling Android Studio (but keep the project files), which will also reinstall the Android SDK with it. If that doesn't work, go to https://developer.android.com/studio/#downloads, scroll down to command-line tools only, and download the right version of the Android SDK based on your OS. Go through the install process and hopefully that should fix your issue.


Q: modifying styles in child component modifies stack order? I'm trying to use @use-gesture/react's useDrag to ... drag things around. Specifically, some MUI components whose styling gets dynamically updated.
I have a component wrapped in a div tied to the bind hook from useDrag:
return (

  <MyComponent isDraggable={logic} isShadow={logic} /> // <- Instance 1

)

When you click on the div, I shadow out the original element, and create a new copy of the component in a createPortal portal tied to the document body, such that you can drag it around:
const dragObjectPortal = dragState && dragState.pointerStartInfo
    ? createPortal(

            <MyComponent isDragged />                 // <- Instance 2

,
        document.body
      )
    : null;

Instance 1 renders fine. When I click on it, the state updates, it gets greyed out, the portal is created attached to the body, and Instance 2 renders fine. However, when I drag Instance 2 around, the movement is constrained by the borders of Instance 1.
The return from MyComponent is something like:
return (
  <Card
    sx={{
      position: 'relative',
      zIndex: 0,
      py: 2,
      px: 3,
      cursor: 'default',
      touchAction: 'none',
      ...(!!isDraggable) ? cardSxDraggable : {},
      ...(!!isShadow) ? cardSxShadow : {}
    }}
  >
    <Box
      sx={{
        width: 300,
        height: 300,
        ...(!!isShadow) ? {bgcolor: 'text.disabled'} : {bgcolor: 'primary.main'}
      }}
    >
    </Box>
  </Card>
)

It took ~ forever for me to figure this out, but if I remove the call to Instance 1, and replace it with inline MUI components from the above return (still dynamically styled), it works fine. So, something about the dynamic styling happening in a component, rather than in the main app's return itself, is ... I don't know ... causing some resetting of the stacking order or something.
Inline demo (works as expected)
Component demo (motion constrained)
But in the actual app I'm writing, I need an arbitrary number of these components. What do I have to do to fix it so that it doesn't ... do whatever it's doing to mess with useDrag?


Q: Why does (1 >> 0x80000000) == 1? The number 1, right shifted by anything greater than 0, should be 0, correct?  Yet I can type in this very simple program which prints 1.
#include <stdio.h>

int main()
{
        int b = 0x80000000;
        int a = 1 >> b;
        printf("%d\n", a);
}

Tested with gcc on linux.

A: 6.5.7 Bitwise shift operators:

If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.

The compiler is at license to do anything, obviously, but the most common behaviors are to optimize the expression (and anything that depends on it) away entirely, or simply let the underlying hardware do whatever it does for out-of-range shifts.  Many hardware platforms (including x86 and ARM) mask some number of low-order bits to use as a shift-amount.  The actual hardware instruction will give the result you are observing on either of those platforms, because the shift amount is masked to zero.  So in your case the compiler might have optimized away the shift, or it might be simply letting the hardware do whatever it does.  Inspect the assembly if you want to know which.

A: according to the standard, shifting for more than the bits actually existing can result in undefined behavior. So we cannot blame the compiler for that.
The motivation probably resides in the "border meaning" of 0x80000000 that sits on the boundary of the maximum positive and negative together (and that is "negative" having the highmost bit set) and on certain check that should be done and that the compiled program doesn't to to avoid to waste time verifying "impossible" things (do you really want the processor to shift bits 3 billion times?).

A: It's very probably not attempting to shift by some large number of bits.
INT_MAX on your system is probably 2**31-1, or 0x7fffffff (I'm using ** to denote exponentiation).  If that's the case, then In the declaration:
int b = 0x80000000;

(which was missing a semicolon in the question; please copy-and-paste your exact code) the constant 0x80000000 is of type unsigned int, not int.  The value is implicitly converted to int.  Since the result is outside the bounds of int, the result is implementation-defined (or, in C99, may raise an implementation-defined signal, but I don't know of any implementation that does that).
The most common way this is done is to reinterpret the bits of the unsigned value as a 2's-complement signed value.  The result in this case is -2**31, or -2147483648.
So the behavior isn't undefined because you're shifting by value that equals or exceeds the width of type int, it's undefined because you're shifting by a (very large) negative value.
Not that it matters, of course; undefined is undefined.
NOTE: The above assumes that int is 32 bits on your system.  If int is wider than 32 bits, then most of it doesn't apply (but the behavior is still undefined).
If you really wanted to attempt to shift by 0x80000000 bits, you could do it like this:
unsigned long b = 0x80000000;
unsigned long a = 1 >> b;    // *still* undefined

unsigned long is guaranteed to be big enough to hold the value 0x80000000, so you avoid part of the problem.
Of course, the behavior of the shift is just as undefined as it was in your original code, since 0x80000000 is greater than or equal to the width of unsigned long.  (Unless your compiler has a really big unsigned long type, but no real-world compiler does that.)
The only way to avoid undefined behavior is not to do what you're trying to do.
It's possible, but vanishingly unlikely, that your original code's behavior is not undefined.  That can only happen if the implementation-defined conversion of 0x80000000 from unsigned int to int yields a value in the range 0 .. 31.  IF int is smaller than 32 bits, the conversion is likely to yield 0.

A: well read that maybe can help you
expression1 >> expression2
The >> operator masks expression2 to avoid shifting expression1 by too much.
That because if the shift amount exceeded the number of bits in the data type of expression1, all the original bits would be shifted away to give a trivial result.
Now for ensure that each shift leaves at least one of the original bits,
the shift operators use the following formula to calculate the actual shift amount:
mask expression2 (using the bitwise AND operator) with one less than the number of bits in expression1.
Example
var x : byte = 15;
// A byte stores 8 bits.
// The bits stored in x are 00001111
var y : byte = x >> 10;
// Actual shift is 10 & (8-1) = 2
// The bits stored in y are 00000011
// The value of y is 3
print(y); // Prints 3

That "8-1" is because x is 8 bytes so the operacion will be with 7 bits. that void remove last bit of original chain bits


Q: Check for specific naming convention I have a directory where users are saving their excel files that should adhere to a specific naming convention:
XX-TestFile.xlsx

where XX is a variable digit and -TestFile.xlsx should always be the same and not change. I'd like to be able to check through a batch job if files in the directory adhere to a specific naming convention.
If filename is misspelled, i.e. XX-TetsFiel.xlsx, XX is not a digit like 02 or even XX-testfile.xlsx (all lowercase), then files should move to an Error directory.
I am using below to move the files to achieve this. I am testing with 11-testFiel.xlsx and it works just fine.
@echo off

for /f "delims=" %%a in ('dir /b *.xlsx ^| findstr /v "[0-9][0-9]-TestFile.xlsx"') do move "%%a" "C:\Temp\Archive\Error"

However, dir /b *.xlsx | findstr /v "[0-9][0-9]-TestFile.xlsx" allows for 109 possible combinations since XX is a variable with two digits like 02. However, I would now only like to check for specific file names of 20 possible digits like 02-TestFile.xlsx, 05-TestFile.xlsx, 10-TestFile.xlsx, etc. This list is fixed... So for example, if file is named 99-TestFile.xlsx I would still like to move it to an Error archive as it is an undesired file name. Can you suggest a solution for this?

A: Put the valid names into a text file (i.e. "ValidNames.txt") and use findstr with the /G option.
02-TestFile.xlsx
05-TestFile.xlsx
10-TestFile.xlsx
...

@echo off

for /f "delims=" %%a in ('
    dir /b *.xlsx ^| findstr /vxlg:"ValidNames.txt"
') do move "%%a" "C:\Temp\Archive\Error"


Q: groupby not behaving as expected The below code is suppose to sum the values of a list of tuples but when two or more tuples contain the same value , the tuple is just outputted once :
var data = List((1, "1") , (1, "one"))            //> data  : List[(Int, java.lang.String)] = List((1,1), (1,one))

        data = data.groupBy(_._2).map {
            case (label, vals) => (vals.map(_._1).sum, label)
        }.toList.sortBy(_._1).reverse

println(data)                                     //> List((1,1))

The output of above is List((1,1)) when I'm expecting List((1,1) , (1,"one"))
Does the groupBy function paramaters need to be tweaked to fix this ?

A: Actually, it does behave as expected. groupBy returns a map. When you map over a map, you construct a new map, where, of course, each key is unique. Here, you'd have the key 1 twice…
You should then call toList before calling map, not after.


Q: Javascript select specificed data from html tag Is is possible for javascript to work like PHP to find specificed data with keyword ? for example
other html from html page
<video> <source type="application/x-mpegurl" src="https://xxxx.xxxx/xxx.mp4"></video>
other html from html page

How can javascript work 2 steps 1st get html page (like php CURL) 2nd find specificed data (in my case is all in src="xx") ("source type="application/x-mpegurl" is keywork for finding) ?
Sorry but I'm very bad in javascript.

A: You can do this with javascript:
document.querySelector('source[type="application/x-mpegurl"]').src


Q: How do I add hint text in otp text field and remain nodes focused when code entered in them? I am using the OtpTextField package and trying to add dashes (-) in text field as a hint text but unable to do so. There is a property in decoration which requires hasInputDecoration set to true, by doing so all the other decorations donot apply e.g showFieldAsBox sets to false. How can I achieve dashes in the otp text field. In addition I also want the box's border to be blue as text gets entered into the field and remain blue when all six fields are filled. Kindly help me out in this.
 OtpTextField(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                numberOfFields: 6,
                borderColor: color.primaryLight,
                filled: true,
                fillColor: color.primaryLight,
                borderRadius: BorderRadius.circular(8),
                showCursor: false,
                fieldWidth: 40,
                showFieldAsBox: true,
                disabledBorderColor: color.accentPrimary,
                decoration: InputDecoration(
                  hintText: "dfgdfgdf",
                  counterText: '',
                  hintStyle: TextStyle(
                    color: Colors.black,
                    fontSize: sizes!.fontRatio!*17,
                    fontWeight: FontWeight.bold,
                  )
                  ),
                //runs when a code is typed in
                onCodeChanged: (String code) {
                  viewModel().otpTextfield(code);
                },
                //runs when every textfield is filled
                onSubmit: (String verificationCode){
                  viewModel().otpTextfield(verificationCode);
                },
              // end onSubmit
              ),


Q: Attaching database to SQL Server 2016 using Management Studio 13 When using the right-click option on 'databases' the 'Attach' option is not listed.
CODE EXAMPLE WITH ERROR
I'm wondering if someone else has seen this before.
I also get an error when I run this code instead:
CREATE DATABASE testdb
ON (FILENAME = 'C:\databasefile.mdf')
FOR ATTACH_REBUILD_LOG
GO

My SQL Server version is
select @@version

Microsoft SQL Azure (RTM) - 12.0.2000.8   Jul 10 2018 21:38:33
Attach option is missing


Q: Is there anyway to set a binding on ALL scroll bars? I need to bind on scroll. Normally I would do this:
$(window).bind('scroll', someFunction);

The issue is that I have a scroll bar on a specific div, so this doesn't work. I need to do this:
$('.divClass').bind('scroll', someFunction);

This works fine. I want to do this for ALL my scroll bars though. Is there any good way to do this?

A: Use on to bing all your div scrollbar, including the dynamically created div.
$(document).on('scroll','.divClass', someFunction);

The .divClass must be present on all your container where you want to execute the someFunction function.


Q: Beds Online API - How to set the destination of the hotel and currency of the results Beds was provided the request example, but i cant set the destination of the hotel in here..
I just want to set manually the destination and set the currency using this request body given by the beds online.
$bedsonline_data = '{
    "stay": {
        "checkIn": "2019-01-01",
        "checkOut": "2019-01-05",
        "shiftDays": "2"
    },
    "occupancies": [
        {
            "rooms": "1",
            "adults": "1",
            "children": "1",
            "paxes": [
                {
                    "type": "AD",
                    "age": 30
                },
                {
                    "type": "AD",
                    "age": 30
                },
                {
                    "type": "CH",
                    "age": 8
                }
            ]
        }
    ],
    "hotels": {
        "hotel": [
            1067,1070,1075,135813,145214,1506,1508,1526,1533,1539,1550,161032,170542,182125,187939,212167,215417,228671,229318,23476
            ]
    }
}';

Where do i need to set that here in request body?

A: see the API docs ...the response will deliver a currency symbol.
and the example on Github explains how to set the destination:
$rqData = new \hotelbeds\hotel_api_sdk\helpers\Availability();
$rqData->destination = new Destination("PMI");


Q: Why is there a 'dangling else' scenario here? Do you think that this is a case of dangling else?
According to compiler and IIT professor it is. But I have doubt! According to theory, after condition of if is met, it will always process further only ONE statement (or one compound statement i.e. multiple statements enclosed within bracket). Here, after first if is processed and met, the compiler should consider immediate statement that is another if and check for the condition. If condition is not met, then compiler will not display any result as we don't have any associated else with printf function saying condition is not met (i.e. n is not zero).
Here, compiler should always associated given else in program with first if clause because all the statement given after first if is not enclosed in brackets. So, why there is a scenario of dangling else here?
#include <stdio.h>

void main(void)
{
  int n = 0;
  printf("Enter value of N: ");
  scanf("%d",&n);
  if (n > 0)
  if (n == 0)
    printf("n is zero\n");
  else
    printf("n is negative\n");
  getch();
}

A: Per Wikipedia's definition of dangling else, you do have a dangling else statement.
C makes your code unambiguous. Your code is interpreted as:
if (n > 0)
{
   if (n == 0)
   {
      printf("n is zero\n");
   }
   else
   {
      printf("n is negative\n");
   }
}

Had you meant the code to be interpreted as:
if (n > 0)
{
   if (n == 0)
   {
      printf("n is zero\n");
   }
}
else
{
   printf("n is negative\n");
}

you would be surprised.
FWIW, no matter which interpretation is used, your code is wrong.
What you need to have is:
if (n > 0)
{
   printf("n is positive\n");
}
else
{
   if (n == 0)
   {
      printf("n is zero\n");
   }
   else
   {
      printf("n is negative\n");
   }
}

or
if (n > 0)
{
   printf("n is positive\n");
}
else if (n == 0)
{
   printf("n is zero\n");
}
else
{
   printf("n is negative\n");
}

A: *

*if (n == 0) printf("n is zero\n"); else printf("n is negative\n"); is ONE statement and

*I strongly recommend not even paying any attention into learning the concept of danglings elses (unless it will show up in tests) but instead learning the concept of ALWAYS using curly brackets, because it helps reading the code and it helps preventing bugs especially when inserting debugging statements.

So write:
if (n > 0) {
    if (n == 0) {
        printf("n is zero\n");
    } else {
        printf("n is negative\n");
    }
}

or
if (n > 0) {
    if (n == 0) {
        printf("n is zero\n");
    }
} else {
    printf("n is negative\n");
}

and everything is clear to everyone.
BTW: Proper indentation - that might be broken due to copy&paste I admit - will help in reading code and preventing bugs, too.

A: +1 to @Bodo Thiesen's suggestion to always use curly braces. I suggest you also use clang-format to automatically format your code. It will it will ident everything correctly and generally make coding wonderful.
You can configure clang-format extensively to match your preferred style - this is your code clang-format'd in LLVM's house style.
#include <stdio.h>

void main(void) {
  int n = 0;
  printf("Enter value of N: ");
  scanf("%d", &n);
  if (n > 0)
    if (n == 0)
      printf("n is zero\n");
    else
      printf("n is negative\n");
  getch();
}


Q: PHP - PayPal Integration, failed running my custom transaction function after payment accepted I have tried using a tutorial script for PayPal payment in the past and it worked. Now it doesn't. The script is simple, all I need is this one page for processing payment:
<?php
  session_start();
  include ('mydbconfig.php');

  // payPal settings
  $paypal_email = 'seller@yahoo.com';
  $return_url = 'https://www.mytestsite.com/paypal-thanks.php';
  $cancel_url = 'https://www.mytestsite.com/paypal-cancel.php';
  $notify_url = 'https://www.mytestsite.com/paypal-notify.php';

  $item_name = $_POST['item_name'];
  $item_amount = $_POST['item_amount']; //price

  // check if paypal request or response
  if (!isset($_POST["txn_id"]) && !isset($_POST["txn_type"])){
    // firstly append paypal account to querystring
    $querystring .= "?business=".urlencode($paypal_email)."&";

    // append amount& currency (£) to quersytring so it cannot be edited in html

    //the item name and amount can be brought in dynamically by querying the $_POST['item_number'] variable.
    $querystring .= "item_name=".urlencode($item_name)."&";
    $querystring .= "amount=".urlencode($item_amount)."&";

    //loop for posted values and append to querystring
    foreach($_POST as $key => $value) {
      $value = urlencode(stripslashes($value));
      $querystring .= "$key=$value&";
    }

    // Append paypal return addresses
    $querystring .= "return=".urlencode(stripslashes($return_url))."&";
    $querystring .= "cancel_return=".urlencode(stripslashes($cancel_url))."&";
    $querystring .= "notify_url=".urlencode($notify_url);

    // Append querystring with custom field
    //$querystring .= "&custom=".USERID;

    // Redirect to paypal IPN
    header('location:https://www.paypal.com/cgi-bin/webscr'.$querystring);
    exit();

  } else { // response from Paypal

    // read the post from PayPal system and add 'cmd'
    $req = 'cmd=_notify-validate';
    foreach ($_POST as $key => $value) {
      $value = urlencode(stripslashes($value));
      $value = preg_replace('/(.*[^%^0^D])(%0A)(.*)/i','${1}%0D%0A${3}',$value);// IPN fix
      $req .= "&$key=$value";
    }

    // assign posted variables to local variables
    $data['item_name'] = $_POST['item_name'];
    $data['item_number'] = $_POST['item_number'];
    $data['payment_status'] = $_POST['payment_status'];
    $data['payment_amount'] = $_POST['mc_gross'];
    $data['payment_currency'] = $_POST['mc_currency'];
    $data['txn_id'] = $_POST['txn_id'];
    $data['receiver_email'] = $_POST['receiver_email'];
    $data['payer_email'] = $_POST['payer_email'];
    $data['custom'] = $_POST['custom'];

    // post back to PayPal system to validate
    $header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
    $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";

    $fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);

    if (!$fp) {
      // HTTP ERROR
      header('location: https://www.mytestsite.com/paypal-error.php?tr='.$data['txn_id'].'&in='.$data['item_name'].'&pe='.$data['payer_email'].'&pa='.$data['payment_amount'].'&ps='.$data['payment_status']);

    } else {
      fputs ($fp, $header . $req);
      while (!feof($fp)) {
        $res = fgets ($fp, 1024);
        if (strcmp ($res, "VERIFIED") == 0) {
          //payment accepted, insert transaction to my database
          //function to insert transaction here

        } else if (strcmp ($res, "INVALID") == 0) {
          //something to do if failed

        }
      }
      fclose ($fp);
    }
  }
?>

After the process is completed, I checked and the payment is paid successfully, but my function or anything I wrote in //function to insert transaction here won't be executed. In the end I'm forced to do the function on paypal-thanks.php page. Is there something's wrong in the script?
Is this script can be used to send more than one item purchasing? My cart is my own custom made and I only want to send Item name, number, and price detail, and total price to PayPal order summary.
I checked the other PayPal integration questions here, and most of them direct me to PayPal tutorial, documentation, or integration wizard which're confusing. I use this simple script before because I can't understand PayPal documentation (and the sample code, it didn't even let me know where to start) :(
And lastly my ultimate question, is this script is the correct and secure way to do a payment transaction?

A: use this
$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);

instead of
$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);

i think it is better to use CURL instead of socket


Q: Erlang C-Node erl_errno symbol not found error I tried to use erl_errno as described in the erlang document: http://erlang.org/doc/man/erl_error.html#.
However, I'm getting a symbol not found problem during linking. I'm running on Mac and here's the how the program is linked:
g++ -L/usr/local/lib/erlang/lib/erl_interface-3.9.3/lib -o "roserl"  ./src/driver.o ./src/erl_bridge.o  -lei -lm -lerl_interface
I have already linked with libei and liberl_interface. What else is needed?

A: It is weird but you will have to do this in your header:
#ifndef _REENTRANT
#define _REENTRANT /* For some reason __erl_errno is undefined unless _REENTRANT is defined */
#endif

#include "erl_interface.h"
#include "ei.h"

This fixed the problem for me. Now I can use erl_errno.


Q: ActionScript: How to listen for an event from a different XML I have a popup screen in which the player enters their name and clicks OK. When OK is clicked I want the player's name to be passed to the main XML. How can I do this?
Here is the function in the main XML that handles the popup:
    private function NewHighScore():void{
        highScorePopup = PopUpManager.createPopUp(this, Popup, true) as Popup;
        highScorePopup.SetScore(playerscore);
        PopUpManager.centerPopUp(highScorePopup);
        playerName = highScorePopup.getName();
        trace(playerName);
    }

And here is the popup XML script:
        import mx.events.CloseEvent;
    import mx.managers.PopUpManager;

    import spark.events.TextOperationEvent;
    public var playerName:String;

    public function SetScore (playerScore:int):void{
        scoreDisplay.text = "You achieved a new high score of " + playerScore.toString();
    }

    protected function button1_clickHandler(event:MouseEvent):void{ remove(); }

    private function remove():void{ PopUpManager.removePopUp(this);}

    protected function titlewindow1_closeHandler(event:CloseEvent):void
    { remove();}

    protected function nameBox_changeHandler(event:TextOperationEvent):void
    {playerName = nameBox.text;}

    public function getName():String{
    return playerName;
    }

A: Waiting for player to enter their name is an asynchronous process, therefore you have to wait for an event dispatched by the popup. Since the popup closes itself (gets removed from stage) once OK button is clicked, you can listen on that popup for Event.REMOVED_FROM_STAGE event, and only then gather the data from the popup. Don't for get to remove the event listener from the popup so that you'll not leak the instance.
private function NewHighScore():void{
    highScorePopup = PopUpManager.createPopUp(this, Popup, true) as Popup;
    highScorePopup.SetScore(playerscore);
    PopUpManager.centerPopUp(highScorePopup);
    highScorePopup.addEventListener(Event.REMOVED_FROM_STAGE,getPlayerName);
}
function getPlayerName(event:Event):void {
    event.target.removeEventListener(Event.REMOVED_FROM_STAGE,getPlayerName);
    var popup:Popup=event.target as Popup;
    if (!popup) return;
    var playerName:String=popup.getName(); // now the name will be populated
    // do stuff with the name
}


Q: Record video using screenrecord error I am trying to use the adb shell screenrecord functionality on my S4 which is running 4.4. I keep getting this error
ERROR: unable to configure codec (err=-2147483648)
WARNING: failed at 1080x1920, retrying at 720x1280
Yes the video eventually gets recorded in the lower resolution. How can I record it in the highest resolution possible (even if you can suggest another method)?
Thank you


Q: Where to store value for duration of request Preamble
I'm developing a card game server in Rails. The application records what a player is expected to do via a tree of instances of the PendingAction model.
class Player < ActiveRecord::Base
  has_many :cards
  has_many :pending_actions
end

At any time, the player needs to act on any leaf PendingActions - there may be more than one, for instance:
1. End turn
|
+- 2. Do thing A
|  |
|  + 3. Do thing pre-A
|
+- 4. Do thing B
   |
   + 5. Do thing pre-B

The view code presents the player with one or more forms, requesting their choice for each leaf action. For instance, in the above case, forms would be presented to solicit input for actions 3 and 5.
When the player makes a choice for, say, action 5, that action is destroyed. However, processing their choice may cause them to need to make another choice before the parent (action 4) can happen. Like so:
1. End turn
|
+- 2. Do thing A
|  |
|  + 3. Do thing pre-A
|
+- 4. Do thing B
   |
   + 6. Do other thing pre-B

Action 4 therefore needs to be on-hand, so action 6 can be created as its child. At present, I am simply passing action 4 around as a function argument. However, I've just come across a situation where it would really help to be able to have access to it in a before_save hook on a Card object.
Question
Where is the best place to store an object, associated with a Player, that I can access from all models related to that Player, which is valid throughout - but not beyond - a single HTTP request?
I am running under Heroku, with 1 dyno - so I believe I'm single-threaded.

A: It depends on which environment you work, but lets assume that this is single-threaded environment. Next, first thought was to create instance attribute to manually assign and retrieve anything. It is will work fine when Player instance is the same for all places.
If not, I suggest to introduce class variable, some sort of cache, that will hold Player#id => <some_obj> reference, and with helper accessors, like Player#some_obj which will query Player for object by self.id.
That way you will be ensured that for all Player with the same Id, some_obj will be the same. Also, you will need to deside, when to empty that class-cache. For Rails, i suppose after_filter is good enough.


Q: The portals keep teleporting me back and forth I have a simple c# script to teleport me between two portals. The problem is that when I place the portals facing down, it keeps teleporting me between them. the script works fine when it is upright. I tried to make a cooldown so that it can't teleport me over and over. I also tried to place the destination above the portal.
Here is my code:
using UnityEngine;

public class portal : MonoBehaviour
{
    public GameObject portal2;
    public GameObject player;

    void OnTriggerEnter(Collider other)
    {
        if (player.transform.position != portal2.transform.position)
        {
            if(other.CompareTag("Player"))
            {
                player.transform.position = portal2.transform.position;
            }
        }
    }
}

A: Comparing the transform positions is not likely to be useful as even a tiny amount of offset in the float (think something as small as 0.0000001 will cause the condition to fail. I would suggest that when a player portals through to another portal, that you place them slightly in front of the portal, in addition to a small cooldown that prevents portal travel. You'll need to translate the players speed (not velocity, speed) to the direction (transform.forward) of the portal they exited as well to keep them moving in the right direction.


Q: How to hold the dynamic text box and its values after form submission fails I am using three dynamic textboxes in a form ,my problem is that when the form validation fails then i have to keep the user in that form ,Now my problem is that i  have to hold the values and those textbox also in the form ,how this is possible ?? i am giving a fiddle please suggest what can be done,
DEMO FIDDLE
Here is the fiddle
function GetDynamicTextBox(value) {
   return '<input class="txt1" name="DynamicTextBox" type="text" value="' + value + '" /> <input class="txt2 time" id="myPicker" class="time" type="text" /> <input name="phoneNum1" id="phoneNum1" class="time txt3"  type="text" /><input type="button" value="Remove" class="remove" />';
}

This is the code which is responsible for the creating dynamic textboxes


Q: capistrano symlink permission denied I am using cap deploy to deploy to staging. cap deploy:setup created the releases and shared folder.
This is the deploy.rb code.
set :stages, %w(staging production)
set :default_stage, "staging"
set :stage_dir, "capistrano"
require 'capistrano/ext/multistage'

set :application, "application"
set :repository,  "git@github.com:owner/#{application}.git"
set :scm, :git

set :local_user, ENV['USER'] || ENV['USERNAME'] || "unknown"
set :user, "server_owner"

set :deploy_via, :copy

set :use_sudo, false
set :copy_remote_dir, "/home/#{user}/tmp/capistrano"

namespace :deploy do
  desc "Change Permissions"
  task :change_permissions, :except => { :no_release => true } do
    run "find #{current_path}/ -type d -exec chmod 755 {} \\;"
    run "find #{current_path}/ -type f -exec chmod 644 {} \\;"
  end

  desc "Create symlinks for shared items"
  task :update_shared_symlinks, :except => { :no_release => true} do
     < ln -s command to create the links>
  end
end

before "deploy:finalize_update", "deploy:update_shared_symlinks"

And this is the staging code
role :app, "ipaddress"

set :branch, "staging"

set :deploy_to, "/home/#{user}/_#{application}_beta/"

When deploying with cap deploy i get the following error
ln: creating symbolic link `/home/narayan/_instaprint_beta/releases/20130130102815/': Permission denied
Can anyone tell me why this is happening?

A: Two things:

*

*Use chmod straight away instead of a find and exec, like so: chmod 755 #{current_path}

*Check if the server_owner user has permission to current_path. If not, then use sudo like so: sudo "chmod 755 #{current_path}"


Q: Firefox driver for selenium where to download the firefox driver for selenium?
I only find this, and herer is not the driver file for download
https://code.google.com/p/selenium/wiki/FirefoxDriver
NOTE: I already have Selenium Webdriver IDE for Firefox but the script aks me to find firefox driver
Can I use firefox in for webdriver in C# or its only capable for java?

A: The best approach for C# projects is to install the WebDriver NuGet, because if there are any updates it will be notified. Just install NuGet Manager and search for WebDriver.
After that just use the following code:
IWebDriver driverOne = new FirefoxDriver();
IWebDriver driverTwo = new InternetExlorerDriver("C:\\PathToMyIeDriverBinaries\");

The FirefoxDriver is included in the NuGet. However, you need to download manually the ChromeDriver from here: https://code.google.com/p/selenium/wiki/ChromeDriver
You can find ten mins tutorial with images here:
http://automatetheplanet.com/getting-started-webdriver-c-10-minutes/

A: You just need to include/import driver to your project if you want to use firefox unlike for CHROME you need to store the jar file or Exe to a particular location and then then you just need to call it in your project
demo program
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;

    public class Firefox {

         public void returnFirefoxBrowser(){
             WebDriver driver = new FirefoxDriver();
        }
    }

chrome
         File file = new File(
              "//Users//Documents//workspace//SELENIUM//chromedriver");
         System.setProperty("webdriver.chrome.driver",file.getAbsolutePath());
         WebDriver driver_chrome;
         driver_chrome = new ChromeDriver();


Q: Problems with updating Xamarin.Android.Support.Annotations 28.0.0 After New Years are over I'm at the office again and started to update the packages of my Xamarin project, that I wrote over the last two months.
I got the error:
Could not install package 'Xamarin.Android.Support.Annotations 28.0.0'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.6.2', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

What do I have to do, to handle the error?


Q: proving strong induction in coq from scratch I am in the middle of proving the equivalence of weak and strong induction.
I have a definition like:
Definition strong_induct (nP : nat->Prop) : Prop :=
  nP 0 /\
  (forall n : nat,
    (forall k : nat, k <= n -> nP k) ->
    nP (S n))
.

And I would like to prove the following, and wrote:
Lemma n_le_m__Sn_le_Sm : forall n m,
  n <= m -> S n <= S m
.

Lemma strong_induct_nP__nP_n__nP_k : forall (nP : nat->Prop)(n : nat),
  strong_induct nP -> nP n ->
  (forall k, k < n -> nP k)
.
Proof.
  intros nP n [Hl Hr].
  induction n as [|n' IHn].
  - intros H k H'. inversion H'.
  - intros H k H'.
    inversion H'.
    + destruct n' as [|n''] eqn : En'.
      * apply Hl.
      * apply Hr.
        unfold lt in IHn.
        assert(H'' : nP (S n'') -> forall k : nat, k <= n'' -> nP k). {
          intros Hx kx Hxx.
          apply n_le_m__Sn_le_Sm in Hxx.
          apply IHn.
          - apply Hx.
          - apply Hxx.
        }

However I cannot continue the proof any further.
How can I prove the lemma in this situation?

A: Changing the place of forall in the main lemma makes it much easier to prove. I wrote it as follow:
Lemma strong_induct_is_correct : forall (nP : nat->Prop),
  strong_induct nP -> (forall n k, k <= n -> nP k).

(Also note that in the definition of strong_induct you used <= so it's better to use the same relation in the lemma as I did.)
So I could use the following lemma:
Lemma leq_implies_le_or_eq: forall m n : nat,
  m <= S n -> m <= n \/ m = S n.

to prove the main lemma like this:
Proof.
  intros nP [Hl Hr] n.
  induction n as [|n' IHn].
  - intros k Hk. inversion Hk. apply Hl.
  - intros k Hk. apply leq_implies_le_or_eq in Hk.
    destruct Hk as [Hkle | Hkeq].
    + apply IHn. apply Hkle.
    + rewrite Hkeq. apply Hr in IHn. apply IHn.
Qed.

This is much a simpler proof and also you can prove a prettier lemma using the lemma above.
Lemma strong_induct_is_correct_prettier : forall (nP : nat->Prop),
  strong_induct nP -> (forall n, nP n).
Proof.
  intros nP H n.
  apply (strong_induct_is_correct nP H n n).
  auto.
Qed.

Note: Usually after using a destruct or induction tactic once, it is not very helpful to use one of them again. So I think using destruct n' after induction n would not bring you any further.


Q: iOS Example (GLSprite) doesnt show anything i implemented the iOS example (GLSprite) for drawing images
but it doesnt show anything. the NSLogs say me, that everything
is initialized, so i dont know, why nothing is shown.
i want to load a png file and to rotate it.

*

*context loads

*framebuffer creates

*setupView finishes

*drawView finishes

No Errors. Everything seem to work fine except this black screen :)
Does anybody knows why?
h-file
#import <Foundation/Foundation.h>
#import <OpenGLES/ES1/gl.h>
#import <OpenGLES/ES1/glext.h>

@interface CJTEAGLView : UIView
{
GLint backingWidth;
GLint backingHeight;

EAGLContext *context;

GLuint viewRenderbuffer;
GLuint viewFramebuffer;
GLuint viewDepthRenderbuffer;

GLuint playerTexture;

BOOL animating;
BOOL displayLinkSupported;

NSInteger animationFrameInterval;

id displayLink;
}

@property (nonatomic) BOOL animating;
@property (nonatomic) NSInteger animationFrameInterval;

- (void)startAnimation;
- (void)stopAnimation;
- (void)drawView;

@end

m-file
@interface CJTEAGLView()
- (void)createFramebuffer;
 - (void)destroyFramebuffer;
- (void)setupView;

@end

const GLfloat spriteVertices[] =
{
-0.5f, -0.5f,
0.5f, -0.5f,
-0.5f,  0.5f,
0.5f,  0.5f,
};

const GLshort spriteTexcoords[] =
{
0, 0,
1, 0,
0, 1,
1, 1,
};

@implementation CJTEAGLView

@synthesize animating;
@synthesize animationFrameInterval;

+ (Class) layerClass
{
return [CAEAGLLayer class];
}

- (id)initWithCoder:(NSCoder*)coder
{
if(self = [super initWithCoder:coder])
{
    CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.layer;

    eaglLayer.opaque = YES;
    eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:
                                    [NSNumber numberWithBool:FALSE], kEAGLDrawablePropertyRetainedBacking, kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat, nil];

    context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1];

    if(!context || ![EAGLContext setCurrentContext:context])
    {
        NSLog(@"Context failed");

        [self release];

        return nil;
    }

    animating = FALSE;
    displayLinkSupported = TRUE;
    animationFrameInterval = 1;
    displayLink = nil;

    [self createFramebuffer];
    [self setupView];
    [self drawView];
}

return self;
}

- (void)layoutSubviews
{
[EAGLContext setCurrentContext:context];

[self destroyFramebuffer];
[self createFramebuffer];
[self drawView];
}

- (void)createFramebuffer
{
glGenFramebuffersOES(1, &viewFramebuffer);
glGenRenderbuffersOES(1, &viewRenderbuffer);

glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
[context renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:(id<EAGLDrawable>)self.layer];
glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, viewRenderbuffer);

glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth);
glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight);
}

- (void)destroyFramebuffer
{
glDeleteFramebuffers(1, &viewFramebuffer);
glDeleteRenderbuffers(1, &viewRenderbuffer);
glDeleteRenderbuffers(1, &viewDepthRenderbuffer);
}

- (NSInteger) animationFrameInterval
{
return animationFrameInterval;
}

- (void) setAnimationFrameInterval:(NSInteger)frameInterval
{
if (frameInterval >= 1)
{
    animationFrameInterval = frameInterval;

    if (animating)
    {
        [self stopAnimation];
        [self startAnimation];
    }
}
}

- (void) startAnimation
{
if (!animating)
{
    if (displayLinkSupported)
    {
        displayLink = [NSClassFromString(@"CADisplayLink") displayLinkWithTarget:self selector:@selector(drawView)];
        [displayLink setFrameInterval:animationFrameInterval];
        [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    }

    animating = TRUE;
}
}

- (void)stopAnimation
{
if (animating)
{
    if (displayLinkSupported)
    {
        [displayLink invalidate];
        displayLink = nil;
    }

    animating = FALSE;
}
}

- (void)setupView
{
CGImageRef playerImage;
CGContextRef playerContext;
GLubyte *playerData;
size_t playerWidth;
size_t playerHeight;

glViewport(0, 0, backingWidth, backingHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrthof(-1.0f, 1.0f, -1.5f, 1.5f, -1.0f, 1.0f);
glMatrixMode(GL_MODELVIEW);
glClearColor(0, 0, 0, 1);

playerImage = [UIImage imageNamed:@"Cruiser.png"].CGImage;
playerWidth = CGImageGetWidth(playerImage);
playerHeight = CGImageGetHeight(playerImage);

if(playerImage)
{
    playerData = (GLubyte *) calloc(playerWidth * playerHeight * 4, sizeof(GLubyte));
    playerContext = CGBitmapContextCreate(playerData, playerWidth, playerHeight, 8, playerWidth * 4, CGImageGetColorSpace(playerImage), kCGImageAlphaPremultipliedLast);
    CGContextDrawImage(playerContext, CGRectMake(0, 0, (CGFloat)playerWidth, (CGFloat)playerHeight), playerImage);
    CGContextRelease(playerContext);

    glGenTextures(1, &playerTexture);
    glBindTexture(GL_TEXTURE_2D, playerTexture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, playerWidth, playerHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, playerData);

    free(playerData);

    glEnable(GL_TEXTURE_2D);
    glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_BLEND);
}
}

- (void)drawView
{
[EAGLContext setCurrentContext:context];

glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
glRotatef(3.0f, 0.0f, 0.0f, 1.0f);

glClear(GL_COLOR_BUFFER_BIT);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
[context presentRenderbuffer:GL_RENDERBUFFER_OES];
}

@end


Q: How do I read time in min/hr in a dataframe get sales rate? I have a data frame which has hours in min for example 14:59 where 60:00 (max) is 1 (hr).
I tried reading this dataframe using the code below I got an error "Can only use .dt accessor with datetimelike values"
df['time sold'].dt.minute

My hope was after reading the date below to get the sale rate per min.
my data is
Name Sales Time
Jame 603   14:59
Sam  903   34:00
Lee  756   34:55

Is there a way to get how much each sold be the minute?
Name Sales Time    Sale Rate
Jame 603   14:59   xxxx
Sam  903   34:00   yyyy
Lee  756   34:55   zzzz

Please excuse the xyz just used them as place holders.

A: first add the HH to be able to convert it to a pandas timedelta:
df['Time'] = '00:'+df['Time'].astype(str)

then convert to timedelta
df['Time'] = pd.to_timedelta(df['Time'])

then make a new column equal to sales per minute
df['Sales Rate'] = df['Sales'] / (df['Time'].dt.total_seconds()/60)

output:
     Sales     Time Sales Rate
Jame   603 00:14:59    40.2447
Sam    903 00:34:00    26.5588
Lee    756 00:34:55    21.6516

A: You could do the following if you have datetime dtype in time column:
s = '''Name Sales Time
       Jame 603   14:59
       Sam  903   34:00
       Lee  756   34:55'''

df = (pd.read_csv(io.StringIO(s),
                  sep='\s+',
                  converters={'Time':lambda x: pd.to_datetime(x, format='%M:%S')})
      )

df['rate'] = df['Sales'] / (df['Time'].dt.minute + df['Time'].dt.second.div(60))


Q: JQuery UI add to accordion Here is the demo for the JQuery UI's accordion widget. I have one on my page, and the way to put items in it (as shown on the demo page) is like so:

Section 1

    Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer
    ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit
    amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut
    odio. Curabitur malesuada. Vestibulum a velit eu ante scelerisque vulputate.

Section 2

    Sed non urna. Donec et ante. Phasellus eu ligula. Vestibulum sit amet
    purus. Vivamus hendrerit, dolor at aliquet laoreet, mauris turpis porttitor
    velit, faucibus interdum tellus libero ac justo. Vivamus non quam. In
    suscipit faucibus urna.

Section 3

    Nam enim risus, molestie et, porta ac, aliquam ac, risus. Quisque lobortis.
    Phasellus pellentesque purus in massa. Aenean in pede. Phasellus ac libero
    ac tellus pellentesque semper. Sed ac felis. Sed commodo, magna quis
    lacinia ornare, quam ante aliquam nisi, eu iaculis leo purus venenatis dui.

List item one

List item two

List item three

Section 4

    Cras dictum. Pellentesque habitant morbi tristique senectus et netus
    et malesuada fames ac turpis egestas. Vestibulum ante ipsum primis in
    faucibus orci luctus et ultrices posuere cubilia Curae; Aenean lacinia
    mauris vel est.

    Suspendisse eu nisl. Nullam ut libero. Integer dignissim consequat lectus.
    Class aptent taciti sociosqu ad litora torquent per conubia nostra, per
    inceptos himenaeos.

Notice how for every item, there is the following structure:
Title

Text

. I would like to be able to dynamically add to this accordion; however, when I tried to simply add that structure to the accordion it didn't work. I looked into my chrome console, and saw that JQuery adds all sorts of classes and properties to the bare-looking elements of the item. Now, of course the obvious way to solve this is instead of adding
Title
 to add

Title

And likewise for every other element. I know that this should work fine, but it looks ugly and I was wondering if JQuery has provided us with some nice function to do all this stuff for us. If it hasn't, can anyone suggest a less annoying way to do this?
EDIT: in response to all the answers suggesting to recreate the accordion: I know that that is probably a better idea than the method shown above, but is it possible to "accordion" only the block of HTML that I need as opposed to the whole accordion, which can get quite big?

A: Just recreate the accordion when you add new data to it:
$("#accordion").append(html).accordion('destroy').accordion();

A: The only critical HTML is the main structure:

Section 1

Section 2

You can put anything you want inside the DIV content panels.
WHen you add a a new set of h3 and div, destroy and recreate the accordion:
var newPanel='
New section

New content
';
$('#accordion').append(newPanel).accordion('destroy').accordion( /* options */ );


Q: Many to many hibernate mapping and intermediate table object How can I define  a many to many relationship in hibernate where the intermediate table maps to a object? I.e.
Build can have another build as dependency and this dependency can be selected in other builds too. The 'build dependency' object should look something like:
BuildDep{
   int id;
   Build parent;
   Build child;
   ....
}

mapping to the intermediate table having columns:
id, child_build_id, parent_build_id

Thank you

A: By definition, many-to-many associations can only be used when the association table does not have any other columns besides the foreign keys to the parent tables.
Instead, you should use two ManyToOne/OneToMany associations.
Here's a forum topic on this subject (with an example):
http://www.coderanch.com/t/218431/ORM/databases/Hibernate-Annotations-many-many-association


Q: Get text of a clicked button? Hi I am very new to java and android studio. I made a set of buttons in a fragment and used a for loop to set the text of each button....
For example:
for (int i = 0; i < letterBttns.length; i++) {
    letterBttns[i].setText(ethereal[i]);
}

What is the best way to get the text of a clicked button? Is there a short way to do it or the only way to do it is calling an onClick method for each button?
Because that seems like the long and easy way.

A: public class TestActivity extends AppCompatActivity implements View.OnClickListener {
    .....
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ....
        for (int i = 0; i < letterBttns.length; i++) {
            letterBttns[i].setOnClickListener(this);
        }
    }

    @Override
    public void onClick(View v) {
        String text = ((Button) v).getText().toString();
    }
}


Q: How to write a spirial function in python? I'm trying to write a function in python that takes two arguments (x,y), and returns an angle in degrees in a spiraling direction.
Suppose the center of the spiral is at location (x0,y0). Then given (0,0), it returns 45. Given some other point say (0,90) which is the second intersection from the top on the y axis, the angle is around 170. For any point not touching the red line, it should return an angle of what you would expect the direction to be. The spiral is just a general thing to show the direction of the angles.
Does anyone know how to write such a function?
Thanks

A: That's an Archimedean spiral curve. As the page says in polar coordinates the formula of the curve is r = aθ, usually the scalar a is 1 i.e. r = θ. Polar to cartesian conversion is
x = r cos θ, y = r sin θ

Hence
x = θ cos θ, y = θ sin θ

Varying θ from 0 to 6π would give the curve you've. When you vary the parameter θ and get x and y values what you get would be relative to the origin (0, 0). For your case, you've to translate i.e. move the points by the x and y offset to position it accordingly. If you want a bigger version of the same curve you've to scale (before translation) i.e. multiply both x and y values by a constant scalar.

A: (I think the spiral image is more confusing than helpful...)
for a point (x, y), you want to get back the angle theta in degrees, where (1,0) is at 0 degrees and (0, 1) is at 90 degrees.
So we want to find theta. Using trigonometry, we know that x is the adjacent side and y is the opposite side, and tan(theta) == y/x.
This is slightly confused by the fact that tan() repeats every 180 degrees - tan(y/x) == tan(-y/-x). Luckily, Python has a built-in function, atan2, that compensates for that. It returns theta in radians, and we convert that to degrees, like so:
from math import atan2, degrees

x, y = (2, 2)
theta = degrees(atan2(y, x))   # => theta == 45.0

however atan2 returns values in -2*pi < theta <= 2*pi (-179.9... to +180 degrees); you want it in (0.. 359.9...) degrees:
theta = (degrees(atan2(y, x)) + 360.0) % 360.0

A: You want a vector field where one of the trajectories is the Archimedean spiral.
If you take the spiral formula

x = θ cos θ, y = θ sin θ

from the answer of legends2k and compute its tangent, you get

vx = cos θ - θ sin θ, vy = sin θ + θ cos θ

Elimination of θ for x and y in the most straightforward way gives the general vector field

vx = x/r-y, vy = y/r + x, where r=sqrt(x^2+y^2).

The angle of the vector field is then obtained as atan2(vy,vx).

A: If someone could verify this I'd appreciate it.
This solution allows you to have a radius which grows at a different rate then the angle
radius:
r(t) = r_scalar * t
d(r(t))/dt = r_scaler

degrees:
a(t) = a0 + a_scalar * t
d(a(t))/dt = a_scaler

location:
x(t),y(t) = x0 + r(t)*cos(a(t)), y0 + r(t)*sin(a(t))

Now we can compute the direction of any t as:
d(x(t))/dt = r(t)*(-sin(a(t))*d(a(t))/dt) + d(r(t))/dt*cos(a(t))
d(y(t))/dt = r(t)*(cos(a(t))*d(a(t))/dt) + d(r(t))/dt*cos(a(t))

which simplifies:
d(x(t))/dt = r(t)*(-sin(a(t))*a_scaler) + r_scaler*cos(a(t))
d(y(t))/dt = r(t)*(cos(a(t))*a_scaler) + r_scaler*sin(a(t))

to get the a value of t for a,b such that it is closest to x(t),y(t). you can first approximate saying the distance x0,y0 to x1,y1 will satisfy r(t).
t0 = sqrt((x0 - x2)^2 + (y0 - y1)^2)/r_scalar

seeing that the closest point in the spiral will be at the same degree, adjust t minimally such that the angle is satisfied.. ie
t1 = t0-t2 where atan((y0 - y1)/(x0 - x2)) = (a0 + a_scalar * t0) % 2*pi - (a0 + a_scalar * t2)

thus
t2 = (((a0 + a_scalar * t0) % 2*pi) - atan((y0 - y1)/(x0 - x2)) + a0)/a_scalar

then the closest direction angle is atan((d(x(t0-t2))/dt / d(y(t0-t2))/dt))

A: import numpy as np
import matplotlib.pyplot as plt
import math

def fermat_spiral(dot):
    data=[]
    d=dot*0.1
    for i in range(dot):
        t = i / d * np.pi
        x = (1 +  t) * math.cos(t)
        y = (1 +  t) * math.sin(t)
        data.append([x,y])
    narr = np.array(data)
    f_s = np.concatenate((narr,-narr))
    return f_s

f_spiral = fermat_spiral(20000)
plt.scatter(f_spiral[len(f_spiral)//2:,0],f_spiral[len(f_spiral)//2:,1])
plt.scatter(f_spiral[:len(f_spiral)//2,0],f_spiral[:len(f_spiral)//2,1])
plt.show()


Q: How to tell when AxWindowsMediaPlayer is downloading? I am using AxWindowsMediaPlayer on VB.NET to preview MP3 files from the web so that the user can choose to download it if he likes it. It works. I just put a link in the URL property and after a while it begins playing.
... after a while, of course. Because it has to download the file first. Perhaps I realized that because of my slow connection XD.
But that made me think: how can I tell if the player is currently downloading a file? So that I can put a label saying "Please wait, preparing file..." or something.

A: Look at using the Buffering Event and the BufferingProgress Property. According to the MSDN Link:

Use this event to determine when buffering or downloading starts or stops. You can use the same event block for both cases and test IWMPNetwork.bufferingProgress and IWMPNetwork.downloadProgress to determine whether Windows Media Player is currently buffering or downloading content.


Q: Android: Issue creating Custom 3 state toggle button I'm trying to create a 3 state toggle button by overriding the Button class.
Although, there is no error in the code, but Eclipse is showing following issue in layout xml.
The following classes could not be instantiated:
- com.example.threewaytoggle.TriToggleButton (Open Class, Show Error Log)
See the Error Log (Window > Show View) for more details.
Tip: Use View.isInEditMode() in your custom views to skip code when shown in Eclipse

And in the error log, this is coming:
com.example.threewaytoggle.TriToggleButton failed to instantiate.

java.lang.NullPointerException
at android.view.View.mergeDrawableStates(View.java:7506)
at com.example.threewaytoggle.TriToggleButton.onCreateDrawableState(TriToggleButton.java:42)
at android.view.View.getDrawableState(View.java:7410)
at android.view.View.setBackgroundDrawable(View.java:7583)....

Following is the code:
Layout xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <com.example.threewaytoggle.TriToggleButton
        android:id="@+id/triToggleButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TriToggleButton" />
</LinearLayout>

Custom Button Class:
package com.example.threewaytoggle;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.Button;

public class TriToggleButton extends Button {

    int _state = 0;
    public TriToggleButton(Context context) {
        super(context);
        _state = 0;
        this.setText("1");
    }

    public TriToggleButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        _state = 0;
        this.setText("1");
    }

    public TriToggleButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        _state = 0;
        this.setText("1");
    }

    private final int[] STATE_ONE_SET = { R.attr.state_one };
    private final int[] STATE_TWO_SET = { R.attr.state_two };
    private final int[] STATE_THREE_SET = { R.attr.state_three };

    @Override
    protected int[] onCreateDrawableState(int extraSpace) {
        final int[] drawableState = super.onCreateDrawableState(extraSpace + 3);

        if (_state == 0) {
            mergeDrawableStates(drawableState, STATE_ONE_SET);
        } else if (_state == 1) {
            mergeDrawableStates(drawableState, STATE_TWO_SET);
        } else if (_state == 2) {
            mergeDrawableStates(drawableState, STATE_THREE_SET);
        }

        return drawableState;
    }

    @Override
    public boolean performClick() {
        nextState();
        return super.performClick();
    }

    private void nextState() {
        _state++;
        if (_state > 2) {
            _state = 0;
        }
        setButtonText();
    }

    private void setButtonText() {
        //TODO
    }

    public int getState() {
        return _state;
    }
}

A: Found it....Only static was missing in:
private static final int[] STATE_ONE_SET = { R.attr.state_one };
private static final int[] STATE_TWO_SET = { R.attr.state_two };
private static final int[] STATE_THREE_SET = { R.attr.state_three };

But how come this creates a problem...?


Q: Cron run my Python script but nothing is happening I want to run a Python script every night at 12:00 am to clean up a csv file which is automatically filled in during the day by another script.
My csv file code_list.csv content looks like this at the end of the day:
87698
63753
19742
89876
62765
79832
# etc.

I use the truncate method to clean the csv file with this script csvclean.py :
import csv

filename = "/root/folder/code_list.csv"
f = open(filename, "w")
f.truncate()
f.close()

and here is my crontab:
SHELL=/bin/bash
0 0 * * * cd /root/folder && /usr/bin/python3 ./csvclean.py

Both files are located in the same folder /root/folder.
I can see in /var/log/syslog that the cron is running at the scheduled time but nothing is happening inside my code_list.csv file. While if I run the script directly using python3 csvclean.py it cleans up the csv file perfectly.
What have I forgotten?
- EDIT -
I used a method found here to retrieve logs.
I edited my crontab like this:
*/1 * * * * cd /root/folder && /usr/bin/python3 ./csvclean.py > /root/folder/csvclean.log 2>&1

and I added this line at the beginning of the csvclean.py script:
print 'starting'

I opened the csvclean.log file after the cron and I saw:
/usr/bin/python3: can't open file './csvclean.py': [Errno 2] No such file or directory

Which made me realize that my Python script file name is cleancsv.py and not csvclean.py.
It was under my eyes...

A: Run this command: sudo /etc/init.d/cron restart
after setting crontab demon has to restart.
Also check sys/log for tracing what is issue while running script.


Q: google maps resize event The problem is start the map hidden, if the toggle buttom start showing the map there isn't any ploblem.
I'm seeing a lot of question with this problem but I can't fix it. This is my code. I call the resize event after toogle the map and doen't work.
$('.map-btn').click(function(){
    $(this).next().toggle(500, function(){
        var gMap = document.getElementById("acf-map");
        google.maps.event.trigger(gMap, 'resize');
    });
})

Related question here Google Maps v3 load partially on top left corner, resize event does not work

A: Form my experience is better recall a (re)initilizeMap() function when you click the tab for show the map.
Due the problem/difficulties related to the correct congfiguration of the map in this case if you, wher click the tab for show the map call the initializzazion of the map. the problem is structurally solved.


Q: Getting a GIT change summary like GitHub I've got a group of developers which make GIT commit and merge mistakes (once in a while).
I would like to monitor for 'large changes' somehow.  I see in GitHub that they have the following line when looking at the details of a specific commit:

Showing 759 changed files with 21,736 additions and 3,237 deletions.

That is an example of a real merge that should have only had 1 file changed and several additions/deletions.
Is there some way or some tool that exists that would send out an alert via email or SMS when a commit breaches a configured threshold?
If not, I was wondering if it was possible to generate that same type of output using the GIT command line.  That way, if no tool exists, I can easily script it and send out an email with my own tools.

Update: 2014-03-20 18:52
Based on nulltoken's suggestion, I've tried the following command:

git diff --shortstat $(git rev-parse HEAD HEAD^)

And got exactly what I needed (for the very last commit anyway).  Oddly enough though, what I just observed is that GitHub (1) provides the following numbers, compared to what my GIT  provides (2):

1 :  759 changed files with 21,736 additions and 3,237 deletions.
2 :  759 files changed, 3237 insertions(+), 21736 deletions(-)

So somebody clearly has a bug!  Either GitHub or my GIT (version 1.7.10.4)... funny!

Update: 2014-03-20 19:05
Correction, I simply inverted my hashes and it fixed it... my mistake!  No bug to report.

A:
if it was possible to generate that same type of output using the GIT command line. That way, if no tool exists, I can easily script it and send out an email with my own tools.

You may be after one of the following options of git diff

*

*git diff --stat <from_commit> <until_commit>

*git diff --shortstat <from_commit> <until_commit>

Those commands, when ran against the LibGit2Sharp project, output the following
$ git diff --stat a4c6c45 14ab41c
 LibGit2Sharp.Tests/StashFixture.cs  |  3 ++-
 LibGit2Sharp/Core/NativeMethods.cs  |  8 +++-----
 LibGit2Sharp/Core/Proxy.cs          | 18 +++++++++---
 LibGit2Sharp/ReferenceCollection.cs |  5 ++++-
 4 files changed, 18 insertions(+), 16 deletions(-)

$ git diff --shortstat a4c6c45 14ab41c
 4 files changed, 18 insertions(+), 16 deletions(-)

You'll note that this is pretty much the same content than from the GitHub page showcasing those changes (Note: Clicking on the "Show Diff Stats" will show the per file counts).


Q: JPQL NEW operator with native query ? Can I use the NEW JPQL operator to map result of query inside DTO ?
I tested this code :
Query query = em.createNativeQuery("SELECT NEW com.sim.dtos.entities.FreeLocation(t1.galaxie, t1.ss, t1.position) FROM ...");

List<FreeLocation> l = query.getResultList();

But I have exception :

[#|2012-12-20T12:9:21.203+0100|WARNING|glassfish3.1.2|javax.enterprise.system.container.web.com.sun.enterprise.web|_ThreadID=79;_ThreadName=Thread-2;|StandardWrapperValve[Faces Servlet]: PWC1406: Servlet.service() for servlet Faces Servlet threw exception
  org.postgresql.util.PSQLException: ERREUR: erreur de syntaxe sur ou près de « . »
    Position : 15

So can I use NEW operator with native query please ?

A: A native query, by definition, is a SQL query. It must contain valid SQL for your specific database.
The query will return a List<Object[]>, and it should be trivial to iterate through the list and create a new instance of FreeLocation for each Object[] array.