text:
Q: In Rails ActiveRecord Migrations, `using:` keyword It's been decided to update certain fields from int to bigint.
Rails can't automatically reverse this kind of migration and so suggests we have to create both an up and a down action along with adding a using:.  The problem is that I honestly can't seem to find documentation on what using: does nor what the suggestion rails makes actually means (beyond what I can infer).
With that in mind, in the following example:

*

*What does using: mean?

*What does the SQL in the String used in as the value of using: mean? (I can infer but I want the actual definition)

class UpdateModelFieldType < ActiveRecord::Migration[5.2]
  def change
    reversible do |dir|
      dir.up do
        change_column :model,
                      :field,
                      :bigint,
                      using: 'field::bigint', algorithm: :concurrently

      end

      dir.down do
        change_column :model,
                      :field,
                      :int,
                      using: 'field::int',
                      algorithm: :concurrently
      end
    end
  end
end

A: Sorry, I can't find anything in the official docs about the :using option but I can tell you what it does and point you at the PostgreSQL documentation instead.
The using: expr option adds a USING clause to the ALTER TABLE statement that gets sent to the database to change the column's type so that you get:
alter table models alter column fields type bigint using 'field::bigint'

instead of just:
alter table models alter column fields type bigint

So what does the USING clause do? The fine manual says:

SET DATA TYPE
  This form changes the type of a column of a table. [...] The optional USING clause specifies how to compute the new column value from the old; if omitted, the default conversion is the same as an assignment cast from old data type to new. A USING clause must be provided if there is no implicit or assignment cast from old to new type.

So the using: expr option tells the database how to convert old column values to values in the new type.
Now what does field::bigint mean? That's a PostgreSQL-specific type cast. The standard SQL version would be cast(field as bigint).


text:
Q: Why spring boot is loading another component even though i am not importing explicitly? I'm not using @import annotation though context is able to load the bean (SalesService) it should throw the exception find the code.
@SpringBootApplication
public class App {

    public static void main(String[] args) {
        ApplicationContext context = (ApplicationContext) SpringApplication.run(CustomerConfig.class);
        CustomerService customer = (CustomerService) context.getBean("customerBean");
        customer.printMessage("setting message for CustomerService");
        SalesService sales = (SalesService)context.getBean("salesBean");
        sales.printMessage("setting message for SalesService");
    }

}

A: The Anntotation @SpringBootApplication does a @ComponentScan on the package off the annotated class.
This means that every @Component,@Controller, @Service in the same or subpacke gets instantiated.
Have a look here.
You can controll it by providing attributes to `@SpringBootApplication'.
Docs

redpajama_set_name: RedPajamaStackExchange


text:
Q: Increasing angle of rotation around center with sin and cos Canvas Js Hy everyone,
i'm making some little exercices in canvas with sin and cos. I can now make a point rotating around another one with the angle incrementation in the animate function it work, like in the code below. My purpose is to put angle incrementation in the update function of the Class viefinder

const canvas= document.getElementById('canvas');
const c= canvas.getContext("2d");

canvas.width= window.innerWidth;
canvas.height= window.innerHeight;

let angle=0;
const r=200;

/* -------------------------------------------------------------------------- */
/*                                 View Finder                                */
/* -------------------------------------------------------------------------- */

class ViewFinder {
  constructor(x,y,radius,color){
      this.x=x;
      this.y=y;
      this.radius=radius;
      this.color=color
      this.r= r;
      this.angle=angle;
      this.dx = this.r * Math.cos(this.angle);
      this.dy= this.r * Math.sin (this.angle);

  }
  draw(){
        //point 1
        c.beginPath()
        c.arc(this.x,this.y,this.radius, 0, Math.PI *2,false )
        c.fillStyle=this.color;
        c.fill();
        //point 2
        c.beginPath();
        c.arc(this.x + this.dx, this.y + this.dy,this.radius,0, Math.PI * 2, false );
        c.fillStyle=this.color;
        c.fill();
  }
  update(){
      this.draw();
  }

}

/* -------------------------------------------------------------------------- */
/*                                   Animate                                  */
/* -------------------------------------------------------------------------- */

let animationId;

function animate(){
   animationId= requestAnimationFrame(animate);
   c.fillStyle='rgba(0, 0, 0, 0.5)';
   c.fillRect(0,0,canvas.width,canvas.height);
   // calculate velocity
   viewFinder = new ViewFinder (canvas.width/2, canvas.height/2, 40, 'white');
   angle +=0.1/2;
   viewFinder.update();
}

animate();
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body style="height: 100vh;">
    <canvas id="canvas"></canvas>
    <script src="main.js"></script>
</body>
</html>

So if i do the same but i put angle incrementation in the update function nothing move.. just try to understand why many thanks for yours answers

const canvas= document.getElementById('canvas');
const c= canvas.getContext("2d");

canvas.width= window.innerWidth;
canvas.height= window.innerHeight;

let angle=0;
const r=200;

/* -------------------------------------------------------------------------- */
/*                                 View Finder                                */
/* -------------------------------------------------------------------------- */

class ViewFinder {
  constructor(x,y,radius,color){
      this.x=x;
      this.y=y;
      this.radius=radius;
      this.color=color
      this.r= r;
      this.angle=angle;
      this.dx = this.r * Math.cos(this.angle);
      this.dy= this.r * Math.sin (this.angle);

  }
  draw(){
        //point 1
        c.beginPath()
        c.arc(this.x,this.y,this.radius, 0, Math.PI *2,false )
        c.fillStyle=this.color;
        c.fill();
        //point 2
        c.beginPath();
        c.arc(this.x + this.dx, this.y + this.dy,this.radius,0, Math.PI * 2, false );
        c.fillStyle=this.color;
        c.fill();
  }
  update(){
      this.draw();
      this.angle +=0.1;
  }

}

/* -------------------------------------------------------------------------- */
/*                                   Animate                                  */
/* -------------------------------------------------------------------------- */

let animationId;

function animate(){
   animationId= requestAnimationFrame(animate);
   c.fillStyle='rgba(0, 0, 0, 0.5)';
   c.fillRect(0,0,canvas.width,canvas.height);
   // calculate velocity
   viewFinder = new ViewFinder (canvas.width/2, canvas.height/2, 40, 'white');
   viewFinder.update();
}

animate();
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body style="height: 100vh;">
    <canvas id="canvas"></canvas>
    <script src="main.js"></script>
</body>
</html>

A: The issue is:
In the first example, you are updating the global variable angle, but in the second you are updating this.angle,
In the first case, you are recreating the object viewFinder each frame, and since the value of angle is changed, the values of both dx & dy are re-calculated for the new object.
However, in the second case you are also recreating the object viewFinder, which uses the global variable angle to set the new angle and dx and dy
but you are not updating the angle anymore, which makes the element look static,
To fix this:

*

*don't recreate the object for each frame, create it once and update it for each frame.

*update the value of dx and dy after updating the value of this.angle
your code will look something like:
const canvas = document.getElementById('canvas')
const c = canvas.getContext('2d')

canvas.width = window.innerWidth
canvas.height = window.innerHeight

let angle = 0
const r = 200

/* -------------------------------------------------------------------------- */
/*                                 View Finder                                */
/* -------------------------------------------------------------------------- */

class ViewFinder {
  constructor(x, y, radius, color) {
    this.x = x
    this.y = y
    this.radius = radius
    this.color = color
    this.r = r
    this.angle = angle
    this.dx = this.r * Math.cos(this.angle)
    this.dy = this.r * Math.sin(this.angle)
  }
  draw() {
    //point 1
    c.beginPath()
    c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false)
    c.fillStyle = this.color
    c.fill()
    //point 2
    c.beginPath()
    c.arc(
      this.x + this.dx,
      this.y + this.dy,
      this.radius,
      0,
      Math.PI * 2,
      false
    )
    c.fillStyle = this.color
    c.fill()
  }
  update() {
    this.draw()
    this.angle += 0.1
    this.dx = this.r * Math.cos(this.angle)
    this.dy = this.r * Math.sin(this.angle)
  }
}

/* -------------------------------------------------------------------------- */
/*                                   Animate                                  */
/* -------------------------------------------------------------------------- */

let animationId

let viewFinder = new ViewFinder(canvas.width / 2, canvas.height / 2, 40, 'white')
function animate() {
  animationId = requestAnimationFrame(animate)
  c.fillStyle = 'rgba(0, 0, 0, 0.5)'
  c.fillRect(0, 0, canvas.width, canvas.height)
  // calculate velocity

  viewFinder.update()
}

animate()


text:
Q: replace Column with maximum string length based on frequency count in dataframe I have two columns: freq and newname. I want to replace newname with maximum string length word  based on freq.
Code Which I tried :
    k = df['Newname'].to_list()
    j = list(set(k))
    for row in df.iterrows():
        print(row)
        if row==j[0]:
            df.at[row.Index, 'Newname'] = df['Newname'].value_counts().argmax()
    elif row==j[1]:
        df.at[row.Index, 'Newname'] = df['Newname'].value_counts().argmax()

Input:
 newname  freq
 ASHOK    5
 aSHOK    5
 Ashok    5
 A        5
 Ask      5
 ajay     4
 Ajay     4
 A        4
 Aja      4

Expected output:
newname    freq
Ashok      5
Ashok      5
Ashok      5
Ashok      5
Ashok      5
Ajay       4
Ajay       4
Ajay       4
Ajay       4

A: Hope it helps!
#Get name lengths
df['name_len'] = df['name'].apply(lambda x : len(x))

#Get variables
max_freq = df['freq'].max()
max_len = df['name_len'].max()

#Apply Filters
filter1 = df[df['name_len'] == max_len].reset_index(drop=True)
filter2 = filter1[filter1['freq'] == max_freq].reset_index(drop=True)

#get the target_name
target_name = np.array(filter2.name[0].capitalize())
new_names = target_name.repeat(df.shape[0])

#create new_names
df['new_name'] = new_names
df = df.drop(['name_len', 'name'], axis = 1)

Note:
You have to give weight to either freq or length of the name when you have same freq and name_len.
Before
After

A: df2 = pd.DataFrame(columns=['new_name', 'freq'])
for name,group in df.groupby(['freq']):
    #Get length of the names and max len
    group['name_len'] = group['name'].apply(lambda x : len(x))
    max_len = group['name_len'].max()

    #Apply Filters
    filter1 = group[group['name_len'] == max_len].reset_index(drop=True)

    #get the target_name
    target_name = np.array(filter1.name[0].capitalize())
    new_names = target_name.repeat(group.shape[0])

    #create new_names
    group['new_name'] = new_names
    group = group.drop(['name_len', 'name'], axis = 1)
    print(group)
    df2 = pd.concat([df2, group]).sort_index(axis=0)


text:
Q: TensorFlow Dataset.flat_map() leads to uneven batches Loading my inputs from files containing 10 samples each, and batching them with 4 samples per batch, I get batches of uneven sizes 4, 4, 2, 4, 4, 2, etc., instead of batches combining samples from consecutive files as I expect after flattening the dataset.
I am using TensorFlow 1.8.0. To get data from files into my Dataset object I followed this answer. My input pipeline looks like this:
# Initialize dataset on files
dataset = tf.data.Dataset.list_files(input_files_list)

# Pre-process data in parallel
def preprocess_fn(input_file):
    # lots of logic here...
    return input1, input2, input3

map_fn = lambda input_file: tf.py_func(
    preprocess_fn, [input_file], [tf.float32, tf.float32, tf.float32])
dataset = dataset.map(map_func=map_fn, num_parallel_calls=4)

# Flatten from files to samples
dataset = dataset.flat_map(lambda *x: tf.data.Dataset.from_tensor_slices(x))

dataset = dataset.batch(batch_size=4)
dataset = dataset.prefetch(buffer_size=8)

But what I see is that samples are not actually concatenated between the input files, so that the batch sizes are uneven. I think this is because flat_map() maps each element (all input samples from a file) to a dataset - so after the flat_map() my dataset is actually a dataset of datasets, and each nested dataset is batched separately.
But this is not what I intended. How do I concatenate the nested datasets, or otherwise flatten the dataset so that samples from different files can be batched together?

A: I was having the similar problem with TF 2.0 and I've used unbatch function, like so:
dataset = dataset.flat_map(lambda f: parse_function(f)).apply(tf.data.experimental.unbatch())

I believe in TF 1.8 tf.contrib.data.unbatch could be used.


text:
Q: Ruby Turn string into integer I'm trying to turn strings in my array

values = (1..10).to_a + ["Jack(11)", "Queen(12)", "King(13)", "Ace(14)"]

into an integer, then sort the array with

def straight(hand)
  numbers = hand.each { |card| card.to_i }
  numbers.sort
end

and I keep getting the error

["Jack(11)", 9, 10, "Queen(12)", "Ace(14)"]
5carddraw.rb:58:in `sort': comparison of String with 10 failed (ArgumentError)

