问:
Mysql query built my phpmyadmin doesn't work in PHP with WHERE clauses
Just trying to select all rows with no comments, or comments < 5 characters.

Starting from basics, this works:

```<code>$query= "SELECT * FROM `comments`";
$result = mysql_query($query);
</code>```

What doesn't work is:

```<code>$query = "SELECT * FROM `comments` WHERE `comment` = ''";
</code>```

or

```<code>$sql = "SELECT * from comments WHERE LENGTH(comment) < 5 LIMIT 30";
</code>```

I've put limit 5 because when I do a COUNT on the "empty" comments, it says there's 4 bytes there. The column is not NULL (don't blame me, I didn't write it!)

I've even tried using phpmyadmin to change the "empty" values to the word "chicken", then running

So, I used phpmyadmin to change all the instances of comments < 4 characters to the word "chicken".

```<code>$query = "SELECT * FROM `comments` WHERE `comment` = 'chicken'";
</code>```

As with ALL of the above errors, it spews out:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

But if I do

```<code>$emptycomment = "chicken";
$query = sprintf("SELECT * FROM `comments` WHERE `comment` = $emptycomment");
</code>```

Invalid query: Unknown column 'chicken' in 'where clause'

WTF?! But that works perfectly in phpmyadmin! (all above tested on stable and alpha versions)

I also saw where someone else put:

```<code>$query = sprintf("SELECT * FROM `comments` WHERE `comment` = 'chicken'");
</code>```

Again, no dice on any of the above.

The stupid thing is, these all work perfectly directly as a mysql query, and the above were even generated by phpmyadmin!
I've even updated php to 5.3.2, the mysql installed is 5.1.52

I've tried making it EXACTLY as per example 2 here, using variables for everything.
http://php.net/manual/en/function.mysql-query.php

I've followed the tutorial here:
http://www.devshed.com/c/a/MySQL/Null-and-Empty-Strings/3/

I've browsed about 20 articles here at Stackoverflow.

It's 11:15am. I started at 6:30. Getting a bit frustrated here. Thanks!

答:
$emptycomment = "chicken"; $query = sprintf("SELECT * FROM comments WHERE comment = $emptycomment");

Have you tried to print $query after? You missed quotes around string variable

```<code>$query = "SELECT * FROM comments WHERE comment = '" . mysql_real_escape_string($comment) . "'";
</code>```

Body:
Just trying to select all rows with no comments, or comments < 5 characters.

Starting from basics, this works:

$query= "SELECT * FROM `comments`";
$result = mysql_query($query);

What doesn't work is:

$query = "SELECT * FROM `comments` WHERE `comment` = ''";

or

$sql = "SELECT * from comments WHERE LENGTH(comment) < 5 LIMIT 30";

I've put limit 5 because when I do a COUNT on the "empty" comments, it says there's 4 bytes there. The column is not NULL (don't blame me, I didn't write it!)

I've even tried using phpmyadmin to change the "empty" values to the word "chicken", then running

So, I used phpmyadmin to change all the instances of comments < 4 characters to the word "chicken".

$query = "SELECT * FROM `comments` WHERE `comment` = 'chicken'";

As with ALL of the above errors, it spews out:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

But if I do

$emptycomment = "chicken";
$query = sprintf("SELECT * FROM `comments` WHERE `comment` = $emptycomment");

Invalid query: Unknown column 'chicken' in 'where clause'

WTF?! But that works perfectly in phpmyadmin! (all above tested on stable and alpha versions)

I also saw where someone else put:

$query = sprintf("SELECT * FROM `comments` WHERE `comment` = 'chicken'");

Again, no dice on any of the above.

The stupid thing is, these all work perfectly directly as a mysql query, and the above were even generated by phpmyadmin!
I've even updated php to 5.3.2, the mysql installed is 5.1.52

I've tried making it EXACTLY as per example 2 here, using variables for everything.
http://php.net/manual/en/function.mysql-query.php

I've followed the tutorial here:
http://www.devshed.com/c/a/MySQL/Null-and-Empty-Strings/3/

I've browsed about 20 articles here at Stackoverflow.

It's 11:15am. I started at 6:30. Getting a bit frustrated here. Thanks!

Body:
$emptycomment = "chicken"; $query = sprintf("SELECT * FROM comments WHERE comment = $emptycomment");

Have you tried to print $query after? You missed quotes around string variable

$query = "SELECT * FROM comments WHERE comment = '" . mysql_real_escape_string($comment) . "'";


来源: stackexchange

问:
how to delete a chat message which posted in telegram-cli?
I need to delete a message that's posted in chat (private or group or super-group). Is there any command in telegram-cli or other telegram clients that
do this? If not, what should  i do?

I only saw this command delete_msg <msg-id> in telegram-cli wiki page, but i don't know what's <msg-id>.

答:
Finally i found the solution.
When run telegram-cli from command line you must pass -N or --enable-msg-id argument. This will add a sequential number before every message. Now when you want to delete a message with delete-msg you need to pass the number that is before message.

```<code>Telegram-cli version 1.5.1, Copyright (C) 2013-2015 Vitaly Valtman

[Ready] 0> msg Ali Hello
[07:30]  262 Ali <<< Hello
[Ready] 0> msg Ali How r u dude?
[07:30]  263 Ali <<< How r u dude?
[Ready] 0> delete_msg 263
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Finally i found the solution.
When run telegram-cli from command line you must pass -N or --enable-msg-id argument. This will add a sequential number before every message. Now when you want to delete a message with delete-msg you need to pass the number that is before message.

Telegram-cli version 1.5.1, Copyright (C) 2013-2015 Vitaly Valtman

[Ready] 0> msg Ali Hello
[07:30]  262 Ali <<< Hello
[Ready] 0> msg Ali How r u dude?
[07:30]  263 Ali <<< How r u dude?
[Ready] 0> delete_msg 263


问:
Django searching for objects by criteria
I know this question is vague but I am hoping it will promt some interesting responses. I am trying to figure out how to accomplish my next Django project and I am having a hard time. I would like to write a Django app that allows someone to enter their information, for example, their age, gender, marital status, etc. and have it return charitable programs that they may qualify for. So here we go:

An organization would create a program and enter in the type of person it is directed towards. Then someone could input their info and have it return what programs they qualify for. The program criteria as well as the user information would be selected by a form ChoiceField. The problem I am having is figuring out how to make the relation between user information and the program criteria. I have a few ideas on how to make this work but I would love to know how a more experienced programmer would handle this task.

Any information/opinions is encouraged. Thank you.

答:
Not an experienced programmer but I think its all about designing the database schema. Have two models:

Charitable organizations model: I'll define ChoiceField for the kind of people they want to support and then assign value to each choice. Say there are three kind of patients i) Trump Fans ii) Putin Fans  iii) Kim Jong Fans. Then I'll assign value to each option. Trump=0, Putin=1 and Kim=3.

Patients Model: Define model to collect the information about them and one of the field is to get kind of disability they have.

```<code>PATIENTS_TYPE = (
    ('0', 'Trump'),
    ('1', 'Putin'),
    ('2', 'Kim'),
    )
</code>```

Once I have this information, all I have to do is to write if and else statements in views.py to match them.

Body:
Not an experienced programmer but I think its all about designing the database schema. Have two models:

Charitable organizations model: I'll define ChoiceField for the kind of people they want to support and then assign value to each choice. Say there are three kind of patients i) Trump Fans ii) Putin Fans  iii) Kim Jong Fans. Then I'll assign value to each option. Trump=0, Putin=1 and Kim=3.

Patients Model: Define model to collect the information about them and one of the field is to get kind of disability they have.

PATIENTS_TYPE = (
    ('0', 'Trump'),
    ('1', 'Putin'),
    ('2', 'Kim'),
    )

Once I have this information, all I have to do is to write if and else statements in views.py to match them.

ContentLicense: CC BY-SA 4.0


问:
How to convert lowercase string to uppercase string without toUppercase() function
```<code>function alpha()
{
    var a=prompt("Enter String: ");

    for(var b=[i=0];c=a.charCodeAt(i);)
    {
        b[i++]=String.fromCharCode(c|(c>96 && c<123));
    }
    alert(b.join(""))
}
console.log(alpha());
</code>```

<p>So far some letters in the code change when I run this but for some reason it is not changing the string characters to all uppercase. (Example of output; I type "hi" into the prompt and the alert outputs "i" so the h disappears for some reason. </p>

答:
Here's a way to implement it without calling any functions at all:

function myToUpper(string) {
  var map = { a: 'A', b: 'B', c: 'C', d: 'D', e: 'E', f: 'F', g: 'G', h: 'H', i: 'I', j: 'J', k: 'K', l: 'L', m: 'M', n: 'N', o: 'O', p: 'P', q: 'Q', r: 'R', s: 'S', t: 'T', u: 'U', v: 'V', w: 'W', x: 'X', y: 'Y', z: 'Z' }

  var output = ''
  for (var i = 0; i < string.length; i++)
    output += map[string[i]] || string[i]

  return output
}

console.log( myToUpper('ABCdefGHIjkl123.') )   // 'ABCDEFGHIJKL123.'```

Body:
function alpha()
{
    var a=prompt("Enter String: ");

    for(var b=[i=0];c=a.charCodeAt(i);)
    {
        b[i++]=String.fromCharCode(c|(c>96 && c<123));
    }
    alert(b.join(""))
}
console.log(alpha());

So far some letters in the code change when I run this but for some reason it is not changing the string characters to all uppercase. (Example of output; I type "hi" into the prompt and the alert outputs "i" so the h disappears for some reason.


问:
How do I have the meta description/keywords in 2 languages for different pages?
I'm working on a site in Joomla and I've got it in two languages, French and English. Is it possible to have the meta description and keywords in French on the French pages and English on the English ones? If so, how?</p>

答:
Note: My joomla version is 3.6.5. I guess it should be same if you use 3.x.

Go to Extensions > Language(s) > Content Languages

Click the language you want to change the meta tags.

Go to the "Metadata" tab.

You will find "Meta Keywords" and "Meta Description"


问:
Print number of the rows Python
I am trying to print the number of the row in 2d array (list of the list) like:

A B C D E F

1: - - - - - -

2: - - - - - -

I need to print only the number of rows 1:

can someone pls guide me

```<code>def printChart(list):
    print('\n  A  B  C  D  E  F')
    for i in list:
        for e in i:
            print(' ', e, end='')
        print()
    print()
</code>```

答:
From my understanding, you want to add a number to the line.

```<code>def printChart(abc):
    print('\n  A  B  C  D  E  F')
    for x,i in enumerate(abc):
        print(x, ' ', i)

alpha = ["A", "B" , "C" ,"D", "E", "F"]
printChart(alpha)
</code>```

OUTPUT:

```<code>0   A
1   B
2   C
3   D
4   E
5   F
</code>```

Title: Print number of the rows Python

Body:
I am trying to print the number of the row in 2d array (list of the list) like:

A B C D E F

1: - - - - - -

2: - - - - - -

I need to print only the number of rows 1:

can someone pls guide me

def printChart(list):
    print('\n  A  B  C  D  E  F')
    for i in list:
        for e in i:
            print(' ', e, end='')
        print()
    print()

Body:
From my understanding, you want to add a number to the line.

def printChart(abc):
    print('\n  A  B  C  D  E  F')
    for x,i in enumerate(abc):
        print(x, ' ', i)

alpha = ["A", "B" , "C" ,"D", "E", "F"]
printChart(alpha)

OUTPUT:

0   A
1   B
2   C
3   D
4   E
5   F


问:
How to deploy azure webjob automatically via VS Team Services - release
I want to deploy azure webjob using build and release management of visual studio  team services.
I have created a webjob project and I already deployed from visual studio and I am looking to make the deployment automatic.

Thank you!

答:
Refer to these steps to publish/deploy web job:

Open VS 2015 and create a Web Job project (e.g. WebJob1)

Right click the project > Publish As Azure WebJob, then it will create webjob-publish-settings.json file (This is required)

Create a build definition, steps:

NuGet Installer (Path to solution or packages.config: **\*.sln; Installation type: Restore)

Visual Studio Build (Solution: **\*.sln, MSBuild Arguments: /p:DeployOnBuild=true /p:WebPublishMethod=Package /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactstagingdirectory)\\")

Publish Build Artifacts (Path to Publish: $(build.artifactstagingdirectory); Artifact Name: drop; Artifact Type: Server)

Queue build

Create a release definition and link to that build definition(Artifacts tab), tasks:

Azure App Service Deploy (Specify Azure Subscription and App Service name; Package or Folder: $(System.DefaultWorkingDirectory)\**\WebJob1.zip

Create a new release

On the other hand, to configure the Azure service endpoint, you can refer to this blog: Automating Azure Resource Group deployment using a Service Principal in Visual Studio Online: Build/Release Management.


问:
Node.js UDP Multicast over Network
I'm having an issue with a repeated EADDRNOTAVAIL issue on a UDP multicast proof of concept. I have a Linux server sending multicast messages to a Windows client (have tried reversing this to no avail..). The server works correctly when running both the client and the server on the same machine, but not over the same network.

Below is the code I've tried to get this to work with, the IPs I'm using, and the errors I've received.

I'm not sure what I'm doing incorrectly!

Environment

Windows Local IP: 192.168.1.10

Linux Local IP: 192.168.1.11

Server: server.js

```<code>const SRC_PORT = 6025;
const PORT = 6024;
const MULTICAST_ADDR = '239.255.255.250';
const LOCAL_IP = '192.168.1.11';
const dgram = require('dgram');
const server = dgram.createSocket("udp4");

server.bind(SRC_PORT, LOCAL_IP, function () {
  setInterval(function () {
    let message = new Buffer(new Date().toLocaleTimeString());
    server.send(message, 0, message.length, PORT, MULTICAST_ADDR, function () {
      console.log("Sent '" + message + "'");
    });
  }, 4000);
});
</code>```

Client: client.js

```<code>const PORT = 6024;
const MULTICAST_ADDR = '239.255.255.250';
const LOCAL_IP = '192.168.1.10';
const HOST_IP = '192.168.1.11';
const dgram = require('dgram');
const client = dgram.createSocket('udp4');

client.on('listening', function () {
  let address = client.address();
  console.log('UDP Client listening on ' + address.address + ":" + address.port);
});

client.on('message', function (message, rinfo) {
  console.log('Message from: ' + rinfo.address + ':' + rinfo.port + ' - ' + message);
});

//*** Also tried with client.bind(PORT, LOCAL_IP, ... and failed
client.bind(PORT, function () {
  client.addMembership(MULTICAST_ADDR, HOST_IP);
});
</code>```

Error

```<code>dgram.js:508
    throw errnoException(err, 'addMembership');
    ^

Error: addMembership EADDRNOTAVAIL
    at exports._errnoException (util.js:1026:11)
    at Socket.addMembership (dgram.js:508:11)
    at Socket.<anonymous> (~/dev/node-multicast/client.js:16:10)
    at Socket.g (events.js:286:16)
    at emitNone (events.js:91:20)
    at Socket.emit (events.js:185:7)
    at startListening (dgram.js:121:10)
    at dgram.js:228:7
    at _combinedTickCallback (internal/process/next_tick.js:77:11)
</code>```

答:
I'm sure you joined wrong multicastInterface from this error:

addMembership EADDRNOTAVAIL

It should be your address of local interface:
client.addMembership(MULTICAST_ADDR, LOCAL_IP);

As the doc says:

socket.addMembership(multicastAddress[, multicastInterface])

  Tells the kernel to join a multicast group at the given
  multicastAddress and multicastInterface using the IP_ADD_MEMBERSHIP
  socket option. If the multicastInterface argument is not specified,
  the operating system will choose one interface and will add membership
  to it. To add membership to every available interface, call
  addMembership multiple times, once per interface.

Title: Node.js UDP Multicast over Network

Body:
I'm having an issue with a repeated EADDRNOTAVAIL issue on a UDP multicast proof of concept. I have a Linux server sending multicast messages to a Windows client (have tried reversing this to no avail..). The server works correctly when running both the client and the server on the same machine, but not over the same network.

Below is the code I've tried to get this to work with, the IPs I'm using, and the errors I've received.

I'm not sure what I'm doing incorrectly!

Environment

Windows Local IP: 192.168.1.10

Linux Local IP: 192.168.1.11

Server: server.js

const SRC_PORT = 6025;
const PORT = 6024;
const MULTICAST_ADDR = '239.255.255.250';
const LOCAL_IP = '192.168.1.11';
const dgram = require('dgram');
const server = dgram.createSocket("udp4");

server.bind(SRC_PORT, LOCAL_IP, function () {
  setInterval(function () {
    let message = new Buffer(new Date().toLocaleTimeString());
    server.send(message, 0, message.length, PORT, MULTICAST_ADDR, function () {
      console.log("Sent '" + message + "'");
    });
  }, 4000);
});

Client: client.js

const PORT = 6024;
const MULTICAST_ADDR = '239.255.255.250';
const LOCAL_IP = '192.168.1.10';
const HOST_IP = '192.168.1.11';
const dgram = require('dgram');
const client = dgram.createSocket('udp4');

client.on('listening', function () {
  let address = client.address();
  console.log('UDP Client listening on ' + address.address + ":" + address.port);
});

client.on('message', function (message, rinfo) {
  console.log('Message from: ' + rinfo.address + ':' + rinfo.port + ' - ' + message);
});

//*** Also tried with client.bind(PORT, LOCAL_IP, ... and failed
client.bind(PORT, function () {
  client.addMembership(MULTICAST_ADDR, HOST_IP);
});

Error

dgram.js:508
    throw errnoException(err, 'addMembership');
    ^

Error: addMembership EADDRNOTAVAIL
    at exports._errnoException (util.js:1026:11)
    at Socket.addMembership (dgram.js:508:11)
    at Socket.<anonymous> (~/dev/node-multicast/client.js:16:10)
    at Socket.g (events.js:286:16)
    at emitNone (events.js:91:20)
    at Socket.emit (events.js:185:7)
    at startListening (dgram.js:121:10)
    at dgram.js:228:7
    at _combinedTickCallback (internal/process/next_tick.js:77:11)


问:
Animated image in Visual Studio Status bar
Following article explains how to use inbuilt VS animated icon in the status bar.

https://msdn.microsoft.com/en-us/library/bb166795.aspx

I would like to know, is there a way to include custom gif animation inside the status bar.

Bitmap image can be included like following.

https://social.msdn.microsoft.com/Forums/vstudio/en-US/fef208e7-b79d-4a0c-94fe-e6861196e1f5/how-to-show-my-icon-in-exp-visutal-stufo-statusbarsvsstatusbar?forum=vsx#ba47b61c-77a8-46c8-aa10-a04211312e6c

When I point a gif image according to above example, animation is not happening. Please help.

答:
There isn't any way to use a gif animation image directly as far as I know.

Just as the IVsStatusbar.Animation method mentioned:

[in] If the VARIANT is a VT_I2, it refers to the SBAI_Index of
  predefined animated icons. If this parameter is a VT_I4, it refers to
  an HBITMAP containing the filmstrip image for animation, whose width
  should be a multiple of its height.

You can convert your gif file to a BMP image whose width is a multiple of its height by copy and paste every frame of the gif image in the BMP file and then use the code provided in the second link you referred to.

For example, here is a BMP image I created which contains 5 frames for animation:

Save this image as a BMP file, use the code in the second link and debug it:

```<code>private void MenuItemCallback(object sender, EventArgs e)
{
    IVsStatusbar statusBar = (IVsStatusbar)ServiceProvider.GetService(typeof(SVsStatusbar));

    Bitmap b = new Bitmap(@"D:\ani.bmp");
    IntPtr hdc = IntPtr.Zero;
    hdc = b.GetHbitmap();
    object hdcObject = (object)hdc;
    statusBar.Animation(1, ref hdcObject);
    System.Windows.Forms.MessageBox.Show("Click OK to end status bar animation.");
    statusBar.Animation(0, ref hdcObject);
    DeleteObject(hdc);
}
[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
</code>```

You will see the animation in Visual Studio like following:

Body:
There isn't any way to use a gif animation image directly as far as I know.

Just as the IVsStatusbar.Animation method mentioned:

[in] If the VARIANT is a VT_I2, it refers to the SBAI_Index of
  predefined animated icons. If this parameter is a VT_I4, it refers to
  an HBITMAP containing the filmstrip image for animation, whose width
  should be a multiple of its height.

You can convert your gif file to a BMP image whose width is a multiple of its height by copy and paste every frame of the gif image in the BMP file and then use the code provided in the second link you referred to.

For example, here is a BMP image I created which contains 5 frames for animation:

Save this image as a BMP file, use the code in the second link and debug it:

private void MenuItemCallback(object sender, EventArgs e)
{
    IVsStatusbar statusBar = (IVsStatusbar)ServiceProvider.GetService(typeof(SVsStatusbar));

    Bitmap b = new Bitmap(@"D:\ani.bmp");
    IntPtr hdc = IntPtr.Zero;
    hdc = b.GetHbitmap();
    object hdcObject = (object)hdc;
    statusBar.Animation(1, ref hdcObject);
    System.Windows.Forms.MessageBox.Show("Click OK to end status bar animation.");
    statusBar.Animation(0, ref hdcObject);
    DeleteObject(hdc);
}
[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);

You will see the animation in Visual Studio like following:


问:
OCAML confuses defined type with definition?
I am working on an assignment for converting Regular Expressions into an NFA and for converting an NFA to DFA in OCAML. I have been writing my code in a separate file in order to test each "function" individually, but I have come across a problem when using the as-pattern.

NFA Definition:

```<code>(* Imports not shown. *)

let sidx = ref 0
let new_state() = sidx := !sidx + 1; !sidx

type state = int
type states = state BatSet.t
type delta = (state * alphabet, state BatSet.t) BatMap.t
type e_delta = (state, state BatSet.t) BatMap.t
type final = state BatSet.t
type init = state

(* ... *)

type t = states * delta * e_delta * init * final

(* create a new NFA with a single start state *)
let create_new_nfa () =
   let is = new_state () in
      (BatSet.singleton is, BatMap.empty, BatMap.empty, is, BatSet.empty)

(* ... More Function(s) Not Shown.*)
</code>```

When I compile the code below on its own (i.e. I don't use a make file, but rather type the compile command input manually), I have no problem and it works just like how it is suppose too:

```<code>let regex2nfa : Regex.t -> Nfa.t
=fun regex ->
        let ((state, delta, e_delta, init, final) as nfa) = Nfa.create_new_nfa () in (*Line 9*)
        nfa
</code>```

But when I use their make file, it complains by saying the following:

This doesn't make any sense. Nfa.t is of type:

'a * 'b * 'c * 'd * 'e

as shown with its declaration of:

```<code>type t = states * delta * e_delta * init * final
</code>```

If I take out that tuple and just assigned the name "nfa" to the output of the create_new_nfa function, then it compiles just fine, but why on earth is this happening?

For reference, the make file can be found here

答:
Nfa.t is exposed as an abstract type in nfa.mli, so outside of the Nfa module you are not permitted to assume that it is a 5-tuple. Your as-pattern does exactly that, which is why it is rejected.

(The error message could definitely be more helpful.)

Abstract types are an information hiding feature in OCaml that allows the author of a module to prevent details of their implementation being relied on by third party code.

But wait, why does your code compile in the toplevel? I'm not certain, but I suspect that you did something like #useing nfa.ml, which would bypass nfa.mli and allow you to make assumptions about the internals of the Nfa.t type.

Body:
I am working on an assignment for converting Regular Expressions into an NFA and for converting an NFA to DFA in OCAML. I have been writing my code in a separate file in order to test each "function" individually, but I have come across a problem when using the as-pattern.

NFA Definition:

(* Imports not shown. *)

let sidx = ref 0
let new_state() = sidx := !sidx + 1; !sidx

type state = int
type states = state BatSet.t
type delta = (state * alphabet, state BatSet.t) BatMap.t
type e_delta = (state, state BatSet.t) BatMap.t
type final = state BatSet.t
type init = state

(* ... *)

type t = states * delta * e_delta * init * final

(* create a new NFA with a single start state *)
let create_new_nfa () =
   let is = new_state () in
      (BatSet.singleton is, BatMap.empty, BatMap.empty, is, BatSet.empty)

(* ... More Function(s) Not Shown.*)

When I compile the code below on its own (i.e. I don't use a make file, but rather type the compile command input manually), I have no problem and it works just like how it is suppose too:

let regex2nfa : Regex.t -> Nfa.t
=fun regex ->
        let ((state, delta, e_delta, init, final) as nfa) = Nfa.create_new_nfa () in (*Line 9*)
        nfa

But when I use their make file, it complains by saying the following:

This doesn't make any sense. Nfa.t is of type:

'a * 'b * 'c * 'd * 'e

as shown with its declaration of:

type t = states * delta * e_delta * init * final

If I take out that tuple and just assigned the name "nfa" to the output of the create_new_nfa function, then it compiles just fine, but why on earth is this happening?

For reference, the make file can be found here


问:
Youtube api ClassNotFoundException
I'm using maven and jboss WildFly 9 as an application server. When I try to deploy my project I got sticked with this error:

java.lang.ClassNotFoundException:
  com.google.api.client.http.HttpRequestInitializer from [Module
  "deployment.Fanny-ear.ear.Fanny-ejb.jar:main" from Service Module
  Loader]

full error from here :

```<code>    03:24:34,570 ERROR [org.jboss.as.ejb3.invocation] (EJB default - 1) WFLYEJB0034: EJB Invocation failed on component YoutubeService for method public abstract void services.YoutubeServiceRemote.setSearchKey(java.lang.String): javax.ejb.EJBException: WFLYEJB0442: Unexpected Error
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.handleExceptionInOurTx(CMTTxInterceptor.java:184)
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInOurTx(CMTTxInterceptor.java:277)
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.required(CMTTxInterceptor.java:327)
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.processInvocation(CMTTxInterceptor.java:239)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.as.ejb3.remote.EJBRemoteTransactionPropagatingInterceptor.processInvocation(EJBRemoteTransactionPropagatingInterceptor.java:79)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.as.ejb3.component.interceptors.CurrentInvocationContextInterceptor.processInvocation(CurrentInvocationContextInterceptor.java:41)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.as.ejb3.component.invocationmetrics.WaitTimeInterceptor.processInvocation(WaitTimeInterceptor.java:43)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.as.ejb3.security.SecurityContextInterceptor.processInvocation(SecurityContextInterceptor.java:100)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.as.ejb3.component.interceptors.ShutDownInterceptorFactory$1.processInvocation(ShutDownInterceptorFactory.java:64)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.as.ejb3.deployment.processors.EjbSuspendInterceptor.processInvocation(EjbSuspendInterceptor.java:53)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.as.ejb3.component.interceptors.LoggingInterceptor.processInvocation(LoggingInterceptor.java:66)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.as.ee.component.NamespaceContextInterceptor.processInvocation(NamespaceContextInterceptor.java:50)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.as.ejb3.component.interceptors.AdditionalSetupInterceptor.processInvocation(AdditionalSetupInterceptor.java:54)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.invocation.ContextClassLoaderInterceptor.processInvocation(ContextClassLoaderInterceptor.java:64)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.invocation.InterceptorContext.run(InterceptorContext.java:356)
    at org.wildfly.security.manager.WildFlySecurityManager.doChecked(WildFlySecurityManager.java:634)
    at org.jboss.invocation.AccessCheckingInterceptor.processInvocation(AccessCheckingInterceptor.java:61)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.invocation.InterceptorContext.run(InterceptorContext.java:356)
    at org.jboss.invocation.PrivilegedWithCombinerInterceptor.processInvocation(PrivilegedWithCombinerInterceptor.java:80)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61)
    at org.jboss.as.ee.component.ViewService$View.invoke(ViewService.java:195)
    at org.jboss.as.ejb3.remote.protocol.versionone.MethodInvocationMessageHandler.invokeMethod(MethodInvocationMessageHandler.java:331)
    at org.jboss.as.ejb3.remote.protocol.versionone.MethodInvocationMessageHandler.access$100(MethodInvocationMessageHandler.java:69)
    at org.jboss.as.ejb3.remote.protocol.versionone.MethodInvocationMessageHandler$1.run(MethodInvocationMessageHandler.java:202)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
    at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: java.lang.NoClassDefFoundError: com/google/api/client/http/HttpRequestInitializer
    at services.YoutubeService.setSearchKey(YoutubeService.java:27)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.jboss.as.ee.component.ManagedReferenceMethodInterceptor.processInvocation(ManagedReferenceMethodInterceptor.java:52)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:437)
    at org.jboss.as.weld.ejb.Jsr299BindingsInterceptor.doMethodInterception(Jsr299BindingsInterceptor.java:82)
    at org.jboss.as.weld.ejb.Jsr299BindingsInterceptor.processInvocation(Jsr299BindingsInterceptor.java:93)
    at org.jboss.as.ee.component.interceptors.UserInterceptorFactory$1.processInvocation(UserInterceptorFactory.java:63)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.as.ejb3.component.invocationmetrics.ExecutionTimeInterceptor.processInvocation(ExecutionTimeInterceptor.java:43)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.as.jpa.interceptor.SBInvocationInterceptor.processInvocation(SBInvocationInterceptor.java:47)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:437)
    at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:73)
    at org.jboss.as.weld.ejb.EjbRequestScopeActivationInterceptor.processInvocation(EjbRequestScopeActivationInterceptor.java:83)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.as.ee.concurrent.ConcurrentContextInterceptor.processInvocation(ConcurrentContextInterceptor.java:45)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.invocation.InitialInterceptor.processInvocation(InitialInterceptor.java:21)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61)
    at org.jboss.as.ee.component.interceptors.ComponentDispatcherInterceptor.processInvocation(ComponentDispatcherInterceptor.java:52)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.as.ejb3.component.pool.PooledInstanceInterceptor.processInvocation(PooledInstanceInterceptor.java:51)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInOurTx(CMTTxInterceptor.java:275)
    ... 41 more
Caused by: java.lang.ClassNotFoundException: com.google.api.client.http.HttpRequestInitializer from [Module "deployment.Fanny-ear.ear.Fanny-ejb.jar:main" from Service Module Loader]
    at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:205)
    at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:455)
    at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:404)
    at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:385)
    at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:130)
    ... 71 more
</code>```

答: You need to place google-api-client jar in your class path.</p>

Title: Youtube api ClassNotFoundException

Body:
I'm using maven and jboss WildFly 9 as an application server. When I try to deploy my project I got sticked with this error:

java.lang.ClassNotFoundException:
  com.google.api.client.http.HttpRequestInitializer from [Module
  "deployment.Fanny-ear.ear.Fanny-ejb.jar:main" from Service Module
  Loader]

full error from here :

    03:24:34,570 ERROR [org.jboss.as.ejb3.invocation] (EJB default - 1) WFLYEJB0034: EJB Invocation failed on component YoutubeService for method public abstract void services.YoutubeServiceRemote.setSearchKey(java.lang.String): javax.ejb.EJBException: WFLYEJB0442: Unexpected Error
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.handleExceptionInOurTx(CMTTxInterceptor.java:184)
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInOurTx(CMTTxInterceptor.java:277)
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.required(CMTTxInterceptor.java:327)
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.processInvocation(CMTTxInterceptor.java:239)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.as.ejb3.remote.EJBRemoteTransactionPropagatingInterceptor.processInvocation(EJBRemoteTransactionPropagatingInterceptor.java:79)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.as.ejb3.component.interceptors.CurrentInvocationContextInterceptor.processInvocation(CurrentInvocationContextInterceptor.java:41)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.as.ejb3.component.invocationmetrics.WaitTimeInterceptor.processInvocation(WaitTimeInterceptor.java:43)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.as.ejb3.security.SecurityContextInterceptor.processInvocation(SecurityContextInterceptor.java:100)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.as.ejb3.component.interceptors.ShutDownInterceptorFactory$1.processInvocation(ShutDownInterceptorFactory.java:64)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.as.ejb3.deployment.processors.EjbSuspendInterceptor.processInvocation(EjbSuspendInterceptor.java:53)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.as.ejb3.component.interceptors.LoggingInterceptor.processInvocation(LoggingInterceptor.java:66)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.as.ee.component.NamespaceContextInterceptor.processInvocation(NamespaceContextInterceptor.java:50)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.as.ejb3.component.interceptors.AdditionalSetupInterceptor.processInvocation(AdditionalSetupInterceptor.java:54)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.invocation.ContextClassLoaderInterceptor.processInvocation(ContextClassLoaderInterceptor.java:64)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.invocation.InterceptorContext.run(InterceptorContext.java:356)
    at org.wildfly.security.manager.WildFlySecurityManager.doChecked(WildFlySecurityManager.java:634)
    at org.jboss.invocation.AccessCheckingInterceptor.processInvocation(AccessCheckingInterceptor.java:61)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.invocation.InterceptorContext.run(InterceptorContext.java:356)
    at org.jboss.invocation.PrivilegedWithCombinerInterceptor.processInvocation(PrivilegedWithCombinerInterceptor.java:80)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61)
    at org.jboss.as.ee.component.ViewService$View.invoke(ViewService.java:195)
    at org.jboss.as.ejb3.remote.protocol.versionone.MethodInvocationMessageHandler.invokeMethod(MethodInvocationMessageHandler.java:331)
    at org.jboss.as.ejb3.remote.protocol.versionone.MethodInvocationMessageHandler.access$100(MethodInvocationMessageHandler.java:69)
    at org.jboss.as.ejb3.remote.protocol.versionone.MethodInvocationMessageHandler$1.run(MethodInvocationMessageHandler.java:202)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
    at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: java.lang.NoClassDefFoundError: com/google/api/client/http/HttpRequestInitializer
    at services.YoutubeService.setSearchKey(YoutubeService.java:27)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.jboss.as.ee.component.ManagedReferenceMethodInterceptor.processInvocation(ManagedReferenceMethodInterceptor.java:52)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:437)
    at org.jboss.as.weld.ejb.Jsr299BindingsInterceptor.doMethodInterception(Jsr299BindingsInterceptor.java:82)
    at org.jboss.as.weld.ejb.Jsr299BindingsInterceptor.processInvocation(Jsr299BindingsInterceptor.java:93)
    at org.jboss.as.ee.component.interceptors.UserInterceptorFactory$1.processInvocation(UserInterceptorFactory.java:63)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.as.ejb3.component.invocationmetrics.ExecutionTimeInterceptor.processInvocation(ExecutionTimeInterceptor.java:43)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.as.jpa.interceptor.SBInvocationInterceptor.processInvocation(SBInvocationInterceptor.java:47)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:437)
    at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:73)
    at org.jboss.as.weld.ejb.EjbRequestScopeActivationInterceptor.processInvocation(EjbRequestScopeActivationInterceptor.java:83)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.as.ee.concurrent.ConcurrentContextInterceptor.processInvocation(ConcurrentContextInterceptor.java:45)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.invocation.InitialInterceptor.processInvocation(InitialInterceptor.java:21)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61)
    at org.jboss.as.ee.component.interceptors.ComponentDispatcherInterceptor.processInvocation(ComponentDispatcherInterceptor.java:52)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.as.ejb3.component.pool.PooledInstanceInterceptor.processInvocation(PooledInstanceInterceptor.java:51)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInOurTx(CMTTxInterceptor.java:275)
    ... 41 more