can anyone tell me how I can make this work?

A: There are a couple misunderstandings here.
each
each iterates through an array, passing each element to a block, and then returns the array itself. So each does not make any changes to the array (unless you specifically tell it to). Since your block just calls to_i, the end result is numbers == hand:
ary = ["Jack(11)", "Queen(12)", "King(13)", "Ace(14)"]
tmp = ary.each { |card| card.to_i }
p tmp
# ["Jack(11)", "Queen(12)", "King(13)", "Ace(14)"]

So you end up sorting an array containing numbers and strings, which is what your error is complaining about. You want to use map, which returns a new array using the results of the block.
to_i
to_i does very simple conversion from string to integer: if the string starts with some digits (ignoring whitespace), it makes a number out of those digits. If the string doesn't start with digits, it returns 0:
" 1 2".to_i       # 1
"99bottles".to_i  # 99
"match3".to_i     # 0

Since your numbers are in the middle of the strings, you need something more advanced, like a regexp, to extract them:
"Jack(11)"[/\d+/].to_i # 11

A: edit I've wrapped these long lines to make this post easy to read, must copy and paste into irb will suck. Sorry.
 values = ("1".."10").to_a + ["Jack(11)", "Queen(12)", "King(13)",  "Ace(14)"]

returns:
["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack(11)",

"Queen(12)", "King(13)", "Ace(14)"]

But values.sort will give:
["1", "10", "2", "3", "4", "5", "6", "7", "8", "9", "Ace(14)",
 "Jack(11)", "King(13)", "Queen(12)"]

So you can do:
values = ("01".."10").to_a + ["Jack(11)", "Queen(12)", "King(13)", "Ace(14)"]

which will return:
["01", "02", "03", "04", "05", "06", "07", "08", "09", "10",

"Jack(11)", "Queen(12)", "King(13)", "Ace(14)"]

but still values.sort gives:
["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "Ace(14)",

"Jack(11)", "King(13)", "Queen(12)"]

So finally you could do:
values = ("01".."10").to_a + ["(11)Jack", "(12)Queen", "(13)King", "(14)Ace"]

wich gives:
["01", "02", "03", "04", "05", "06", "07", "08", "09", "10",

 "(11)Jack", "(12)Queen", "(13)King", "(14)Ace"]

so you try values.sort and get...
["(11)Jack", "(12)Queen", "(13)King", "(14)Ace", "01", "02", "03",

"04", "05", "06", "07", "08", "09", "10"]

Darn it! Still not working. What does all this tell you? The array you are trying to use is the wrong data structure. Use a Hash and stop trying to sort anything:
values = {one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7,

 eight: 8, nine: 9, ten: 10, jack: 11, queen: 12, king: 13, ace: 14}

def straight(hand)
  numbers = hand.values.sort
end

straight(values)

  #returns => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

Look at all of the methods in the Hash and Enumerable classes. These will give you a huge arsenal of dealing with your hash of card values. Many of these methods will do something that you have already, or probably will do with a larger chunk of code.
As I think about this, I would create a Hash as my dictionary, using strings instead of the written number as I show above:
Values = {"1" => 1, "2" => 2, "3" => 3, "4" => 4, "5" => 5, "6" => 6,
 "7" => 7, "8" => 8, "9" => 9, "10" => 10, "Jack" => 11, "Queen" => 12,
 "King" => 13, "Ace" => 14}

#note we are using a Constant now with "Values". We want to access this anywhere and for it to not change.

Then you can use the strings where you are displaying cards, but when you want to lookup a hand's value you can convert it to a numeric array:
hand = ["2", "4", "10", "Ace", "King"]
def hand_value(hand)
  hand.map { |card| Values[card]}
end
    # => [2, 4, 10, 14, 13]

now you can manipulate the value of the hand any way you want. You can check to see if they are consecutive, sum them up, etc.
To look up a value:
Values["King"] #=> 13

to do the reverse and look up a key:
Values.key(13) #=> "King"


text:
Q: Can mercenaries be self-sufficient for rubies? In Clicker Heroes, the newly added mercenaries have a chance to die on each mission they're assigned. Resurrecting them costs rubies, the amount of which is based on the level of the mercenary.
I have a set of 5 level 1-5 mercenaries, and even though I try to pick missions that reward rubies as often as possible, it feels like a huge ruby sink.
Do mercenaries ever get self-sufficient for rubies as you level them up?

A: The answer is No.
They can be temporarily self-sufficient, but once they reach a high enough level, the ruby cost to revive them grows much faster than their expected income per life.
See here for some guidelines on when it is or isn't worth reviving mercs.


text:
Q: Getting error while mounting nfs with error mount.nfs: Remote I/O error When you are mounting AIX nfs shares, the following error may be obtained:
mount.nfs: Remote I/O error

Aix NFS server with NFSv4 protocol support
This may be due to a misconfiguration of NFSv4 on the Aix NFS server

Aix NFS server without NFSv4 protocol support
To resolve the issue, mount the nfs share with an option vers=3. Eg:

Raw
# mount -o vers=3 server_ip_addr:dir local_mount_point


text:
Q: Comando para definir um valor padrão para uma coluna no SQL Server Olá, desejo saber o comando para definir um valor como default no SQL server.
O nome da tabela é "Tabela" e o nome da coluna que desejo alterar é "COLUNA2".

A: Para definir um valor padrão de uma coluna da tabela você deve utilizar o operador DEFAULT. Você pode informá-lo na criação da sua tabela:
CREATE TABLE tabela (
  id INT NOT NULL PRIMARY KEY,
  coluna1 VARCHAR(100),
  coluna2 INT DEFAULT 1
);

Ou para alterar a coluna:
ALTER TABLE tabela ADD CONSTRAINT coluna2_default DEFAULT 1 FOR coluna2;

Nos exemplos acima o valor 1 será definido na coluna caso não seja informado na inserção:
INSERT INTO tabela(id, coluna1)
            VALUES(1, 'blablabla');

Resultando no registro:
| id  | coluna1   | coluna2 |
| --- | --------- | ------- |
| 1   | blablabla | 1       |

Usar o Transact-SQL para especificar um padrão
Há várias maneiras pelas quais você pode especificar um valor padrão para uma coluna usando o SSMS para enviar o T-SQL.

A: Julio, boa tarde!
Se você já configurou a tabela para ter um valor default na criação da mesma, não há necessidade de passar valor para a coluna quando efetuar o insert.
Exemplo de criação com valor Default:
CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    City varchar(255) DEFAULT 'Sandnes'
);


text:
Q: Issue with returning the last 10 lines of a file in PHP Currently, I have this code to return the last 10 lines in the file: food.txt
<?php
echo `tail /home/food.txt`;

and the output returns something like:
pie apple orange fish lemon peach egg bacon pancake strawberry

The problem is, running the tail command in PHP is ignoring the lines originally in the file food.txt, if I run the same command over SSH, I get:
pie
apple
orange
fish
lemon
peach
egg
bacon
pancake
strawberry

I cannot use PHP to open the file (from my knowledge) because the file will grow pretty large over time and I'm not sure PHP will be able to handle it, and by large, I mean 250,000+ lines.
Thanks.

A: If the problem is missing line breaks (not clear from the question) wrap everything in <pre>.
echo '<pre>';
echo `tail /home/food.txt`;
echo '</pre>';

Edited to add: <pre> will give you a monospace font by default; you can fix that easily with CSS if it's a problem.

A: We can use only one <pre> tag
First
echo '<pre>';
echo 'tail /home/food.txt';

Second
$string = 'tail /home/food.txt';
echo str_replace(" " ,"\n", $string);


text:
Q: When I add an arrow to my circuitikz, the document wont compile I want to make the following diagram of the setup for my project, but when I try to add a powerflow arrow the document wont compile.
code is below
    \begin{circuitikz}[american]
    \draw (0,0)
    % PV Block
    to [short] (0,2.5)
    to [short] (2,2.5)
    to [short] (2,0)
    to [short] (0,0)
    (0,2.5) to [short] (1,1.5)
    to [short] (2,2.5)

    % Lines to DC Boost
    (2,0.75) to [short] (4,0.75)
    (2,1.75) to [short] (4,1.75)
    (3,1.75) to [C] (3,0.75)

    % Boost converter
    (4,0.25) to [short] (4,2.25)
    to [short] (6,2.25)
    to [short] (6,0.25)
    to [short] (4,0.25)
    to [short] (6,2.25)

    %Lines to DC/AC
    (6,0.75) to [short] (10,0.75)
    (6,1.75) to [short] (10,1.75)
    (7,1.75) to [C] (7,0.75)

    % DC/AC
    (10,0.25) to [short] (10,2.25)
    to [short] (12,2.25)
    to [short] (12,0.25)
    to [short] (10,0.25)
    to [short] (12,2.25)

    % Lines to DC/DC Bidrectional
    (7.5,0.75) to [short] (7.5,-0.75)
    (8.5,1.75) to [short] (8.5,1)
    (8.5,0.5) to [short] (8.5,-0.75)
    (8.5,1) to [crossing] (8.5,0.5)

    % Bidirectional DC/DC
    (7,-0.75) to [short] (9,-0.75)
    to [short] (9, -2.75)
    to [short] (7,-2.75)
    to [short] (7,-0.75)
    (9,-0.75) to [short] (7,-2.75)

    % Lines to BESS
    (7.5,-2.75) to [short] (7.5,-3.5)
    (8.5,-2.75) to [short] (8.5,-3.5)

    % BESS
    (7,-3.5) to [short] (9,-3.5)
    to [short] (9, -4.5)
    to [short] (7,-4.5)
    to [short] (7,-3.5)

    % Display names
    (1,0.5) node[align=center]{PV Array}
    (4.5,1.65) node[align=center]{DC}
    (5.5,0.85) node[align=center]{DC}
    (10.5,1.65) node[align=center]{DC}
    (11.5,0.85) node[align=center]{AC}
    (8.5,-2.25) node[align=center]{DC}
    (7.5,-1.25) node[align=center]{DC}
    (8,-4) node[align=center]{BESS}

    % Arrows
    %\draw[-latex] (4,3) -- (6,3);

    \end{circuitikz}

Many thanks for answering

A: I quite don't get why you are manually re-building the blocks of circuitikz (all of them are available), and do so using to[short]... you can just use -- in this case, there is no difference.
Anyway, if you change the last lines of your code into:
[...]
  (8,-4) node[align=center]{BESS}; %<--- Add a semicolon here!

    % Arrows
    \draw[-latex] (4,3) -- (6,3);
[...]

it compiles and gives

MWE:
\documentclass[margin=5mm]{standalone}

\usepackage{circuitikz}
\begin{document}
\begin{circuitikz}[american]
    \draw (0,0)
    % PV Block
    -- (0,2.5) -- (2,2.5) -- (2,0) -- (0,0) (0,2.5) -- (1,1.5) -- (2,2.5)
    % Lines to DC Boost
    (2,0.75) -- (4,0.75) (2,1.75) -- (4,1.75) (3,1.75) to [C] (3,0.75)
    % Boost converter
    (4,0.25) -- (4,2.25) -- (6,2.25) -- (6,0.25) -- (4,0.25) -- (6,2.25)
    %Lines to DC/AC
    (6,0.75) -- (10,0.75) (6,1.75) -- (10,1.75) (7,1.75) to [C] (7,0.75)
    % DC/AC
    (10,0.25) -- (10,2.25) -- (12,2.25) -- (12,0.25) -- (10,0.25) -- (12,2.25)
    % Lines to DC/DC Bidrectional
    (7.5,0.75) -- (7.5,-0.75) (8.5,1.75) -- (8.5,1) (8.5,0.5)
    -- (8.5,-0.75) (8.5,1) to [crossing] (8.5,0.5)
    % Bidirectional DC/DC
    (7,-0.75) -- (9,-0.75) -- (9, -2.75) -- (7,-2.75) -- (7,-0.75)
    (9,-0.75) -- (7,-2.75)
    % Lines to BESS
    (7.5,-2.75) -- (7.5,-3.5) (8.5,-2.75) -- (8.5,-3.5)
    % BESS
    (7,-3.5) -- (9,-3.5) -- (9, -4.5) -- (7,-4.5) -- (7,-3.5)
    % Display names
    (1,0.5) node[align=center]{PV Array}
    (4.5,1.65) node[align=center]{DC}
    (5.5,0.85) node[align=center]{DC}
    (10.5,1.65) node[align=center]{DC}
    (11.5,0.85) node[align=center]{AC}
    (8.5,-2.25) node[align=center]{DC}
    (7.5,-1.25) node[align=center]{DC}
    (8,-4) node[align=center]{BESS};
    % Arrows
    \draw[-latex] (4,3) -- (6,3);
    \end{circuitikz}
\end{document}


text:
Q: Get the right function to send one email to multiple filenames I have a code that will get the filename ready for email but Im wondering if anyone could help me get the right function to send one email to multiple filenames.
Here is the code i have so far.
 <?php
    SELECT filename FROM feedback;
    //you fill the $emails with all the names from the file
    foreach ($filenames as $filename){
    //splitting the string, and take all the characters before the .pdf
    $filename = substr($filename, 0, strrpos($filename, '.pdf'))+"@email.ulster.ac.uk";
    }

?>

A: Ok, whatever you try to by sending emails to an adress built from a filename, just sent it to multiple receivers:
mail('user1@foo.bar; user2@foo.bar', 'topic', 'text');


text:
Q: iphone: floats cast to unsigned ints get set to 0 if they are negative? try it out:
volatile float bob = -344.0f;
unsigned int fred = (unsigned int)bob;

printf("%d\n",fred);

output will be 0.
obviously I am expecting it to wrap around just as if I had cast from a signed int to an unsgined int (which does wrap and act as expected on the iphone)
we assume it is something to do with the floating point settings.
any ideas?

A: §6.3.1.4 of the C standard:

When a finite value of real floating
  type is converted to an integer type
  other than _Bool, the fractional part
  is discarded (i.e., the value is
  truncated toward zero). If the value
  of the integral part cannot be
  represented by the integer type, the
  behavior is undefined.

So like Paul R said, this is undefined behavior.

A: This is to be expected - casting a negative float to an unsigned int results in undefined behaviour (UB). If you want the value to wraparound (which is also UB, BTW), then you would need to cast to a (signed) int first and then to unsigned int. Ideally you should not rely on UB at all and find a better way of doing what you need to do.

A: This conversion is undefined and therefore not portable.
According to C99 §6.3.1.4 footnote 50:

The remaindering operation performed when a value of integer type is converted to unsigned type need not be performed when a value of real floating type is converted to unsigned type. Thus, the range of portable real floating values is (−1, Utype_MAX+1).

And given that this conversion is known not to be portable, it's quite a reasonable interpretation to return 0 rather than a random particular conversion. There are at least two reasons for this: (1) to flag non-portable code rather than propagate it, and (2) just dropping the sign is wildly different from what happens when the same value of an integral type is converted, so it's unclear that any particular alternative is a better idea.

A: Cast via a signed int.


text:
Q: CPT unsaved draft gives error 404 - when Post Formats support enabled I've a plugin for Portfolio CPT (can be downloaded from here: http://bit.ly/1tEj5bC), using this plugin, every thing works fine. But when i edit any portfolio entry and click on 'Preview Changes' BEFORE saving the edited entry, instead of showing edited content, it gives me error 404.
The url which gives 404 error is something like this ...
http://www.example.com/portfolio/post-name/?preview=true&preview_id=192&preview_nonce=2d14ae4815&post_format=gallery

Now, if i remove post_format=gallery parameter from this URL, it shows the portfolio post.  So, If i remove post-format support in the plugin, it does not append this parameter when viewing the draft but i need this plugin to support post-formats.
How to resolve the issue?
Update: I've tested two more third party plugin for portfolio CPT, adding post formats support in those plugin also leads to same error. It means, most probably, there is nothing wrong with the plugin code.
JFYI, post formats support is being added by passing following args through register_post_type() ...
'supports'          => array( 'title', 'editor', 'thumbnail', 'post-formats'),


text:
Q: two adobe air native extensions using google-play-services jar file I have two .ane extensions and they both require the google-play-services jar file to work successfully. when I use them separately in my mobile Air project, they work just fine. but when I need them both in one project, they conflict with each other:
java.lang.IllegalArgumentException: already added:
com/google/android/gms/appstate/OnStateListLoadedListener;

I wonder if there is a way so I don't put the google-play-services jar file in one of them and then create the .ane and yet when using it in the project that is using the other extension (which of course includes the google jar) then the former extension would work fine?
let me put it this way, how can my extension use the google-play-services jar file without combining the google jar file into my extension jar file and instead it will use what it needs from other extension that already has the google jar combined in the extension...?
am I clear in explaining what my problem is?! :)

A: Looks like AIR 4.0 has a solution for this.
If you look in Adobe's documentation
Developing Native Extensions for Adobe AIR
 / Developing Native Extensions
Packaging a native extension / Including resources in your native extension package
http://help.adobe.com/en_US/air/extensions/WSf268776665d7970d-2e74ffb4130044f3619-7ff8.html
You will see an example in the section: "Accessing native resources with R.* mechanism"
To quote:

Following is an example of the dependencies in platform.xml:

<packagedDependencies>
    <packagedDependency>android-support-v4.jar</packagedDependency>
    <packagedDependency>google-play-services.jar</packagedDependency>
</packagedDependencies>
<packagedResources>
  <packagedResource>
        <packageName>com.myane.sampleasextension</packageName>
        <folderName>ane-res</folderName>
    </packagedResource>
    <packagedResource>
        <packageName>com.google.android.gms</packageName>
        <folderName>google-play-services-res</folderName>
    </packagedResource>
</packagedResources>


text:
Q: (Weighted)AdjacencyMatrix for custom properties Is it possible to make (Weighted)AdjacencyMatrix from a graph whose elements have custom properties?
Consider this graph:
g = Graph[{
      Property[DirectedEdge[0, 1], {"WaterFlow" -> x, "PipeWidth" -> 10.0}],
      Property[DirectedEdge[1, 2], {"WaterFlow" -> x + y, "PipeWidth" -> 8.5}],
      Property[DirectedEdge[2, 1], {"WaterFlow" -> y, "PipeWidth" -> 8.5}],
      Property[DirectedEdge[2, 3], {"WaterFlow" -> x, "PipeWidth" -> 10.0}]
    }]

How do I make one WeightedAdjacencyMatrix weighted by "WaterFlow" and another one weighted by "PipeWidth"?
For example, the one for "WaterFlow" would be:

A: You could specify custom properties to set edge weights using undocumented option EdgeWeight:
WeightedAdjacencyMatrix[g, EdgeWeight -> "WaterFlow"] // MatrixForm

WeightedAdjacencyMatrix[g, EdgeWeight -> "PipeWidth"] // MatrixForm

Since this option is not documented, its behavior could be changed later though.


text:
Q: SQLite: Delete duplicate entries I am new to SQLite and I would like to find a solution to deleting duplicate entries based on a certain condition.
Suppose I have a table like this:
ID | Person1 | ID1 | Person2 | ID2 | Average
-------------------------------------------
1  | Name1   |   1  | Name4 |   4  | 47
2  | Name1   |   1  | Name5 |   5  | 88
3  | Name1   |   1  | Name6 |   6  | 15
----------------------------------------
4  | Name2   |   2  | Name4 |   4  | 90
5  | Name2   |   2  | Name5 |   5  | 80
6  | Name2   |   2  | Name6 |   6  | 45
----------------------------------------
7  | Name3   |   3  | Name4 |   4  | 30
8  | Name3   |   3  | Name5 |   5  | 20
9  | Name3   |   3  | Name6 |   6  | 79

and want a table like this:
ID | Person1 | ID1 | Person2 | ID2  | Average
-------------------------------------------
2  | Name1   |   1  | Name5 |   5   | 88
5  | Name2   |   2  | Name4 |   4   | 90
9  | Name3   |   3  | Name6 |   6   | 79

Is there anyway of doing this?
Thanks in advance.

A: This works:
DELETE FROM tablename
WHERE ID NOT IN (
    SELECT T.ID
    FROM (
        SELECT ID1, MAX(Average) AS MAverage
        FROM TableName
        GROUP BY ID1
    ) AS X
    INNER JOIN TableName T
        ON X.ID1 = T.ID1 AND X.MAverage = T.Average
);

This query finds the rows with the highest average per person (based on ID1), then deletes all the other rows.


text:
Q: magento minimal price of grouped product I want to display minimal price of grouped product in our magento online shop. I used
<?php echo $this->getPriceHtml($_product, true) ?>

But it does not work for grouped product. It only works for simple product.

A: $_product->getMinimalPrice () ;


text:
Q: Pyqt5 QtVirtualKeyboard raspberry pi 4 buster lite EGLFS cannot be mixed I'm trying to add QtVirtualKeyboard to my standalone application. My app running without desktop but i don't think this is the problem. I found that we can integrate to my QMainWindow a QObject that show the keyboard along my app. I also found that it possible to use QQuickView and inputPanel, but sincerely, im not sure how to make it. Anyone can help?
To make it "works" i used this topic Install QtVirtualkeyboard in raspberry-pi? then i have installed QtVirtualKeyboard with this commandsudo apt install qtvirtualkeyboard-plugin. I said "work" because if i didn't install with apt, my application did nothing.