Caused by: java.lang.ClassNotFoundException: com.google.api.client.http.HttpRequestInitializer from [Module "deployment.Fanny-ear.ear.Fanny-ejb.jar:main" from Service Module Loader]
    at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:205)
    at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:455)
    at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:404)
    at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:385)
    at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:130)
    ... 71 more


问:
Reshape numpy array and stacking into 3D at regular intervals
I have some time ordered images stored as a numpy 2D array with the shape (60000, 784). I would like to ultimately reshape the data to (1200, 28, 28, 50). What I am trying to do is orient subsequent stacks the 50 28x28 images on top of one another where the top image is the earliest in time.

I think the following code is getting me started, but this returns a list of 1200 images of shape (50, 28, 28). I would like an numpy array that is of shape (1200, 28, 28, 50).

```<code>import numpy as np

X = np.ones((60000, 784))
X = X.reshape(X.shape[0], 28, 28)

X_new = []
prev = 0
for i in range(50, len(X)+50, 50):
    X_new.append(np.dstack( [X[prev:i]] ))
    prev += i

#print type(X_new)     # 'list'
#print len(X_new)      # 1200
#print X_new[0].shape  # (50, 28, 28)
</code>```

答:
I think you need to transpose some axes after reshaping:

```<code>In [792]: X = np.ones((60000,784),int)
In [793]: X1 = X.reshape(1200,50,28,28)
In [794]: X2 = X1.transpose([0,2,3,1])
In [795]: X2.shape
Out[795]: (1200, 28, 28, 50)
</code>```