text:
Q: Upload file to Sharepoint Online (Microsoft 365) using Powershell (Option 1-Using PnP.Powershell) I'm trying to upload a file into a Sharepoint Online (M365) library subfolder, but it keeps giving me errors. I have tried many scripts. This post is about using PnP.Powershell (I have posted questions about other scripts hoping someone can help me with any of them)
This is the code:
$url="https://mydomain.sharepoint.com/sites/mysharepointsite/"

$userID = "mail@foo.com"
$securePassword = ConvertTo-SecureString -String "myPaswword" -AsPlainText -Force
$credentials = New-Object System.Management.Automation.PSCredential -ArgumentList $userID, $securePassword

Install-Module -Name PnP.PowerShell
Connect-PnPOnline $url -Credentials $credentials

$files = Get-Item -Path "C:\myFolder\myFile.csv" -Force
foreach ($file in $files)
{
    Add-PnPFile -Folder "myLibraryname/subfolder"  -Path $file.FullName
    Write-Host $done.Name  "Uploaded into the Site" -BackgroundColor Green
}

It gives me this error
Connect-PnPOnline : AADSTS65001: The user or administrator has not consented to use the application with ID 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' named 'PnP Management Shell'. Send an interactive authorization request for this user and resource.
How do I grant this permission in M365? Is it safe to grant it?
Thanks

A: PnP PowerShell need to be granted some privileges on your tenant.
Maybe you can try
Register-PnPManagementShellAccess

Ref: Connecting with PnP PowerShell
I guess it's safe if you ensure you are on the official build and not a customized (hacked) one.
Basically, it will grant the module the right to perform some task using a delegated authorization. It won't have more privileges than your account.


text:
Q: Confusion regarding Inelastic Collisions contradicting my book Suppose two bodies $A$ and $B$ with equal mass are kept at a distance. $A$ starts moving towards $B$ at a constant velocity, they hit, and I assume that it is a PERFECTLY INELASTIC collision here.
According to what I learnt from my book, suppose a body hits another body and inelastic collision takes place, in order to maintain conservation of momentum, the final velocity of the two bodies will be equal and they will stick together.
But I was thinking about it with respect to velocities and I came across a dilemma. Suppose the velocity of $A$ is $V_A$ and of $B$ is $V_B$. Before collision, $V_B=0$. After $A$ hits $B$, it applies a force on it, and $V_B$ gains some velocity. Since I assumed that both of them have equal mass, the acceleration of $B$ will be equal to retardation of $A$. Let the change in velocity at the instance of the collision be $x$.
Therefore
relative velocity of $A$ w.r.t. B before collision$=V_A-V_B=V_A$
relative velocity of $A$ w.r.t. B at the instant of collision after instantaneous acceleration$=V_A-x-(V_B+x)=V_A-x-V_B-x = V_A-V_B-2x$
This shows that the relative velocity of  $A$ w.r.t. $B$ has decreased.
But doesn't this mean that $A$ will apply less force at $B$ now?
That means,
$A$ will have less retardation, and $B$ will have less acceleration than before.
But doesn't that mean that the rate of decrease of velocity of $A$ as well as the rate of increase of velocity of $B$ will keep decreasing? Which means relative velocity of one of the bodies with respect to the other will keep decreasing till it approaches $0$, but will never be $0$?
So does this mean the two bodies never truly attain same velocity?
P.S:  I referred to this post which I had asked long back before knowing about collisions based on a thought experiment

A: As I am not exactly sure as to your question I have given a number of possible answers.
In your previous post An overwhelming thought experiment regarding Newton's Third Law and motion of two bodies in an ideal condition it is explained that during a collision the total energy of the system of two colliding masses was the sum of kinetic energy and elastic potential energy.
In a system where the kinetic energy is not conserved internal forces do work, think of the masses oscillating with damping present, and heat and sound are produced and work is done by internal forces irreversibly breaking the bonds between atoms.
This is what would be happening in this example.
Now this might not answer your question in that you actually were asking about a variation of Zeno's Paradox regarding Achilles and a tortoise where it appears that adding ever deceasing quantities never allows one to get to a final state?
This paradox is as follows:
Achilles, the fleet-footed hero of the Trojan War, is engaged in a race with a lowly tortoise, which has been granted a head start. Achilles' task initially seems easy, but he has a problem. Before he can overtake the tortoise, he must first catch up with it. While Achilles is covering the gap between himself and the tortoise that existed at the start of the race, however, the tortoise creates a new gap. The new gap is smaller than the first, but it is still a finite distance that Achilles must cover to catch up with the animal. Achilles then races across the new gap. To Achilles' frustration, while he was scampering across the second gap, the tortoise was establishing a third. The upshot is that Achilles can never overtake the tortoise. No matter how quickly Achilles closes each gap, the slow-but-steady tortoise will always open new, smaller ones and remain just ahead of the Greek hero.
I refer you to What Is the Answer to Zeno's Paradox? for the resolution.
Another possibility is that the functions relating to the changes are of an exponential form, eg $\propto \text{e}^{-kt}$ which mathematically never reaches zero but one can say in Physics that after a time the model breaks down as in the real world the final state is reached.  There are many other examples, eg reaching a terminal speed whilst falling, the complete discharge of a capacitor, etc.

A: When you think of inelastic collisions it's best to think of two lumps of clay colliding. They give the most intuitive picture.
We can move to the rest frame of the two lumps to make things easier to reason about. In the rest frame the total momentum is zero. In the rest frame your question becomes "Do the centers of mass of the two lumps keep moving together forever?". This is still a valid point because the force between the lumps does get smaller as they lose velocity. But at some point the relative velocity becomes smaller than thermal motion: the random motion of atoms and molecules gives a larger contribution to the velocity than the relative velocity from the collision. At this point you can safely say the relative velocity is zero.
You may object that you don't want to reason about thermal motion at all. You are wondering about the idealized mathematics which is a reasonable thing to ask. In this case you can model the collision in two ways. Either by a contact force, like you describe, or by modelling the collision as an instantaneous transfer of momentum (an impulse). In the first case the relative velocity only asymptotically goes to zero and the "paradox" you describe holds true. In the second case the relative velocity after a perfectly inelastic collision is defined to be zero. For an impulse collision you don't worry about the details of the collision you only worry about the outcome.


text:
Q: iOS 11 list all applications Is it possible to get a list of all installed applications in iOS 11 beta?
I'm working on enterprise application, so I'm able to use any private API.
I know about old methods, such as using LSApplicationWorkspace class, but it's not working in iOS 11.
Maybe I need to add some strings in entitlement file? Or something else.

A: In enterprise you can use Apple Mobile Device Management (MDM) Protocol ManagedApplicationList commands to get managed applications list


text:
Q: Interval of Validity of a Solution
By separation of variables, the general solution to $y' = 3y - y^2$ is
$y(t) = 0$ or $y(t) = \frac{3}{1+ce^{-3t}}$.
Find the interval of validity of the solution satisfying $y(0) = 6$.
(i.e. find $a$ and $b$ such that the solution is valid on the interval $a<t<b$.)

I'm not really sure how to approach this.
I set $y' = 0$ and hence $3y - y^2 = 0$, and assuming $y \neq 0$, I proceeded to $3 = y = \frac{3}{1+ce^{-3t}}$. Then $1=1+ce^{-3t}$, which means $c=0$ since any $e^x$ function will never be $0$.
However, this entirely gets rid of the term containing $t$, and doesn't help me find boundaries for $t$.
How should I approach/solve this?

A: So you found the non-stationary solution of the ODE $y'(t)=3y(t)-y^2(t)$:
$$y(t) = \frac{3}{1+ce^{-3t}}$$
where $c$ is a real value different from zero.
The interval of validity depends on the initial condition $y(t_0)=y_0$. If $t_0=0$ and $y_0=6$ then
$$6=y(0) = \frac{3}{1+ce^{-3\cdot 0}}=\frac{3}{1+c}$$
which implies that $c=-1/2$.
Hence the solution that passes through the initial point $(0,6)$ is
$$y(t) = \frac{3}{1-\frac{e^{-3t}}{2}}=\frac{6}{2-e^{-3t}}$$
which is not defined for all real values of $t$.
The interval of validity of the solution is the biggest interval in the domain which contains $t=0$. Can you take it from here?
P.S. Note that if the initial condition is $y(t_0)=y_0$ with $y_0\in (0,3)$, i.e. between the stationary solutions that it will turn out that the interval of validity is whole real line $\mathbb{R}$. On the other hand, for $y_0$ outside the interval $[0,3]$, as in your case, the  interval of validity is just a half-line.


text:
Q: replace the assigned number in increasing order I have file containing following format. In the following file I want to replace every t=0.00000 with t=0.00000+50 like 50.00000 without changing the format of file. my file looks like:
MODULE  for the   Modulate t=   0.00000

MODULE  for the    Modulate t=   4.00000

MODULE   overshoot  Modulate t=   8.00000

MODULE   fail for  Modulate t=  12.00000

MODULE   successful for the Modulate t=  16.00000

I did something like this but not able to increment and its taking much time manually.
sed -i 's/MODULE  for the   Modulate t=   0.00000/MODULE  for the   Modulate t=50 /g'  file.txt

expected output:
MODULE  for the  Modulate t=   50.00000

MODULE  for the  Modulate t=  54.00000

MODULE  overshoot   Modulate t=  58.00000

MODULE   fail for  Modulate t=  62.00000

MODULE   successful for the Modulate t=  66.00000

A: In a Perl one-line command
perl -pe 's/Modulate\s+t=\K\s*([0-9.]+)/sprintf '%10.5f',$1+50/e' my_file

output
MODULE  for the   Modulate t=  50.00000
MODULE  for the    Modulate t=  54.00000
MODULE   overshoot  Modulate t=  58.00000
MODULE   fail for  Modulate t=  62.00000
MODULE   successful for the Modulate t=  66.00000

A: Using awk
awk 'NF{$NF=sprintf("%.5f",$NF+50)}1' file

MODULE  for the  Modulate t=   50.00000

MODULE  for the  Modulate t=  54.00000

MODULE  overshoot   Modulate t=  58.00000

MODULE   fail for  Modulate t=  62.00000

MODULE   successful for the Modulate t=  66.00000

A: incremental
awk '/t=[[:blank:]]*0.00000/{gsub(/t=[[:blank:]]*0.00000/, "t= " (Inc+=50) ".00000")}1' YourFile > NewFile

you can add BEGIN{Inc=-50} as first action if first occurence of t=0 need to still be 0
decal
sed '/\(t=[[:blank:]]*\)0\([.]00000\)/ s//\150\2/' YourFile > NewFile


text:
Q: How to call function inside EventHandler function react native I implement this library https://github.com/elanic-tech/react-native-paytm in my project. I successfully get a response from Paytm inside my
onPayTmResponse but now I want to send this response to the server but inside this function, I am unable to call any function or state it give me an undefined error.
componentWillMount() {
        if(Platform.OS == 'ios'){
            const { RNPayTm } = NativeModules
            const emitter = new NativeEventEmitter(RNPayTm)
            emitter.addListener('PayTMResponse', this.onPayTmResponse)
        }else{
            DeviceEventEmitter.addListener('PayTMResponse', this.onPayTmResponse)
        }

        //this.makeRemoteRequest();
}

onPayTmResponse(response) {
        // Process Response
        // response.response in case of iOS
        // reponse in case of Android

        var actual = "";
        if(Platform.OS == 'ios'){
            actual = JSON.parse(response.response);
        }else{
            actual = JSON.parse(response);
        }

        console.log(actual, this.state);

        if(actual.RESPCODE == "01"){
            // Place Order
            placeOrder();
        }else{
            alert(actual.RESPMSG);
            this.setState({loading: false, buttonText: 'Continue'});
        }
    }