An array of ones is not very diagnostic, and I'm not about to generate real images of this size.

Small test case:

```<code>In [796]: img = np.arange(12).reshape(3,4)
In [797]: img = img.flatten()
In [798]: img.shape
Out[798]: (12,)
In [799]: X = np.stack([img,img,img,img,img],0)
In [800]: X = np.stack([img,img,img,img,img,img],0)
In [801]: X.shape
Out[801]: (6, 12)
In [802]: X1 = X.reshape(2,3,3,4)
In [803]: X2 = X1.transpose([0,2,3,1])
In [804]: X2.shape
Out[804]: (2, 3, 4, 3)
In [805]: X2[0,:,:,0]
Out[805]:
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
</code>```

Body:
I have some time ordered images stored as a numpy 2D array with the shape (60000, 784). I would like to ultimately reshape the data to (1200, 28, 28, 50). What I am trying to do is orient subsequent stacks the 50 28x28 images on top of one another where the top image is the earliest in time.

I think the following code is getting me started, but this returns a list of 1200 images of shape (50, 28, 28). I would like an numpy array that is of shape (1200, 28, 28, 50).

import numpy as np

X = np.ones((60000, 784))
X = X.reshape(X.shape[0], 28, 28)

X_new = []
prev = 0
for i in range(50, len(X)+50, 50):
    X_new.append(np.dstack( [X[prev:i]] ))
    prev += i

#print type(X_new)     # 'list'
#print len(X_new)      # 1200
#print X_new[0].shape  # (50, 28, 28)

Body:
I think you need to transpose some axes after reshaping:

In [792]: X = np.ones((60000,784),int)
In [793]: X1 = X.reshape(1200,50,28,28)
In [794]: X2 = X1.transpose([0,2,3,1])
In [795]: X2.shape
Out[795]: (1200, 28, 28, 50)

An array of ones is not very diagnostic, and I'm not about to generate real images of this size.

Small test case:

In [796]: img = np.arange(12).reshape(3,4)
In [797]: img = img.flatten()
In [798]: img.shape
Out[798]: (12,)
In [799]: X = np.stack([img,img,img,img,img],0)
In [800]: X = np.stack([img,img,img,img,img,img],0)
In [801]: X.shape
Out[801]: (6, 12)
In [802]: X1 = X.reshape(2,3,3,4)
In [803]: X2 = X1.transpose([0,2,3,1])
In [804]: X2.shape
Out[804]: (2, 3, 4, 3)
In [805]: X2[0,:,:,0]
Out[805]:
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])


问:
find count of element over multiple array
Given two list I need to make a third list which contains elements that occur only twice in over all list 1 and list 2.
How to do it efficienlty with reasonable time and space complexity ?

my solution:
using dictionary:

```<code>from collections import defaultdict

L=['a','b','c','d','a','d','e','e','g','h']
K=['a','g','i','g','g','i','r','r']

d=defaultdict(int)

for i in L:
    d[i]+=1
for j in K:
    d[j]+=1

print d
result=[]
for key,val in d.iteritems():
  if val == 2:
     result.append(key)

print result
</code>```

My desired output would be:

```<code>['e', 'd', 'i', 'r']
</code>```

Can I get a better pythonic solution?

Thanks.

答:
You can use python Counter for getting count of each word in the list. https://docs.python.org/2/library/collections.html#counter-objects

```<code>>>> L=['a','b','c','d','a','d','e','e','g','h']
>>> from collections import Counter
>>> c = Counter(L)
>>> c
Counter({'a': 2, 'd': 2, 'e': 2, 'b': 1, 'c': 1, 'g': 1, 'h': 1})
</code>```

After doing this iterate over counter object and add elements to third list which have value 2.

Body:
Given two list I need to make a third list which contains elements that occur only twice in over all list 1 and list 2.
How to do it efficienlty with reasonable time and space complexity ?

my solution:
using dictionary:

from collections import defaultdict

L=['a','b','c','d','a','d','e','e','g','h']
K=['a','g','i','g','g','i','r','r']

d=defaultdict(int)

for i in L:
    d[i]+=1
for j in K:
    d[j]+=1

print d
result=[]
for key,val in d.iteritems():
  if val == 2:
     result.append(key)

print result

My desired output would be:

['e', 'd', 'i', 'r']

Can I get a better pythonic solution?

Thanks.

Body:
You can use python Counter for getting count of each word in the list. https://docs.python.org/2/library/collections.html#counter-objects

>>> L=['a','b','c','d','a','d','e','e','g','h']
>>> from collections import Counter
>>> c = Counter(L)
>>> c
Counter({'a': 2, 'd': 2, 'e': 2, 'b': 1, 'c': 1, 'g': 1, 'h': 1})

After doing this iterate over counter object and add elements to third list which have value 2.


问:
How to create dynamic folder selection parameter in Jankins pipeline
I am trying to use Jenkins as a tool as an automation build.
So, I need to create a pipline with parameter that helps me to select an appropriate directory where I start a build batch file.
By the moment, I have found how to select a directory as a parameter by usage of Extensible Choice plugin.
But it allows me to select a folder at one level, but I need to go deeper and get an oportunity to select via multilevel directory levels.
For example, select directory at level1 and than at level2 and finaly at level3.
Could you please give me any advise how to do that?</p>

答:
Thanks. I have tried to find any similar example of code or plugin but haven't been succeed with this.
So, I have decided to do that based on a standard groovy syntax. Here is the code:

```<code>node {stage "Directories list output"
          def dirname  = getdirlist()
            echo dirname}
import java.io.File;
import java.io.IOException;
import javax.swing.JFileChooser;
@NonCPS
  def getdirlist() {def initialPath = System.getProperty("user.dir");
        JFileChooser fc = new JFileChooser(initialPath);
        fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        int result = fc.showOpenDialog( null );
            switch ( result ){case JFileChooser.APPROVE_OPTION:
                    File file = fc.getSelectedFile();
                    def path =  fc.getCurrentDirectory().getAbsolutePath();
                    def outputpath="path="+path+"\nfile name="+file.toString();
                    break;
                    case JFileChooser.CANCEL_OPTION:
                    case JFileChooser.ERROR_OPTION:
                    break;}
  return outputpath}
</code>```

I can't make it work. I have some suspitions that Jenkins pipeline doesn't allow to open a standard Java file dialog. What can be another aproach to my task?

Body:
Thanks. I have tried to find any similar example of code or plugin but haven't been succeed with this.
So, I have decided to do that based on a standard groovy syntax. Here is the code:

node {stage "Directories list output"
          def dirname  = getdirlist()
            echo dirname}
import java.io.File;
import java.io.IOException;
import javax.swing.JFileChooser;
@NonCPS
  def getdirlist() {def initialPath = System.getProperty("user.dir");
        JFileChooser fc = new JFileChooser(initialPath);
        fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        int result = fc.showOpenDialog( null );
            switch ( result ){case JFileChooser.APPROVE_OPTION:
                    File file = fc.getSelectedFile();
                    def path =  fc.getCurrentDirectory().getAbsolutePath();
                    def outputpath="path="+path+"\nfile name="+file.toString();
                    break;
                    case JFileChooser.CANCEL_OPTION:
                    case JFileChooser.ERROR_OPTION:
                    break;}
  return outputpath}

I can't make it work. I have some suspitions that Jenkins pipeline doesn't allow to open a standard Java file dialog. What can be another aproach to my task?


问:
Get element with jquery and selenium IDE 1.0.8
I'm trying to get element with jquery and Selenium IDe 1.0.8.

```<code><td>storeValue</td>
<td>$('#result').find('img').filter('[alt="NameOfPhoto"]').eq(0)</td>
<td></td>
</code>```

And in log I get

```<code>[error] Element $('#result').find('img').filter('[alt="NameOfPhoto"]').eq(0) not found
</code>```

When I put this command in firebug I get this element :/

Why it doesn't work ?

EDIT:
Alternatively for example you can give me code how to get id of first object whith JAVA tag at main page of stackoverflow.

TAG:

```<code><a rel="tag" title="show questions tagged 'java'" class="post-tag" href="/questions/tagged/java">java</a>
</code>```

and the example result from :

```<code><div id="question-summary-4303985" class="question-summary narrow">
</code>```

is:

```<code>question-summary-4303985
</code>```

答: Have you bundled jQuery in Selenium jar? If not, you can't use that syntax. </p>

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to get element with jquery and Selenium IDe 1.0.8.

storeValue
$('#result').find('img').filter('[alt="NameOfPhoto"]').eq(0)

And in log I get

[error] Element $('#result').find('img').filter('[alt="NameOfPhoto"]').eq(0) not found

When I put this command in firebug I get this element :/

Why it doesn't work ?

EDIT:
Alternatively for example you can give me code how to get id of first object whith JAVA tag at main page of stackoverflow.

TAG:

java

and the example result from :

is:

question-summary-4303985


问:
Laravel 5.4 detecting variable in developing mode but not in production mode
I am learning laravel and for my practicing purpose I am working on a project. When that app run in local machine it work perfectly but in live server it doesn't. Whats wrong here? I know it's kind of weird but just cant figure it out.

Here is my view

```<code>@foreach($product_details as $product_detail)
    <div data-repeater-item class="mt-repeater-item">
        <div class="mt-repeater-row">
            <div class="col-md-2"></div>
            <div class="col-md-3">
                <label class="control-label">Title</label>
                <input type="hidden" name="indicator_id" value="{{$product_detail->id}}">
                <input name="title" type="text" placeholder="Title" class="form-control" value="{{$product_detail->title}}" /> </div>
            <div class="col-md-6">
                <label class="control-label">Description</label>
                <textarea name="description" type="text" placeholder="Description" class="form-control description content" >{{$product_detail->description}}</textarea> </div>
            <div class="col-md-1">
                <a href="javascript:;" data-repeater-delete class="btn btn-danger mt-repeater-delete">
                    <i class="fa fa-close"></i>
                </a>
            </div>
        </div>
    </div>
@endforeach
</code>```

Here is Controller

```<code>$product_details = IndicatorDetails::where('indicator_id',$id)->get();

return view('admin.indicator.indicator_edit')->with('product_details',$product_details);
</code>```

And Model

```<code>class IndicatorDetails extends Model
{
    protected $fillable = ['title','description','indicator_id'];
    public function indicator()
    {
        return $this->belongsTo(Indicators::class);
    }
}
</code>```

Thanks in advance.

答:
You can try changing ownership of the storage directory so the cache can write to it and the laravel.log can be written to.

This can be achieved with the chgrp
 and chown commands:

```<code>sudo chgrp -R www-data storage bootstrap/cache
sudo chmod -R ug+rwx storage bootstrap/cache
</code>```

Body:
I am learning laravel and for my practicing purpose I am working on a project. When that app run in local machine it work perfectly but in live server it doesn't. Whats wrong here? I know it's kind of weird but just cant figure it out.

Here is my view

@foreach($product_details as $product_detail)

                Title
                <input type="hidden" name="indicator_id" value="{{$product_detail->id}}">
                <input name="title" type="text" placeholder="Title" class="form-control" value="{{$product_detail->title}}" />

                Description
                <textarea name="description" type="text" placeholder="Description" class="form-control description content" >{{$product_detail->description}}</textarea>

@endforeach

Here is Controller

$product_details = IndicatorDetails::where('indicator_id',$id)->get();

return view('admin.indicator.indicator_edit')->with('product_details',$product_details);

And Model

class IndicatorDetails extends Model
{
    protected $fillable = ['title','description','indicator_id'];
    public function indicator()
    {
        return $this->belongsTo(Indicators::class);
    }
}

Thanks in advance.

Body:
You can try changing ownership of the storage directory so the cache can write to it and the laravel.log can be written to.

This can be achieved with the chgrp
 and chown commands:

sudo chgrp -R www-data storage bootstrap/cache
sudo chmod -R ug+rwx storage bootstrap/cache


问:
Avoid zombie processes by regularly calling `join()`
I'm writing a program in Python that runs forever and randomly receives requests
that have to be processed in parallel. Each request can take dozens of minutes
to process and puts some burden on the CPU, so asyncio is not an option. For
each request I start a new worker process.

The problem is, that if I don't call join() on a worker after it's finished,
it turns into a zombie process.

My current solution is to regularly iterate over all worker processes and call
join() on them if they are finished. Is there a more elegant way than using a
timeout on multiprocessing.Queue.get()? Maybe an event driven approach? Or is using a timeout totally fine in this case?
Please see the following code for my
current solution.

```<code>#!/usr/bin/env python3

import multiprocessing as mp
import queue
import random
import time
from typing import List

def main():
    q = mp.Queue()
    p_produce = mp.Process(target=produce, args=(q,))
    p_receive = mp.Process(target=receive, args=(q,))

    p_produce.start()
    p_receive.start()

    p_receive.join()
    p_produce.join()

def produce(q: mp.Queue):
    for i in range(10):
        print(f"put({i})")
        q.put(str(i))
        time.sleep(random.uniform(2.0, 3.0))
    q.put("EOF")

def receive(q: mp.Queue):
    workers = []  # type: List[mp.Process]
    while True:
        to_join = [w for w in workers if not w.is_alive()]
        for p_worker in to_join:
            print(f"Join {p_worker.name}")
            p_worker.join()
            workers.remove(p_worker)

        try:
            request = q.get(block=True, timeout=1)  # Is there a better way?
        except queue.Empty:
            continue

        if request == "EOF":
            break

        p_worker = mp.Process(target=worker, args=(request,), name=request)
        p_worker.start()
        workers.append(p_worker)

    for p_worker in workers:
        print(f"Join {p_worker.name}")
        p_worker.join()

def worker(name: str):
    print(f"Working on {name}")
    time.sleep(random.uniform(2.0, 3.0))

if __name__ == "__main__":
    main()
</code>```

答:
As @Giannis suggested in a comment, you're reinventing a process manager from scratch.  Sticking to what comes with Python, do you have some objection to using multiprocessing.Pool?  If so, what?

The usual way to do this is to pick a maximum number of worker processes you want to run simultaneously.  Say,

```<code>NUM_WORKERS = 4
</code>```

Then drop this in as a replacement for your receive() function:

```<code>def receive(q: mp.Queue):
    pool = mp.Pool(NUM_WORKERS)
    while True:
        request = q.get()
        if request == "EOF":
            break
        pool.apply_async(worker, args=(request,))
    pool.close()
    pool.join()
</code>```