Error

A: Bind your onPayTmResponse function with this inside componentWillMount like
componentWillMount() {
  this.onPayTmResponse = this.onPayTmResponse.bind(this); // note: we bind onPayTmResponse with this
  if(Platform.OS == 'ios'){
    const { RNPayTm } = NativeModules
    const emitter = new NativeEventEmitter(RNPayTm)
    emitter.addListener('PayTMResponse', this.onPayTmResponse)
  }else{
    DeviceEventEmitter.addListener('PayTMResponse', this.onPayTmResponse)
  }
  //this.makeRemoteRequest();
}

Now you should be able to call setState within onPayTmResponse.


text:
Q: ggplot aes: alpha gets "smoothed out" I'm using ggplot in the ggplot2 R package, with the mpg data set.
classify = function(cls){
    if (cls == "suv" || cls == "pickup"){result = 1}
    else {result = 0}
    return(result)
}
mpg = mpg %>% mutate(size = sapply(class, classify))

ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy, alpha = size))

Now, size can take only two values: 1 when class is suv or pickup, and 0 otherwise. But I get a weird "smooth" range of sizes in the resulting plot:

(It's not the legend that surprises me, but the fact that there are actually values plotted with alpha 0.1 or 0.3 or whatever.)
What's going on?

A:
(It's not the legend that surprises me, but the fact that there are actually values plotted with alpha 0.1 or 0.3 or whatever.)

There aren't. What you're seeing is that multiple points have the exact same discrete coordinates, and so the semi-transparent points overlap.
And to fix the legend, use factors or character strings (= discrete) instead of numbers (= continuous).

Unrelated, but your classify implementation is pretty unorthodox code. First of all, since R is a functional language, all expressions are values. That means that, rather than performing assignment inside an if you'd usually assign the result of if:
result = if (cls == "suv" || cls == "pickup") 1 else 0

What's more, there's no need for the result variable and neither for the return function call (which in R performs early exit). Instead, an idiomatic R implementation would look as follows:
classify = function(cls) {
    if (cls == "suv" || cls == "pickup") 1 else 0
}

Better yet, use vectorised ifelse instead of non-vectorised if:
classify = function(cls) {
    ifelse(cls == "suv" | cls == "pickup", 1, 0)
}

Now you can use classify without the sapply:
mpg = mpg %>% mutate(size = classify(class))


text:
Q: face detection in Qt and opencv I wrote some code for face detection in c++ using the opencv library. Here I am controlling the mouse pointer using face. When I write the same code in Qt, it does not load the haarcascade xml files
Here is my c++ code:
#include<opencv2/opencv.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<time.h>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
using namespace cv;

CascadeClassifier faceCade;

String faceCascadeName = "lbpcascade_frontalface.xml";
String FaceDetectWindow = "Face Detector Window";
String FaceDetectGrayWindow = "Face Detector Gray Window";

int main() {

    VideoCapture cap(0);
    Mat camFrames, grayFrames;
    vector<Rect> faces;
    long imageIndex = 0;

    int preX=0,preY=0;
    int j=0;

     if( !faceCade.load( faceCascadeName ) ){ cout<<"--(!)Error loading\n"; return -1; };

    while (1) {
        cap >> camFrames;

        cvtColor(camFrames, grayFrames, CV_BGR2GRAY);
        equalizeHist(grayFrames, grayFrames);

        faceCade.detectMultiScale(grayFrames, faces, 1.1, 2, 0, Size(160, 160));

        for (int i = 0; i < faces.size(); i++)
      {
            Mat faceROI = grayFrames(faces[i]);

            rectangle(camFrames, Rect(faces[i].x - 25,faces[i].y - 25,faces[i].width + 35 ,faces[i].height + 35),  Scalar(0, 0, 255), 1, 1, 0);

            Point center(faces[i].x + faces[i].width * 0.5,faces[i].y + faces[i].height * 0.5);

            cout<<"\nx = "<<faces[i].x<<"\ty = "<<faces[i].y;

            //while(j==10)
            //{
             if((faces[i].y<125)&&(faces[i].x<255))
             {
                printf("  RU");
                system("xte 'mousermove 10 -10'");
                }
             else if((faces[i].y>185)&&(faces[i].x<255)){
                  printf("  RD");
                  system("xte 'mousermove 10 10'");
                  }
             else if((faces[i].y>185)&&(faces[i].x>305)){
                  printf("  LD");
                  system("xte 'mousermove -10 10'");
                  }
             else if((faces[i].y<125)&&(faces[i].x<255)){
                  printf("  LU");
                  system("xte 'mousermove -10 -10'");
                  }
              else if((faces[i].y>185)&&(faces[i].x>255)&&(faces[i].x<305)){
                  printf("  Down");
                  system("xte 'mousermove 0 10'");
                  }
               else if((faces[i].y<125)&&(faces[i].x>255)&&(faces[i].x<305)){
                  printf("  up");
                  system("xte 'mousermove 0 -10'");
                  }
              else if((faces[i].y>125)&&(faces[i].y<185)&&(faces[i].x<255)){
                  printf("  L");
                  system("xte 'mousermove -10 0'");
                  }
             else if((faces[i].y>125)&&(faces[i].y<185)&&(faces[i].x>305)){
                  printf("  R");
                  system("xte 'mousermove 10 0'");
                  }
               preX = faces[i].x;
               preY   = faces[i].y;
               j=0;
              }
        //j++;
        //}

        imshow(FaceDetectWindow, camFrames);
        imshow(FaceDetectGrayWindow, grayFrames);
        if(waitKey(30) >= 0) break;

    }

}

here the face is detected but in the qt code below it is not working
#include<opencv2/opencv.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<time.h>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
using namespace cv;

CascadeClassifier faceCade;

String faceCascadeName = ":/new/prefix1/lbpcascade_frontalface.xml";
String FaceDetectWindow = "Face Detector Window";
String FaceDetectGrayWindow = "Face Detector Gray Window";

int main() {

    VideoCapture cap(0);
    Mat camFrames, grayFrames;
    vector<Rect> faces;
    long imageIndex = 0;

    int preX=0,preY=0;
    int j=0;

    if( !faceCade.load( "lbpcascade_frontalface.xml" ) ){ cout<<"--(!)Error loading\n"; return -1; };

    while (1) {
        cap >> camFrames;

        cvtColor(camFrames, grayFrames, CV_BGR2GRAY);
        equalizeHist(grayFrames, grayFrames);

        faceCade.detectMultiScale(grayFrames, faces, 1.1, 2, 0, Size(80, 80));

    /*    for (int i = 0; i < faces.size(); i++)
      {
            Mat faceROI = grayFrames(faces[i]);

            rectangle(camFrames, Rect(faces[i].x - 25,faces[i].y - 25,faces[i].width + 35 ,faces[i].height + 35),  Scalar(0, 0, 255), 1, 1, 0);

            Point center(faces[i].x + faces[i].width * 0.5,faces[i].y + faces[i].height * 0.5);

            cout<<"\nx = "<<faces[i].x<<"\ty = "<<faces[i].y;

            //while(j==10)
            //{
             if((faces[i].y<125)&&(faces[i].x<255))
             {
                printf("  RU");
                system("xte 'mousermove 10 -10'");
                }
             else if((faces[i].y>185)&&(faces[i].x<255)){
                  printf("  RD");
                  system("xte 'mousermove 10 10'");
                  }
             else if((faces[i].y>185)&&(faces[i].x>305)){
                  printf("  LD");
                  system("xte 'mousermove -10 10'");
                  }
             else if((faces[i].y<125)&&(faces[i].x<255)){
                  printf("  LU");
                  system("xte 'mousermove -10 -10'");
                  }
              else if((faces[i].y>185)&&(faces[i].x>255)&&(faces[i].x<305)){
                  printf("  Down");
                  system("xte 'mousermove 0 10'");
                  }
               else if((faces[i].y<125)&&(faces[i].x>255)&&(faces[i].x<305)){
                  printf("  up");
                  system("xte 'mousermove 0 -10'");
                  }
              else if((faces[i].y>125)&&(faces[i].y<185)&&(faces[i].x<255)){
                  printf("  L");
                  system("xte 'mousermove -10 0'");
                  }
             else if((faces[i].y>125)&&(faces[i].y<185)&&(faces[i].x>305)){
                  printf("  R");
                  system("xte 'mousermove 10 0'");
                  }
               preX = faces[i].x;
               preY   = faces[i].y;
               j=0;
              }
            //j++;
        //}*/

        imshow(FaceDetectWindow, camFrames);
        imshow(FaceDetectGrayWindow, grayFrames);
        if(waitKey(30) >= 0) break;

    }

}

please help me to do that in qt platform
here the output shown in qt code is --(!)Error loading
which means the cascade file is not loaded

A: String faceCascadeName = ":/new/prefix1/lbpcascade_frontalface.xml";

It is a valid path, but you need to create it in the Qt resource file.
http://qt-project.org/doc/qt-5.0/qtcore/resources.html
Otherwise, if you don't want to deal with resources, go and make it a relative path.
For example:
"./file.xml" will look for the xml file from the working directory.
"../file.xml" will look for the xml file one level above the working directory.
Hope that helps.

A: The following path does not seem to be correct:
String faceCascadeName = ":/new/prefix1/lbpcascade_frontalface.xml";


text:
Q: Regex to match sequence of permutations Given set of n characters, what regex do we need to match a sequence of 0-x permutations of these characters?
We want permutations. Given set of 3 characters A,B,C we want to match ABC, ACB, BAC, BCA, CAB, CBA.
However, we want to match a sequence of these permutations. Sequence may contain 0 or more permutations, meaning that we want to match empty string, ABC, ABCBCA, BACCAB, BCAABCCBAABC, etc.
I was able to find solutions to match a permutation, but was unable to modify it to match a sequence of permutations.
I understand that sometimes the used regex engine might make difference. I would like to use this regex in C#'s Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.Matches method, should that make a difference. We simply want to check whether output string of tested method matches this regex, i.e. is a sequence of permutations of given set of characters.

A: I cannot recommend too highly1 the use of a regular expression here!
You can use the following regex to test strings for conformance when  for n = 3 and the characters are 'A', 'B' and 'C':
/^(?:([ABC])(?!\1)([ABC])(?!\1|\2)[ABC])*$/

Demo
The regex can be made self-documenting by writing it in free-spacing mode:
/
^           # match beginning of line
(?:         # begin non-capture group
  ([ABC])   # match 'A', 'B' or 'C' in capture group 1
  (?!\1)    # next character cannot be the content of capture group 1
  ([ABC])   # match 'A', 'B' or 'C' in capture group 2
  (?!\1|\2) # next character cannot be the content of capture group 1 or 2
  [ABC]     # match 'A', 'B' or 'C'
)           # end non-capture group
*           # execute non-capture group 0+ times
$           # match end of line
/x          # free-spacing mode

(?!\1|\2) is a negative lookaheads.
I've used beginning- and end-of-line anchors to facilitate testing at the link, but beginning- and end-of-string anchors would be more appropriate (\A and \z).
1 Literal interpretation intended.

A: You could just use a little helper i guess
static bool Check(string source, string target)
{
   int? sLen = source?.Length, tLen = target?.Length;

   if (!(sLen > 0) || !(tLen > 0) || tLen % sLen != 0)
      return false;

   IEnumerable<string> Chunks(string str, int chunkSize)
      => Enumerable.Range(0, str.Length / chunkSize)
                   .Select(i => str.Substring(i * chunkSize, chunkSize));

   return Chunks(target, source.Length).All(x => source.All(x.Contains));

}

This is likely to be a lot faster than regex, and can deal with nulls


text:
Q: Could files downloaded from Youtube and Tumblr harm Mac? I'm putting old files to fresh Mac and on one external drive, there is bunch of video files I downloaded from Youtube and Tumblr at one point few months ago.
Would it be safe to put them to fresh Mac or could those files be harmful? There didn't seem to be anything bad with them before, but as this is fresh Mac I'm more careful now.
Should I keep them away from fresh Mac just in case?

A: Well there are two points to this.
A.) there is a question of whether or not the files themselves contain any malicious code, which is hypothetically possible, but not likely. Owlswipe's comment is not correct in saying you cannot download files from YouTube, you can do so both through YouTube Red, as well as downloader extensions (which by the way are not illegal).
All a YouTube downloader extension does is use a program (often times wget, or something similar) to make a copy of the video file that is referenced in the html for that video's page. While it is possible for a downloader extension to infect that video file, it is quite unlikely for it to happen in practice. As far as files from Tumblr go you can probably safely assume the majority of posters on Tumblr do not have the knowledge how, or a reason to inject malware into a picture they are posting. Also seeing as both of these sites use HTTPS (Secure HyperText Transfer Protocol) it would not be possible for someone else to slip malware into either the file as you were downloading it or the page when you were connecting. Though there is always technically the possibility that their severs could be hijacked, it is very unlikely that it happened during the specific time you were downloading files. Which brings me to the second point.
B.) Macs run macOS, which is built on Unix. Unix is very secure, and generally hard to infect with malware. While this does not mean you should stop caring about keeping your computer safe (because it is still possible for a Mac to get infected), as long as you don't enter your password into random prompts saying a program you didn't launch wants to modify your system you should be fine. Typically it is only Windows that is vulnerable to the type of attacks used by malware that is contained in an image or video file, and it is because of the way Windows handles both security access and multimedia with a connected system.
All in all your Mac should be fine if you move your older files to it. Unless you know for sure that someone had hijacked the YouTube or Tumblr servers on the day you downloaded the files, you don't realistically need to worry about it getting infected by them. With that said always be careful when running programs you download from the internet, even on a Mac, as it is easier for malware in a program to infect any system than it is for malware in a video or image file.