The NUM_WORKERS processes are created once, and reused across tasks.  If for some reason you need (or want) a brand new process for each task, you only need to add maxtasksperchild=1 to the Pool constructor.

And if for some reason you need to know when each task finishes, you could, e.g., add a callback= argument to the apply_async() call and write a little function that will be called when the task ends (and it will receive, as argument, whatever your worker() function returns).

The devil's in the daemons

So it turns out your worker processes in your real app want to (for whatever reasons) create processes of their own, and processes created by Pool can't do that.  They're created as "daemon" processes.  From the docs:

When a process exits, it attempts to terminate all of its daemonic child processes.

Note that a daemonic process is not allowed to create child processes. Otherwise a daemonic process would leave its children orphaned if it gets terminated when its parent process exits.

Pretty much clear as mud ;-)  Here's an elaborate way to roll your own Pool workalike that creates non-daemon processes, but too elaborate for my tastes:

Python Process Pool non-daemonic?

Going back to your original design, which you already know works, I'd just change it to separate the logic of periodically joining worker processes from the logic of manipulating the queue.  Logically, they really have nothing to do with each other.  Specifically, creating a "background thread" to join makes good sense to me:

```<code>def reap(workers, quit):
    from time import sleep
    while not quit.is_set():
        to_join = [w for w in workers if not w.is_alive()]
        for p_worker in to_join:
            print(f"Join {p_worker.name}")
            p_worker.join()
            workers.remove(p_worker)
        sleep(2)  # whatever you like
    for p_worker in workers:
        print(f"Join {p_worker.name}")
        p_worker.join()

def receive(q: mp.Queue):
    import threading
    workers = []  # type: List[mp.Process]
    quit = threading.Event()
    reaper = threading.Thread(target=reap, args=(workers, quit))
    reaper.start()

    while True:
        request = q.get()
        if request == "EOF":
            break
        p_worker = mp.Process(target=worker, args=(request,), name=request)
        p_worker.start()
        workers.append(p_worker)

    quit.set()
    reaper.join()
</code>```

I happen to know that list.append() and list.remove() are thread-safe in CPython, so there's no need to protect those operations with a lock.  But it wouldn't hurt if you added one.

And one more to try

While processes created by Pool are daemonic, it seems that processes created by the similar concurrent.futures.ProcessPoolExecutor are not.  So this simple variation of my first suggestion may work for you (or may not ;-) ):

```<code>NUM_WORKERS = 4

def receive(q: mp.Queue):
    import concurrent.futures as cf
    with cf.ProcessPoolExecutor(NUM_WORKERS) as e:
        while True:
            request = q.get()
            if request == "EOF":
                break
            e.submit(worker, request)
</code>```

If that does work for you, it's hard to imagine anything materially simpler.

Body:
I'm writing a program in Python that runs forever and randomly receives requests
that have to be processed in parallel. Each request can take dozens of minutes
to process and puts some burden on the CPU, so asyncio is not an option. For
each request I start a new worker process.

The problem is, that if I don't call join() on a worker after it's finished,
it turns into a zombie process.

My current solution is to regularly iterate over all worker processes and call
join() on them if they are finished. Is there a more elegant way than using a
timeout on multiprocessing.Queue.get()? Maybe an event driven approach? Or is using a timeout totally fine in this case?
Please see the following code for my
current solution.

#!/usr/bin/env python3

import multiprocessing as mp
import queue
import random
import time
from typing import List

def main():
    q = mp.Queue()
    p_produce = mp.Process(target=produce, args=(q,))
    p_receive = mp.Process(target=receive, args=(q,))

    p_produce.start()
    p_receive.start()

    p_receive.join()
    p_produce.join()

def produce(q: mp.Queue):
    for i in range(10):
        print(f"put({i})")
        q.put(str(i))
        time.sleep(random.uniform(2.0, 3.0))
    q.put("EOF")

def receive(q: mp.Queue):
    workers = []  # type: List[mp.Process]
    while True:
        to_join = [w for w in workers if not w.is_alive()]
        for p_worker in to_join:
            print(f"Join {p_worker.name}")
            p_worker.join()
            workers.remove(p_worker)

        try:
            request = q.get(block=True, timeout=1)  # Is there a better way?
        except queue.Empty:
            continue

        if request == "EOF":
            break

        p_worker = mp.Process(target=worker, args=(request,), name=request)
        p_worker.start()
        workers.append(p_worker)

    for p_worker in workers:
        print(f"Join {p_worker.name}")
        p_worker.join()

def worker(name: str):
    print(f"Working on {name}")
    time.sleep(random.uniform(2.0, 3.0))

if __name__ == "__main__":
    main()

Body:
As @Giannis suggested in a comment, you're reinventing a process manager from scratch.  Sticking to what comes with Python, do you have some objection to using multiprocessing.Pool?  If so, what?

The usual way to do this is to pick a maximum number of worker processes you want to run simultaneously.  Say,

NUM_WORKERS = 4

Then drop this in as a replacement for your receive() function:

def receive(q: mp.Queue):
    pool = mp.Pool(NUM_WORKERS)
    while True:
        request = q.get()
        if request == "EOF":
            break
        pool.apply_async(worker, args=(request,))
    pool.close()
    pool.join()

The NUM_WORKERS processes are created once, and reused across tasks.  If for some reason you need (or want) a brand new process for each task, you only need to add maxtasksperchild=1 to the Pool constructor.

And if for some reason you need to know when each task finishes, you could, e.g., add a callback= argument to the apply_async() call and write a little function that will be called when the task ends (and it will receive, as argument, whatever your worker() function returns).

The devil's in the daemons

So it turns out your worker processes in your real app want to (for whatever reasons) create processes of their own, and processes created by Pool can't do that.  They're created as "daemon" processes.  From the docs:

When a process exits, it attempts to terminate all of its daemonic child processes.

Note that a daemonic process is not allowed to create child processes. Otherwise a daemonic process would leave its children orphaned if it gets terminated when its parent process exits.

Pretty much clear as mud ;-)  Here's an elaborate way to roll your own Pool workalike that creates non-daemon processes, but too elaborate for my tastes:

Python Process Pool non-daemonic?

Going back to your original design, which you already know works, I'd just change it to separate the logic of periodically joining worker processes from the logic of manipulating the queue.  Logically, they really have nothing to do with each other.  Specifically, creating a "background thread" to join makes good sense to me:

def reap(workers, quit):
    from time import sleep
    while not quit.is_set():
        to_join = [w for w in workers if not w.is_alive()]
        for p_worker in to_join:
            print(f"Join {p_worker.name}")
            p_worker.join()
            workers.remove(p_worker)
        sleep(2)  # whatever you like
    for p_worker in workers:
        print(f"Join {p_worker.name}")
        p_worker.join()

def receive(q: mp.Queue):
    import threading
    workers = []  # type: List[mp.Process]
    quit = threading.Event()
    reaper = threading.Thread(target=reap, args=(workers, quit))
    reaper.start()

    while True:
        request = q.get()
        if request == "EOF":
            break
        p_worker = mp.Process(target=worker, args=(request,), name=request)
        p_worker.start()
        workers.append(p_worker)

    quit.set()
    reaper.join()

I happen to know that list.append() and list.remove() are thread-safe in CPython, so there's no need to protect those operations with a lock.  But it wouldn't hurt if you added one.

And one more to try

While processes created by Pool are daemonic, it seems that processes created by the similar concurrent.futures.ProcessPoolExecutor are not.  So this simple variation of my first suggestion may work for you (or may not ;-) ):

NUM_WORKERS = 4

def receive(q: mp.Queue):
    import concurrent.futures as cf
    with cf.ProcessPoolExecutor(NUM_WORKERS) as e:
        while True:
            request = q.get()
            if request == "EOF":
                break
            e.submit(worker, request)

If that does work for you, it's hard to imagine anything materially simpler.


问:
how to sort numerical arraylist in ascending order
I have an ArrayList which I have sorted using Collections.sort.
But the outcome looks like down below. How do I get it to be ascending order?

[0, 1, 11, 12, 12, 13, 13, 14, 14, 16, 16, 16, 17, 17, 17, 18, 18, 19, 2, 2, 20, 20, 20, 21, 21, 22, 4, 7, 7, 7, 8, 9, 9, 9, 9, 9]

答:
Java7: Collections.sort() methods works differently for String and Integer data types.

I assume that you have ArrayList<String>. One solution is to convert it to ArrayList<Integer> and then pass through Collections.sort()

```<code>    ArrayList<String> strList = new ArrayList<String>();
    strList.add("0");
    strList.add("1");
    strList.add("11");
    strList.add("12");
    strList.add("2");
    strList.add("02");
    strList.add("004");
    strList.add("9");
    strList.add("20");

    System.out.println("strList Unsorted :" + strList);
    Collections.sort(strList);
    System.out.println("strList Sorted :" + strList);

    //Convert ArrayList<String> to ArrayList<Integer>
    List<Integer> intList = new ArrayList<Integer>(strList.size());
    for (String strValue : strList) {
        intList.add(Integer.parseInt(strValue));
    }

    System.out.println("intList Unsorted :" + intList);
    Collections.sort(intList);
    System.out.println("intList Sorted :" + intList);
</code>```

Body:
Java7: Collections.sort() methods works differently for String and Integer data types.

I assume that you have ArrayList<String>. One solution is to convert it to ArrayList<Integer> and then pass through Collections.sort()

    ArrayList<String> strList = new ArrayList<String>();
    strList.add("0");
    strList.add("1");
    strList.add("11");
    strList.add("12");
    strList.add("2");
    strList.add("02");
    strList.add("004");
    strList.add("9");
    strList.add("20");

    System.out.println("strList Unsorted :" + strList);
    Collections.sort(strList);
    System.out.println("strList Sorted :" + strList);

    //Convert ArrayList<String> to ArrayList<Integer>
    List<Integer> intList = new ArrayList<Integer>(strList.size());
    for (String strValue : strList) {
        intList.add(Integer.parseInt(strValue));
    }

    System.out.println("intList Unsorted :" + intList);
    Collections.sort(intList);
    System.out.println("intList Sorted :" + intList);


问:
chrome-gnome-shell causing crash?
I am not sure if this has been answered as I am not really sure of the problem. At least once (sometimes more) during the day I get a notice that Ubuntu crashed. The info says it's related to the chrome-gnome-shell(I have reinstalled chrome-gnome-shell). I also can't get my local Gnome extensions to list at: https://extensions.gnome.org/local/. Using the browser console in Firefox, I get the following when I bring up that page:

```<code>Unchecked lastError value: Error: Could not establish connection. Receiving end does not exist.  ExtensionCommon.jsm:265
stderr output from native app org.gnome.chrome_gnome_shell:
stderr output from native app org.gnome.chrome_gnome_shell: (process:13043): GLib-GIO-CRITICAL **: g_application_release: assertion 'application->priv->use_count > 0' failed
stderr output from native app org.gnome.chrome_gnome_shell: [13043] Uncaught exception of type <class 'gi._glib.GError'> occured
stderr output from native app org.gnome.chrome_gnome_shell:   File "/usr/bin/chrome-gnome-shell", line 550, in <module>
stderr output from native app org.gnome.chrome_gnome_shell:     app = ChromeGNOMEShell('--gapplication-service' in sys.argv)
stderr output from native app org.gnome.chrome_gnome_shell:   File "/usr/bin/chrome-gnome-shell", line 67, in __init__
stderr output from native app org.gnome.chrome_gnome_shell:     self.register()
stderr output from native app org.gnome.chrome_gnome_shell: [13043] Exception: GDBus.Error:org.freedesktop.DBus.Error.NoReply: Message did not receive a reply (timeout by message bus)
</code>```

I am running Ubuntu 14.04 Gnome (v3.8.4), Linux kernel 4.4.0-71, Firefox 52.0.2 32-bit.

Any ideas of what is wrong and how to fix it?

答:
You are using old chrome-gnome-shell version.
Just upgrade.</p>

Title: chrome-gnome-shell causing crash?

Body:
I am not sure if this has been answered as I am not really sure of the problem. At least once (sometimes more) during the day I get a notice that Ubuntu crashed. The info says it's related to the chrome-gnome-shell(I have reinstalled chrome-gnome-shell). I also can't get my local Gnome extensions to list at: https://extensions.gnome.org/local/. Using the browser console in Firefox, I get the following when I bring up that page:

Unchecked lastError value: Error: Could not establish connection. Receiving end does not exist.  ExtensionCommon.jsm:265
stderr output from native app org.gnome.chrome_gnome_shell:
stderr output from native app org.gnome.chrome_gnome_shell: (process:13043): GLib-GIO-CRITICAL **: g_application_release: assertion 'application->priv->use_count > 0' failed
stderr output from native app org.gnome.chrome_gnome_shell: [13043] Uncaught exception of type <class 'gi._glib.GError'> occured
stderr output from native app org.gnome.chrome_gnome_shell:   File "/usr/bin/chrome-gnome-shell", line 550, in <module>
stderr output from native app org.gnome.chrome_gnome_shell:     app = ChromeGNOMEShell('--gapplication-service' in sys.argv)
stderr output from native app org.gnome.chrome_gnome_shell:   File "/usr/bin/chrome-gnome-shell", line 67, in __init__
stderr output from native app org.gnome.chrome_gnome_shell:     self.register()
stderr output from native app org.gnome.chrome_gnome_shell: [13043] Exception: GDBus.Error:org.freedesktop.DBus.Error.NoReply: Message did not receive a reply (timeout by message bus)

I am running Ubuntu 14.04 Gnome (v3.8.4), Linux kernel 4.4.0-71, Firefox 52.0.2 32-bit.

Any ideas of what is wrong and how to fix it?


问:
batch file to execute a command in it every 1 minute
i want to create a batch file that executes command in it every 1 minute.

how can i go ahead with this ?

what i want to do is :

download a file from somedomain.com/updates.html to a new file every 1 min. or so
i don't have any .NET framework installed here, so i thought of going with batch files.

After googling a bit a got http://www.chami.com/tips/windows/062598W.html

now what i want is to call 1 command whic downloads & writes a new file every 1 minute.

答:
From http://malektips.com/dos0017.html

Do you need a batch file that waits a certain amount of seconds? In some languages, the command would be WAIT, but DOS and Windows do not come with this command for batch files. If you want to implement the WAIT command:

For DOS, Windows 95, and Windows 98 machines

Create the following batch file and name it WAIT.BAT.

@CHOICE /T:N,%1% > NUL

Now, in order to wait 10 seconds in a batch file, just call the WAIT.BAT batch file as follows:

CALL WAIT 10

For Windows 95, Windows 98, Windows NT, Windows 2000, Windows XP, or Windows 2003 machines

You can use the following WAIT.BAT, as the CHOICE command is not included in the default install on Windows NT, Windows 2000, Windows XP, or Windows 2003:

@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul

The reason for the two lines is that in order to wait using the PING command, you must add extra pings to correctly wait the desired number of seconds. Also, since the PING command is being used, it is possible that this WAIT batch file may run over a few milliseconds. Thus, it is not recommended to use this for critical real-time processing.

Windows XP and Windows 2003 machines

Since Windows XP and 2003 users do not have the CHOICE command, if you find the PING alternative not to your liking, the Windows 2003 Resource Kit has a batch file SLEEP command.


答:
Java 8:</p>

```<code>List<String> numbers = new ArrayList<>();
    // add numbers...
    Collections.sort(numbers, Comparator.comparing(Integer::valueOf));
</code>```

Title: how to sort numerical arraylist in ascending order

Body:
I have an ArrayList which I have sorted using Collections.sort.
But the outcome looks like down below. How do I get it to be ascending order?

[0, 1, 11, 12, 12, 13, 13, 14, 14, 16, 16, 16, 17, 17, 17, 18, 18, 19, 2, 2, 20, 20, 20, 21, 21, 22, 4, 7, 7, 7, 8, 9, 9, 9, 9, 9]

Body:
Java 8:

List<String> numbers = new ArrayList<>();
    // add numbers...
    Collections.sort(numbers, Comparator.comparing(Integer::valueOf));


问:
Bootstrap button sizing and alignment
This is what I have so far http://www.bootply.com/SDIQQr0dZJ or    https://jsfiddle.net/sjgz57b8/

```<code><div class="panel panel-default">
 <div class="panel-heading">
           <strong>myusername</strong>
    <div class="btn-group btn-group-sm pull-right">
       <button type="button" class="btn btn-danger">Dislike</button>
       <button type="button" class="btn btn-success">Like</button>
    </div>
 </div>
     <div class="panel-body">
              Panel content
     </div>
 </div>
</code>```

I'm trying to make the buttons fit within that space and centered vertically, but I already added the btn-group-sm class so I'm not sure what else I can do. I'm also trying to make the dislike button the same width as the like button. Thanks for any help

答:
You missed to include the
 and
. Here you go. I have provided the demo.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        Myusername

          <button type="button" class="btn btn-danger">Dislike</button>
          <button type="button" class="btn btn-success">Like</button>

    Panel content

```

Title: Bootstrap button sizing and alignment

Body:
This is what I have so far http://www.bootply.com/SDIQQr0dZJ or    https://jsfiddle.net/sjgz57b8/

           myusername

       <button type="button" class="btn btn-danger">Dislike</button>
       <button type="button" class="btn btn-success">Like</button>

              Panel content

I'm trying to make the buttons fit within that space and centered vertically, but I already added the btn-group-sm class so I'm not sure what else I can do. I'm also trying to make the dislike button the same width as the like button. Thanks for any help

Body:
You missed to include the <div class="row"> and <div class="col-lg-*">. Here you go. I have provided the demo.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="panel panel-default">
  <div class="panel-heading">
    <div class="row">
      <div class="col-lg-12">
        <strong>Myusername</strong>
        <div class="btn-group btn-group-sm pull-right">
          <button type="button" class="btn btn-danger">Dislike</button>
          <button type="button" class="btn btn-success">Like</button>
        </div>
      </div>
    </div>
  </div>
  <div class="panel-body">
    Panel content
  </div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


问:
Two type models and FirebaseRecyclerAdapter in android
I have two types of product in my firebase db which are the following.

Model : ProductTypeOne.java

```<code>package fyp.hkust.facet.model;

import java.util.ArrayList;

public class ProductTypeOne {

private String name;
private String brand;
private String desc;
private String image;
private String username;
private String uid;
private ArrayList<ArrayList<String>> color;

public Product()
{

}

public Product(String name,String brand, String desc, String image,String username,String uid,ArrayList<ArrayList<String>> color) {
    this.name = name;
    this.brand = brand;
    this.desc = desc;
    this.image = image;
    this.username = username;
    this.uid = uid;
    this.color = color;
}

public String getName() {

    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getBrand() {
    return brand;
}

public void setBrand(String brand) {
    this.brand = brand;
}

public String getDesc() {
    return desc;
}

public void setDesc(String desc) {
    this.desc = desc;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getUid() {
    return uid;
}

public void setUid(String uid) {
    this.uid = uid;
}

public ArrayList<ArrayList<String>> getColor() {
    return color;
}

public void setColor(ArrayList<ArrayList<String>> color) {
    this.color = color;
}

}
</code>```

Model : ProductTypeTwo.java

```<code>package fyp.hkust.facet.model;

import java.util.ArrayList;

public class ProductTypeTwo {

private String name;
private String brand;
private String desc;
private String image;
private String username;
private String uid;
private ArrayList<String> color;

public Product()
{

}

public Product(String name,String brand, String desc, String image,String username,String uid,ArrayList<String> color) {
    this.name = name;
    this.brand = brand;
    this.desc = desc;
    this.image = image;
    this.username = username;
    this.uid = uid;
    this.color = color;
}

public String getName() {

    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getBrand() {
    return brand;
}

public void setBrand(String brand) {
    this.brand = brand;
}

public String getDesc() {
    return desc;
}

public void setDesc(String desc) {
    this.desc = desc;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getUid() {
    return uid;
}

public void setUid(String uid) {
    this.uid = uid;
}

public ArrayList<String> getColor() {
    return color;
}

public void setColor(ArrayList<String> color) {
    this.color = color;
}

}
</code>```

There is an indicator for me to detect that their type. How can I detect their type to choose the right model to get them? Please give me some helps. Thank you very much.

```<code> FirebaseRecyclerAdapter<Product, ProductViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Product, ProductViewHolder>(

            Product.class,
            R.layout.product_row,
            ProductViewHolder.class,
            mDatabase

    ) {
        @Override
        protected void populateViewHolder(ProductViewHolder viewHolder, Product model, int position) {

            Log.d(TAG, "loading view " + position);
            final String product_id = getRef(position).getKey();
            viewHolder.setTitle(model.getName());
            viewHolder.setDesc(model.getDesc());
            viewHolder.setImage(getApplicationContext(), model.getImage());
            viewHolder.setUsername(model.getUsername());

            viewHolder.mView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent productDetailIntent = new Intent();
                    productDetailIntent.setClass(MainActivity.this, ProductDetailActivity.class);
                    productDetailIntent.putExtra("product_id", product_id);
                    Log.d(TAG + " product_id", product_id);
                    startActivity(productDetailIntent);
                }
            });

            Log.d(TAG, "finish loading view");
        }
    };