text:
Q: React beautiful DND: Detected non-consecutive  indexes - Error when re-reodering Using https://www.npmjs.com/package/react-beautiful-dnd after reordering some element for the first time, reordering of the previously moved item is not possible and the console prints
 Unable to find draggable with id: XXX

Also, when dragging another item the UI get broken and the console prints:
Detected non-consecutive <Draggable /> indexes.(This can cause unexpected bugs) 0, [2], 3, 4, 5

A: SOLUTION
You have to add the key property to the  <Draggable key={uniqueId} ...> component.
also, please notice:

*

*You cannot use the array index as value for the key attribute

*key value should be a unique id and stable value (not change across re-render) that represents the element

BROKEN
    <Draggable draggableId={id} index={index}>
                {(provided) => (
                   ...
                )}
    </Draggable>

FIXED
<Draggable key={uniqueId} draggableId={uniqueId} index={index}>
            {(provided) => (
                     ...
            )}
 </Draggable>


text:
Q: Embedding Python 3.3: How do I access _PyParser_Grammar? I am attempting to emulate the Python/C API's PyRun_InteractiveLoop() function, but from a different input system used by my employer. The Python FAQ (http://docs.python.org/3/faq/extending.html#how-do-i-tell-incomplete-input-from-invalid-input) has the following code, used to check if a given character array is a complete Python block:
#include <Python.h>
#include <node.h>
#include <errcode.h>
#include <grammar.h>
#include <parsetok.h>
#include <compile.h>

int testcomplete(char *code)
  /* code should end in \n */
  /* return -1 for error, 0 for incomplete, 1 for complete */
{
  node *n;
  perrdetail e;

  n = PyParser_ParseString(code, &_PyParser_Grammar,
                           Py_file_input, &e);
  if (n == NULL) {
    if (e.error == E_EOF)
      return 0;
    return -1;
  }

  PyNode_Free(n);
  return 1;
}

This gives an undeclared variable error for _PyParser_Grammar. Searching the Python source code, I did not find any headers that declared _PyParser_Grammar. Looking further, I found it referenced by a few functions, in particular meta_grammar() and Py_meta_grammar() as defined in metagrammar.c.
While meta_grammar() is defined in pgen.h, it gives an undefined symbol error despite compiling (g++ for my test code) with -lpython3.3m. A quick nm revealed that meta_grammar() is not a visible symbol in libpython3.3m.so, while Py_meta_grammar() is. However, when searching the Python source code, I have not found any header that declares Py_meta_grammar().
Am I missing something? Where are these symbols declared/defined?

A: After a great deal of faffing about, it seems there are no headers declaring _PyParser_Grammar. However, declaring
extern grammar _PyParser_Grammar;

in each of the C++ source files that need access works perfectly. Not particularly elegant, but at least it compiles.


text:
Q: Помогите чуть допилить скрипт Скрипт, чтоб при открытии одного попапа, другой попап закрывался (если он на тот момент открыт). Спасибо
https://jsfiddle.net/52hxLrsk/10/
var items = $('.btn-win');
      for(var i=0;i<items.length;i++){
          $(items[i]).click(function () {
          var id = $(this).attr('href');
              $(id).toggleClass("active");
              return false;
          });
      }

A:

$('.btn-win').click(function() {
  $('.btn-win').not(this).each(function() {
    $($(this).attr("href")).removeClass("active");
  });
  $($(this).attr("href")).toggleClass("active");
  return false;
});
.win {
  position: absolute;
  width: 200px;
  height: 200px;
  display: none;
}

.win.active {
  display: block;
}

.win:nth-child(1) {
  background: pink;
  /*top: 100px;*/
}

.win:nth-child(2) {
  background: green;
  /*top: 200px;*/
}

.win:nth-child(3) {
  background: yellow;
  /*top: 300px;*/
}

Окно 1
Окно 2
Окно 3

Окно 1

Окно 2

Окно 3


text:
Q: How to retrive data in Angular 2? I am using post method.
Here is my ts file:
viewt(testid)
{
    $('#myModal22').modal('show');
    var param2 = {
        testid:testid,
    }
    this.service.get_tquestion(param2).subscribe(data => {
        this.test_question1 = data;
        console.log(data);
        console.log(this.test_question1);
    });
}

Also HTML Code:
<ng-container *ngFor="let v of test_question1">

        {{v.questionid}}
        {{v.questionname}}

</ng-container>

And Service Part:
get_tquestion(param) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    // this.createAuthorizationHeader(headers);
    return this.http.post(
        this.base_url + "test/getquestion", param, {headers: headers })
        .map((res: Response) => res.json());
}

And API response is this:

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

Response what I am getting is:

{"Code":200,"Results":[{"questionid":1034,"questionname":"Identify the adjective in the following sentence. We carried a few sandwiches for lunch.(Hard)","duration":60}]}

But I cannot display in HTML.

A: You're passing whole response from the API to test_question1 variable. Since response is an object and it's not Iterable you cannot use it with ngFor directive. To fix this you can for example return data array from the service:
return this.http.post(this.base_url + "test/getquestion", param, { headers: headers })
    .map((res: Response) => res.json().Results);}

or assign property of response object inside subscription:
this.test_question1 = data.Results;

A: You should try this, works for me:
In your service.ts
import { Injectable } from '@angular/core';
import { URLSearchParams, Http, HttpModule, Response, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class AuthService {
constructor(private http: Http) { }

authenticate(user_creds)
{
  //console.log(user_creds);
  const header = new Headers();
  header.append('Content-Type', 'application/x-www-form-urlencoded');
  return this.http.post('http://localhost/valuesassessment/api/login/authenticate_login', user_creds, { headers: header })
    .map((res: Response) => res.json());
}
}

In your .ts :
import { AuthService } from '../auth.service';

export class LoginComponent implements OnInit {
    session_data: any = {};
constructor( private authService: AuthService )
{
  // your logic before init
}

authenticate(x)
{
    this.authService.authenticate(x)
                    .subscribe(data =>
                    {
                      if(data.ResponseCode == 411)
                      {
                        // console.log(data.ResponseCode)
                        this.session_data = data;
                      }
                      else
                      {
                        this.session_data = data;
                        // console.log(this.session_data);
                      }
                    })
    this.session.store('header',this.header);
}

Note that before assigning responce to session_data, we have initialised it as type any.
Hope this helps.


text:
Q: Rails join two different tables resulting in data cascade to next rows I'm trying to join two different tables together to get a user activity report but I'm getting wrong results and after getting the result rows I'm having trouble working with it.
Here is my query:
User.joins(:contract_comments).joins(:audits).where(id:1).where(contract_comments: { created_at: (dateRange) }).where(audits: { created_at: (dateRange) })

This produces 4 times more results than expected, for example:
[#<User id: nil, audit_id: 56237, contract_comment_id: 4511>,
 #<User id: nil, audit_id: 56238, contract_comment_id: 4511>,
 #<User id: nil, audit_id: 56239, contract_comment_id: 4511>,
 #<User id: nil, audit_id: 56240, contract_comment_id: 4511>]

This is the result after getting on a dateRange that should have only one contract_comment and no audits.
I tried different approaches to solve but this was the most promising one. But I'm stuck now and need help on how to get this report done. The reason I need the table joined is to get the first 25 rows sorted by date independent of the table it came from.
Thanks!

A: Try User.joins([:contract_comments,:audits]).where(id: 1, contract_comments: { created_at: dateRange }, audits: { created_at: dateRange } )


text:
Q: Slow program- Mathematica shuts down I've been trying to draw dynamic pictures of level sets of certain polynomials. The code right now looks like that :
 n = 2;
 dp[w_, z__] := ((-1)^(n))*
 Product[w - Complex @@ zz, {zz, {z}}]/
 Product[Complex @@ zz, {zz, {z}}]
 dp[w, Sequence @@ z] (* not really needed here*)
 Integrate[dp[w, Sequence @@ z], w] (*not really needed either*)

 DynamicModule[{z = RandomReal[{1, 2}, {n, 2}]},
 Dynamic[
 Show[ContourPlot[
 With[{w = x + I*y},
  Abs[Integrate[dp[Q, Sequence @@ z], Q] /. Q -> w] - Abs[w]] ==
  0, {x, -15, 15}, {y, -15, 15}, ImageSize -> Large, Axes -> True],
  Graphics[
  Evaluate@
   Table[With[{i = i}, Locator[Dynamic[z[[i]]]]], {i, n}]]]]]

What this does is it builds a polynomial $dp(w)$ having n roots (think of this as the derivative of some polynomial $p(w)$) and it retrieves the anti-derivative that corresponds to const=0, $p(w)$, by integrating. Then I want to draw dynamic pictures of the level curves $|p(w)|=|w|$ that I can change by moving the roots of $p'(w)$ (dp[w] in the code ) around. It seems to work for n<=3 but it's very slow and for n>3 the program shuts down. Is there anyway to prevent this/make the program faster? I would like to be able to work with at least n=6. Any help is appreciated!

A: I have tuned your code a bit and it now works reasonably on v.10. 7 locators are ok, 10 gets terrible, but nothing crashes.
This is the integral of your function. You can compare it to Integrate[dp[w, z], w]:
p[w_, n_Integer, z__] :=
 Sum[Total@(((-1)^n w^(n - i + 1))/(n - i + 1)
       Times @@@ Subsets[-(Complex @@@ {z}), {i}]), {i, 0, n}]/
  Times[Sequence @@ (Complex @@@ {z})]

I have made it a function of n too, to localize the variables as much as possible.
DynamicModule[{z, n = 10}, z = RandomReal[{1, 2}, {n, 2}];
 Dynamic[Show[
   ContourPlot[
    With[{w = x + I*y}, Abs[p[w, n, Sequence @@ z]] - Abs[w]] ==
     0, {x, -15, 15}, {y, -15, 15}, ImageSize -> Large, Axes -> True],
    Graphics[
    Evaluate@
     Table[With[{i = i}, Locator[Dynamic[z[[i]]]]], {i, n}]]]]]

As you can see, n is now assigned a value within the module. Try starting small and working up. n=6 should not be a problem.


text:
Q: SQL Alchemy - How to use built-in function in PostgreSQL database? I want put this query into code:
select * from st_geomfromtext('POINT(106.69588536141288 10.782847409207672)')

Here is what I did in code:
class st_geomfromtext(GenericFunction):
    name = 'st_geomfromtext'

query = Session.query(func.st_geomfromtext('POINT(106.69588536141288 10.782847409207672)')).all()

Here is what I receive:
LINE 1: SELECT st_geomfromtext('POINT(106.69588536141288 10.78284740...
               ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

A: Are you able to validate your query directly against PostgreSQL?
Function may actually not be there. st_geomfromtext is part of PostGIS, depending on the PostgreSQL version, you may need to install / enable it.


text:
Q: font-weight:300 doesn't work in Chrome I'm having an issue with font-weight in Chrome.  Any font weights lower than the default weight of 400 will render at the default weight, overriding the font-weight:300 CSS attribute.  Font weights higher than the default weight will render as expected in Chrome, and all font weights render properly in Firefox.  Why is this happening?
For example:

Light

with CSS
.light {font-weight:300;}

will render as if font-weight:400.
jsfiddle, compare view in Firefox and Chrome
EDIT: Screenshots of the text in both Chrome and Firefox, running in Fedora 20:
Chrome (incorrect rendering): i.imgur.com/MCHHTlF.png
Firefox (correct rendering): i.imgur.com/tTH9rPd.png
Sorry, I can only post 2 links maximum, apparently.

A: Try changing the font family to 'Open Sans Light', sans-serif;. I had the same problem and this worked for me. It also worked in your provided fiddle.


text:
Q: bash script fail when a command wait ffmpeg to finish In ubuntu 13.04 have a node.js server that launch for certain events, a script like this:
#! /bin/bash
...
...

avconv -i "$dir$video" -ss "$ss.000" -t $tt -threads 0 "$folder/$dif.webm"

y_uid=$(/app/youtube-uploader "$folder/$dif.webm" "$label" "$desc" | grep 'watch' | sed 's/v=/ /g' | awk '{print$2}')

echo "$y_uid" >> ~/log/yt.log
...
...

if avconv (ffmpeg) process a small file (less then 30 minutes of encoding), the script works fine, but if avconv runs for hours, the next command "...youtube-uploader..." (that is a python based application) doesn't work (but if i try to launch it manually, it will go fine).
I have also tried to launch the next command inside a loop that check if the variable "$y_uid" is empty, so it will try to repeat youtube-uploader until it find a right value, but it will continue to stay in background and will try forever.. (and it is strange, because if i try to launch the command manually, it works fine..).
Summarizing, seems like that if avconv run for hours, the avconv process will generate a file that is not recognised or locked or a ghost file for the same script (but is recognised if the command is launched outside the script), if it is a small encoding, it will work fine.
Unfortunatelly It is difficult to debug or test, because i have every time to wait for hours, please help!
UPDATE
I think the problem is related at the buffer size of node.js OR some other buffer that store the standard output of ffmpeg. Just correct
avconv -i "$dir$video" -ss "$ss.000" -t $tt -threads 0 "$folder/$dif.webm"

in
avconv -i "$dir$video" -ss "$ss.000" -t $tt -threads 0 "$folder/$dif.webm" &> /dev/null

so all the ffmpeg output not full the buffer memory and everythings go well


text:
Q: Is Windows Kinect different from Xbox Kinect? I couldn't tell from the official site whether Windows Kinect is just an SDK, or another hardware piece that works only with Windows. What's the difference between a Windows Kinect and an Xbox Kinect?

A: Yes and No
There are minor differences.
Its more like a "refresh" of the hardware.  The Kinect that only supports the XBOX 360 is limited in several ways because of the hardware limits of the USB 2.0 bus interface.
So the one major "minor" difference is you can be a great deal closer to the Windows Kinect's sensor and it can still track your movements.
The second difference is the SDK released with this hardware can be used in a commercial application.  The SDK that was released in the past CANNOT.
The original hardware is limited by the limitations of the older XBOX 360 models, the newest model ( released with the Kinect ) has a Kinect dedecated port, but because backware compatability is a concern the Kinect hardware itself is unlikely to be updated on the xbox 360.
Technically there is no reason the Windows Kinect hardware could not work on other operating systems.
Update:
There are drivers for this device on Linux that have been released since I first answered this question.


text:
Q: Como encontrar el contorno mas grande en OpenCV he estado trabajando en un codigo para el reconocimiento de manos. Pero me he encontrado con un problema que llevo tiempo teniendolo a la hora de hacer cualquier tipo de reconocimiento de imagen y es que me encuentro con pequeñas manchas que mi codigo detecta y en vez de seleccionar el contorno mas grande, lo que hace es escoger el contorno mas pequeño. Por lo que quiero saber si existe alguna forma de elegir el contorno mas grande.
He intentado buscar el area mas grande con el metodo de cv2.contourAreay tambien con el metodo de cv2.arcLengthpero no me ha funcionado, porque lo que realmente me coge el programa son pequeños contornos.
Este es mi codigo:
import cv2
import numpy as np
import xlsxwriter

def SkinColorUpper (Hue,mult1,mult2):
    upper = [Hue,mult1*255,mult2*255]
    upper = np.array(upper)
    return upper

def SkinColorLower (Hue,mult1,mult2):
    lower = [Hue,mult1*255,mult2*255]
    lower = np.array(lower)
    return lower

direc = ('Fotos/A/1.jpg')
img = cv2.imread(direc,1)
# cv2.imshow("Imagen",img)
# cv2.waitKey(0)
heigth, width = img.shape[:2]
#print (img.shape)

start_row,start_col = int(0),int(0)
end_row, end_col = int(heigth), int(width*.3)
img = img[start_row:end_row,start_col:end_col]

hls = cv2.cvtColor(img,cv2.COLOR_BGR2HLS)

mask = cv2.inRange(hls,SkinColorLower(0,0.2,0),SkinColorUpper(27,0.72,0.75))
#mask = cv2.inRange(hls,np.array([0,49,61]),np.array([20,255,127]))

blur = cv2.medianBlur(mask,5)

ret,edges = cv2.threshold(blur,0,255,cv2.THRESH_BINARY + cv2.THRESH_OTSU)
#edges = cv2.adaptiveThreshold(blur, 255, cv2.ADAPTIVE_THRESH_MEAN_CHRESH_MEAN_C, cv2.THRESH_BINARY_INV, 11, 2)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
edges= cv2.morphologyEx(edges, cv2.MORPH_OPEN, kernel)

contours, hierarchy = cv2.findContours(edges.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
draw = cv2.drawContours(img,contours,-1,(255,0,0),3)
#print(contours)
cv2.imshow("mask",img)
cv2.waitKey(0)

for component in zip(contours,hierarchy):
    current_contour = component[0]
    # cv2.imshow("img_resize",current_contour)
    # cv2.waitKey(0)
    x,y,w,h = cv2.boundingRect(current_contour)
    p = cv2.arcLength(current_contour,True)
    epsilon = p*0.015
    approx = cv2.approxPolyDP(current_contour,epsilon,True)
    lados = len(approx)
    empty = np.zeros((h,w),np.uint8)
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),1)
    roi = edges[y:y+h,x:x+w]
    empty[0:h,0:w]=roi
    edges=empty
    # cv2.imshow("Edges",edges)
    # cv2.waitKey(0)
    img_resize = cv2.resize(edges,(150,150),interpolation=cv2.INTER_AREA)
    ret, edges_res = cv2.threshold(img_resize,0,255,cv2.THRESH_BINARY + cv2.THRESH_OTSU)
    # cv2.imshow("img_resize",img_resize)
    # cv2.waitKey(0)
    contours_2,hierarchy_2 = cv2.findContours(edges_res.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

    for component_2 in zip(contours_2,hierarchy_2):
        currentContour =  component_2[0]
        x,y,w,h = cv2.boundingRect(currentContour)
        M = cv2.moments(currentContour)
        cx = int(M['m10']/M['m00'])
        cy = int(M['m01']/M['m00'])
        A = cv2.contourArea(currentContour)
        p = cv2.arcLength(currentContour,True)
        aP=A/float(p*p)
        #print(M['m10'],M['m01'],M['m00'],cx,cy,A,p,aP)
        Hu = cv2.HuMoments(M)
        # print(Hu)
cv2.destroyAllWindows()


text:
Q: Apple "13 2011 MacBook Pro touchpad battery faulty issue. (10.13.6 software problem) Recently, my school that gave me that laptop asked it back, and it removed the battery. I'm forced to use the charger but that is not the question right now.
I currently need help because it doesn't actually show the settings in the trackpad settings, instead it thinks i'm using an iMac because it has bluetooth trackpad + keyboard connection.
The issue and the pictures:

You might see this kind of a post alot now, it's an issue on high sierra. I recently re-installed it because of performance slow-down, actually that is not the thing i'm talking about right now.
I currently have no other idea other than downgrading to 10.12 sierra
Any ideas how to fix the trackpad?

A: The most likely cause is that the "tech" broke the trackpad when they removed the battery, so the Mac is looking for a Bluetooth trackpad instead. (Or at least, they 'loosened' it sufficiently that it has subsequently broken.)
Frankly, your school has given you a 10-year-old laptop, with no battery, and a broken trackpad. (And a startup disk called "aaaaaa".) Because there's no battery, the CPU performance will be throttled at best.
At worst, the power adapter can't supply enough current at all times to even make the OS stable. Let's hope it doesn't have the original hard drive....
Take it back to them, and tell them it's unreliable. This is not a software problem. You need hardware service on this unit or a new Mac.


text:
Q: Extend functionality of dependent classes in a module in python There is a library that hast several classes. Some are used inside others because Sentence consists of lots of Token.
Now I need to add a new property to Token and a new method to Sentence that takes the new property of Token into account.
class Sentence:
    tokens: List[Token] = []

    def to_tokenized_text(self):
        return ' '.join(self.tokens)

    def to_original_text(self):
        out = ''
        for token in self.tokens:
            out += token
            if token.space_after is True:
                 out += ' '
        return out

To add a new method I would usually just subclass the Sentence class and add it there
class MySentence(Sentence):
    def to_my_text(self):
         out = ''
         for token in self.tokens:
             if token.skip:  # example of new property
                 continue
             out += token
         return out

This would work if there would be no need for the new property of Token. But I cant Subclass Token, because Sentence would still use the original Token class and I don't want to overwrite the whole class or all of the methods that include the use of Token.
I found a way to overwrite a property getter in this unrelated GitHub Issue, but i could not translate it to my situation.
In the end i would like to be able to call either Sentence.to_my_text() or MySentence.to_my_text() and have the Tokens concatenated respecting the value of the new property (e.g. skip), that is not available in the original Token class.

A: I found a solution that works and its indeed inspired by the unrelated GitHub Issue.
I've added
def get_my_new_prop(token):
    try:
        return token._my_new_prop
    except AttributeError:
        return None

def set_my_new_prop(token, val):
    token._my_new_prop = val

Token.anonym = property(lambda self: get_my_new_prop(self),
                        lambda self, val: set_my_new_prop(self, val))

class MySentence(Sentence):
    # ...

    def to_my_text(self):
        # ...
        for t in self.tokens:
            if t.my_new_prop:
                apply_magic_dust(t.text)
        # ...

and now the Tokens have a new property i can read and write.
The new Method can make use of it and apply things based on that new property.
I had to catch the AttributeError for the cases where the property was never set on a Token.
One flaw I found, my IDE does not recognize the new property at the t.my_new_prop position.


text:
Q: MANIFEST file processing in JBoss 6 I have an .ear file that contains:

*

*a jar file a.jar with some EJBs whose manifest file refers to jar b.jar in its class-path.

*a jar file b.jar with other EJBs.

This deploys correctly in JBoss 5. However, when trying to deploy in JBoss 6, I get a:
DEPLOYMENTS IN ERROR:
  Deployment "jboss.j2ee:ear=SMS-ear.ear,jar=SMS-ejb.jar,name=TimerServiceDispatcher,service=EJB3" is in error due to the following reason(s): org.jboss.ejb3.common.registrar.spi.DuplicateBindException: Cannot install org.jboss.ejb3.proxy.impl.factory.session.stateless.StatelessSessionLocalProxyFactory@248fd67f under name "ProxyFactory/my-ear/MyEJB/local" as there is already an existing object there:

Where MyEJB ejb belongs to b.jar jar file. If I remove the b.jar entry from the a.jar Manifest file, everything works fine. I am pretty sure the EJB is not duplicated and there are not other EJBs with the same name.
Why does JBoss try to bind EJBs that are referenced from a manifest file a second time?


text:
Q: How would you solve this problem using a hash map instead of a set? def pair_sum(array,r_sum):
  if len(array)<2:
    return
  found = set()
  output= set()
  for num in array:
    k = r_sum - num
    if k not in found:
      found.add(num)
    else:
      output.add(((min(num,k)),(max((num,k)))))
  print('\n'.join(map(str,list(output))))

So for this question, if I have an array for example [4,1,2,5,3] and a target sum of 6 the function will return the two pairs of numbers which add up to the target sum so in this case, it would return (1,5) and (2,4). How would I do something similar using a hash map instead of a set?

A: Your desire to use a hash map instead of a set obviously comes from wanting to reduce the run time from O(n^2) to O(n) where n is the length of the array.
Here is an O(n) implementation using the python dictionary (hash map).
array = [4, 1, 2, 5, 3]
r_sum = 6

found = {}
while array:
    num = array.pop(0)
    k = r_sum - num
    if k in found:
        found[k] = True
    else:
        found[num] = False

for key, val in found.items():
    if val:
        print("({}, {})".format(key, r_sum - key))


text:
Q: SQL Server Select the most recent record only I have a table tat looks like this:
Table1
ID Date       TermDate Cancel
1  20140101   99999999 20140102
1  20140101   20130102 20140102

2  20140108   20130102 20140102
2  20140101   99999999 20140102

3  20140101   99999999 20140102
3  20140101   99999999 20140102
3  20140101   99999999 20140709

What I want to do is, to group by each ID and select only the most recent record.
First I need to check the Date column, from there if a record is more recent then I do not need to check the other columns, in this case, it is ID #2.
If the Date column is the same for same ID, then I want to compare the Cancel column, whichever is the most recent then that record should be shown only, in this case it is ID 3.
If both Date and Cancel columns are the same, then I need to compare the TermDate column and the most recent should be displayed, in this case it is ID #1. All columns are int type.
Basically the result should be:
ID Date       TermDate Cancel
1  20140101   99999999 20140102
2  20140108   20130102 20140102
3  20140101   99999999 20140709

I am not the best person with self join tables and really not sure how to get started with this... what I currently do is: I copy the table into Excel file and then do the job manually...
I am thinking to use CASE Statement but really do not know how to convert my logic to SQL proper code, here is my pseducode:
SELECT (CASE WHEN Date > DATE THEN SELECT the greater Date
        CASE WHEN Date = Date THEN SELECT the grater Cancel
        ELSE WHEN Date = Date AND Cancel = Cancel THEN SELECT the grater TermDate END)
FROM Table1
GROUP BY ID

I don't even know how to make the table look like the above with case statement.
Please let me know what is the best way to do this... I searched online with no help.

A: You can use dense_rank function to assign a rank to each row within one ID based on your ordering and get the first one for each ID:
select id, [date], termdate, cancel from
    (select id, [date], termdate, cancel,
        dense_rank() over (partition by id order by [date] desc, cancel desc, termdate desc) rank
    from table1) X
where rank = 1

SQL Fiddle Demo


text:
Q: Restoring Derby-Database via Java I'm trying to restore an Apache Derby Database via Java. While researching I found the following page http://db.apache.org/derby/docs/10.3/adminguide/tadminhubbkup44.html . As far as I understand I got to have a running connection to the server and use the given URL to make a restore happen.
I'm not sure how to restart and restore the running server in Java using this URL.

A: I have managed to restore the derby database using the backup files created. The problem was that I needed to shut down the database before trying to restore it.
But now I ran into another problem. After the shutdown and the following restore of the database the database doesn't boot automatically. I have tried to register a new driver or to set the shutdown attribute to false but none of that has worked to reboot the database via Java.
This is my code so far:
public boolean restore() throws DataSourceException {
  String databaseName = "jdbc:derby://localhost:1527/sun-appserv-samples;restoreFrom="+ getRestorePath() +"sun-appserv-samples";
  String delete = "jdbc:derby://localhost:1527/sun-appserv-samples;shutdown=true";
  try {
   DriverManager.getConnection(delete);
  } catch (SQLException e) {
   Connection con;
   try {
    con = DriverManager.getConnection(databaseName);
    con.commit();
    try {
     Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
    } catch (ClassNotFoundException e1) {
    } catch (InstantiationException e1) {
    } catch (IllegalAccessException e1) {
    }

    con = DriverManager.getConnection("jdbc:derby://localhost:1527/sun-appserv-samples;create=true");
    con.commit();
    return true;
   } catch (SQLException e1) {
   }
  }
  return false;
 }


text:
Q: Python app with wsgi apache2 returns *.py file content I have a small Flask app that I managed to get running using apache2 and mod-wsgi.
I set it up to run on a subdomain like test.example.com
The app is in /var/www/flasktest .
Now if I go to example.com/flasktest/test.wsgi it returns the contents of the file - the same happens with .py files. If I go to test.example.com the website works.
How do I prevent py, wsgi ..etc files from being up for download. I would love to only allow *.css, *.js, ..etc
Thanks.

A: You should NOT put your code under DocumentRoot. You need a WSGIScriptAlias in that VirtualHost to map the URL you want it to appear as to the WSGI script file where you put it. You need to use the URL given as first argument to WSGIScriptAlias to access it.


text:
Q: SQL Server - Update a column if row is the first record in group How do i identify the first row that has value for each Brand and Category, then update Column "FirstValue" as 1, else 0?
e.g of expected table
Date   |  Brands  |  Category |  Value  | FirstValue
Jan 08 |   A      |  1        | 0       |0
Jan 08 |   A      |  2        | 0       |0
Jan 08 |   A      |  3        | 0       |0
Jan 08 |   B      |  1        | 12      |1
Jan 08 |   B      |  2        | 0       |0
Jan 08 |   B      |  3        | 0       |0
Feb 08 |   A      |  1        | 5       |1
Feb 08 |   A      |  2        | 0       |0
Feb 08 |   A      |  3        | 67      |1
Feb 08 |   B      |  1        | 0       |0
Feb 08 |   B      |  2        | 0       |0
Feb 08 |   B      |  3        | 6       |1

A: Common table expressions are actually updatable, and combining CTEs with ranking functions ROW_NUMBER() gives a perfect solution:
with cte as (
 select row_number() over (partition by Brand, Category order by Date) as rn
, FirstValue
from Table)
update cte
set FirstValue = case when rn = 1 then 1 else 0 end;


text:
Q: How to verify the whole column has the same values I need to verify that a column in web table contains the exact same value for all rows.
I've done some coding but I'm looking for info about how to improve the performance:

*

*I've tried a for loop, using getText method for each row and comparing the value to an expected string:

      List<WebElement> rows = driver.findElements(By.xpath(xxxx))

      for(WebElement e : rows) {
          if(e.getText() != expectedString) {
              throwError
          }
      }

*

*I've also tried Java stream and lambda expressions, however at the end the Collector part is taking a lot of time to process:

        List<String> fetchedValues = rows
           .stream()
           .filter(e -> e.getText() != expectedString)
           .collect(Collectors.toList());

I would like to get info if at least one of the rows does not contain expected String.
Is there any way e.g. with Java to read all values in a given column and load it to ArrayList at once?

A: You can try forEach method described here
Here you have an example:
    @Test
    public void sTest () {
        WebDriverManager.chromedriver().setup();
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.techbeamers.com/handling-html-tables-selenium-webdriver/");
        List<WebElement> el = driver.findElements(By.xpath("//*[@id='post-3500']/div[1]/div/p[3]/a"));
        el.forEach((e)-> {
            if(!e.getText().equals(expectedString)) throwError
        });
        driver.quit();

    }


text:
Q: JavaScript--how to pass scope to reader.onload method I am using the ExtJS Framework.
Inside my reader.onload fn I make an Ajax request and in the success function I call a different function using "this", but "this" is undefined.
reader.onload = function(e){
  //do stuff

  Ext.Ajax.request({
    url:url,
    params:params,
    method:"POST",
    scope:this,
    success:function(resp){
      //decode resp;
      console.log(this);//FileReader obj, not the controller obj this code is in
      if(resp.something){
        this.foo(resp); //this.foo isundefined
      }
    }
  });
};

Elsewhere on SO in another post someone answered passing scope like so:
reader.onload = (function(e){
  //do stuff
}(this));

but when I do that "e" becomes undefined.

A: You can keep a reference to the desired object using something like self.
var self = this;
reader.onload = function(e) {
  ...
  Ext.Ajax.request({
    url:url,
    params:params,
    method:"POST",
    scope:self,
    success:function(resp){
      if(resp.something){
        this.foo(resp);
      }
    }
  });
};


text:
Q: Passing parameters to onchange doesnt use the parameters at runtime Hello I am using function
function prepareRadios(radioGroupName) {
  var radios = document.getElementsByName(radioGroupName);
  for( i = 0; i < radios.length; i++ ) {
    document.getElementById(radios[i].id).onchange = function() {
      radioUpdated(radioGroupName, radios[i].id);
    };
  }
}

the problem is, that the onchange event fires with quote (radioGroupName, radios[i].id) instead of having those values put into it with my function
I need to pass the VALUES of them, not the names of the vars
What am I doing wrong?

A: It's closure-time :)
function prepareRadios(radioGroupName) {
    var radios = document.getElementsByName(radioGroupName);
    for( i = 0; i < radios.length; i++ ) {
        document.getElementById(radios[i].id).onchange = (function(name, id) {
            return function() { radioUpdated(name, id); }
        })(radioGroupName, radios[i].id);
    }
}