    mProductList.setAdapter(firebaseRecyclerAdapter);
</code>```

答:
Create Custom Adapter like this

```<code>class PersonAdapter extends FirebaseRecyclerAdapter<Person, RecyclerView.ViewHolder> {

    PersonAdapter(Class<Person> modelClass, DatabaseReference ref) {
        super(modelClass, 0, RecyclerView.ViewHolder.class, ref);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case Person.PersonType.TYPE_1:
                View userType1 = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.item_person_type_1, parent, false);
                return new PersonType1ViewHolder(userType1);
            case Person.PersonType.TYPE_2:
                View userType2 = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.item_person_type_2, parent, false);
                return new PersonType2ViewHolder(userType2);
        }
        return super.onCreateViewHolder(parent, viewType);
    }

    @Override
    protected void populateViewHolder(RecyclerView.ViewHolder viewHolder, Person model,
            int position) {
        if (viewHolder instanceof PersonType1ViewHolder) {
            ((PersonType1ViewHolder) viewHolder).name.setText("Full name: " + model.getName());
            return;
        }

        if (viewHolder instanceof PersonType2ViewHolder) {
            ((PersonType2ViewHolder) viewHolder).name.setText("Full name: " + model.getName());
            ((PersonType2ViewHolder) viewHolder).tvAge.setText("Age: " + model.getAge());
        }
    }

    private class PersonType1ViewHolder extends RecyclerView.ViewHolder {
        TextView name;

        PersonType1ViewHolder(View itemView) {
            super(itemView);
            name = (TextView) itemView.findViewById(R.id.tvName);
        }
    }

    private class PersonType2ViewHolder extends RecyclerView.ViewHolder {
        TextView name;
        TextView tvAge;

        PersonType2ViewHolder(View itemView) {
            super(itemView);
            name = (TextView) itemView.findViewById(R.id.tvName);
            tvAge = (TextView) itemView.findViewById(R.id.tvAge);
        }
    }

    @Override
    public int getItemViewType(int position) {
        return getItem(position).getType();
    }
}
</code>```

Model class (Person)

```<code>public class Person {
    public String name;
    public int age;
    public int type;

    @IntDef({PersonType.TYPE_1, PersonType.TYPE_2 })
    public @interface PersonType {
        int TYPE_1 = 1;
        int TYPE_2 = 2;
    }
    ...
}
</code>```

In Activity

```<code>PersonAdapter adapter = new PersonAdapter(Person.class, myFirebaseRef);
mRecyclerView.setAdapter(adapter);
</code>```

FULL DEMO

My Firebase database json will look like

```<code>{
  "students" : {
    "-KgX6BkMc-zaxk6E7ohB" : {
      "age" : 23,
      "name" : "Linh",
      "type" : 1
    },
    "-KgX6UCjrTYmPgFUrgTY" : {
      "age" : 23,
      "name" : "Linh",
      "type" : 2
    },
    "-KgX7G9MdE8rm0PspZp3" : {
      "age" : 23,
      "name" : "Linh",
      "type" : 1
    },
    "s1" : {
      "age" : 31,
      "name" : "John",
      "type" : 2
    },
    "s2" : {
      "age" : 31,
      "name" : "John",
      "type" : 1
    },
    "s3" : {
      "age" : 31,
      "name" : "John",
      "type" : 2
    },
    "s4" : {
      "age" : 31,
      "name" : "John",
      "type" : 2
    }
  }
}
</code>```

Body:
I have two types of product in my firebase db which are the following.

Model : ProductTypeOne.java

package fyp.hkust.facet.model;

import java.util.ArrayList;

public class ProductTypeOne {

private String name;
private String brand;
private String desc;
private String image;
private String username;
private String uid;
private ArrayList<ArrayList<String>> color;

public Product()
{

}

public Product(String name,String brand, String desc, String image,String username,String uid,ArrayList<ArrayList<String>> color) {
    this.name = name;
    this.brand = brand;
    this.desc = desc;
    this.image = image;
    this.username = username;
    this.uid = uid;
    this.color = color;
}

public String getName() {

    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getBrand() {
    return brand;
}

public void setBrand(String brand) {
    this.brand = brand;
}

public String getDesc() {
    return desc;
}

public void setDesc(String desc) {
    this.desc = desc;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getUid() {
    return uid;
}

public void setUid(String uid) {
    this.uid = uid;
}

public ArrayList<ArrayList<String>> getColor() {
    return color;
}

public void setColor(ArrayList<ArrayList<String>> color) {
    this.color = color;
}

}

Model : ProductTypeTwo.java

package fyp.hkust.facet.model;

import java.util.ArrayList;

public class ProductTypeTwo {

private String name;
private String brand;
private String desc;
private String image;
private String username;
private String uid;
private ArrayList<String> color;

public Product()
{

}

public Product(String name,String brand, String desc, String image,String username,String uid,ArrayList<String> color) {
    this.name = name;
    this.brand = brand;
    this.desc = desc;
    this.image = image;
    this.username = username;
    this.uid = uid;
    this.color = color;
}

public String getName() {

    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getBrand() {
    return brand;
}

public void setBrand(String brand) {
    this.brand = brand;
}

public String getDesc() {
    return desc;
}

public void setDesc(String desc) {
    this.desc = desc;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getUid() {
    return uid;
}

public void setUid(String uid) {
    this.uid = uid;
}

public ArrayList<String> getColor() {
    return color;
}

public void setColor(ArrayList<String> color) {
    this.color = color;
}

}

There is an indicator for me to detect that their type. How can I detect their type to choose the right model to get them? Please give me some helps. Thank you very much.

 FirebaseRecyclerAdapter<Product, ProductViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Product, ProductViewHolder>(

            Product.class,
            R.layout.product_row,
            ProductViewHolder.class,
            mDatabase

    ) {
        @Override
        protected void populateViewHolder(ProductViewHolder viewHolder, Product model, int position) {

            Log.d(TAG, "loading view " + position);
            final String product_id = getRef(position).getKey();
            viewHolder.setTitle(model.getName());
            viewHolder.setDesc(model.getDesc());
            viewHolder.setImage(getApplicationContext(), model.getImage());
            viewHolder.setUsername(model.getUsername());

            viewHolder.mView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent productDetailIntent = new Intent();
                    productDetailIntent.setClass(MainActivity.this, ProductDetailActivity.class);
                    productDetailIntent.putExtra("product_id", product_id);
                    Log.d(TAG + " product_id", product_id);
                    startActivity(productDetailIntent);
                }
            });

            Log.d(TAG, "finish loading view");
        }
    };

    mProductList.setAdapter(firebaseRecyclerAdapter);

Body:
Create Custom Adapter like this

class PersonAdapter extends FirebaseRecyclerAdapter<Person, RecyclerView.ViewHolder> {

    PersonAdapter(Class<Person> modelClass, DatabaseReference ref) {
        super(modelClass, 0, RecyclerView.ViewHolder.class, ref);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case Person.PersonType.TYPE_1:
                View userType1 = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.item_person_type_1, parent, false);
                return new PersonType1ViewHolder(userType1);
            case Person.PersonType.TYPE_2:
                View userType2 = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.item_person_type_2, parent, false);
                return new PersonType2ViewHolder(userType2);
        }
        return super.onCreateViewHolder(parent, viewType);
    }

    @Override
    protected void populateViewHolder(RecyclerView.ViewHolder viewHolder, Person model,
            int position) {
        if (viewHolder instanceof PersonType1ViewHolder) {
            ((PersonType1ViewHolder) viewHolder).name.setText("Full name: " + model.getName());
            return;
        }

        if (viewHolder instanceof PersonType2ViewHolder) {
            ((PersonType2ViewHolder) viewHolder).name.setText("Full name: " + model.getName());
            ((PersonType2ViewHolder) viewHolder).tvAge.setText("Age: " + model.getAge());
        }
    }

    private class PersonType1ViewHolder extends RecyclerView.ViewHolder {
        TextView name;

        PersonType1ViewHolder(View itemView) {
            super(itemView);
            name = (TextView) itemView.findViewById(R.id.tvName);
        }
    }

    private class PersonType2ViewHolder extends RecyclerView.ViewHolder {
        TextView name;
        TextView tvAge;

        PersonType2ViewHolder(View itemView) {
            super(itemView);
            name = (TextView) itemView.findViewById(R.id.tvName);
            tvAge = (TextView) itemView.findViewById(R.id.tvAge);
        }
    }

    @Override
    public int getItemViewType(int position) {
        return getItem(position).getType();
    }
}

Model class (Person)

public class Person {
    public String name;
    public int age;
    public int type;

    @IntDef({PersonType.TYPE_1, PersonType.TYPE_2 })
    public @interface PersonType {
        int TYPE_1 = 1;
        int TYPE_2 = 2;
    }
    ...
}

In Activity

PersonAdapter adapter = new PersonAdapter(Person.class, myFirebaseRef);
mRecyclerView.setAdapter(adapter);

FULL DEMO

My Firebase database json will look like

{
  "students" : {
    "-KgX6BkMc-zaxk6E7ohB" : {
      "age" : 23,
      "name" : "Linh",
      "type" : 1
    },
    "-KgX6UCjrTYmPgFUrgTY" : {
      "age" : 23,
      "name" : "Linh",
      "type" : 2
    },
    "-KgX7G9MdE8rm0PspZp3" : {
      "age" : 23,
      "name" : "Linh",
      "type" : 1
    },
    "s1" : {
      "age" : 31,
      "name" : "John",
      "type" : 2
    },
    "s2" : {
      "age" : 31,
      "name" : "John",
      "type" : 1
    },
    "s3" : {
      "age" : 31,
      "name" : "John",
      "type" : 2
    },
    "s4" : {
      "age" : 31,
      "name" : "John",
      "type" : 2
    }
  }
}