问:
How i can use functions in multiple files, c++
I have a little problem with using multiple files.
I have a task to use three files: function.h, function.cpp, prog.cpp.

In function.h I defined each function.

In function.cpp I put the code of each function.

In prog.cpp I have to call the functions. There i don't have anything defined.

I have these errors:

```<code>"void __cdecl randInt(int *,int)" (?randInt@@YAXPAHH@Z) already defined in function.obj

"void __cdecl showInt(int *,int)" (?showInt@@YAXPAHH@Z) already defined in function.obj

One or more multiply defined symbols found
</code>```

function.cpp:

```<code>#include <iostream>
using namespace std;

void randInt(int *arr, int size) {
    for (int *i = arr; i < arr + size; i++) {
        *i = rand() % 10;
    }

}
void showInt(int *arr, int size) {
    cout << "Int Massive" << endl;
    for (int *i = arr; i < arr + size; i++) {
        cout << *i << ", ";
    }
    cout << endl;
}
</code>```

function.h:

```<code>#pragma once
void randInt(int *, int);
void showInt(int *, int);
</code>```

prog.cpp:

```<code>#include <iostream>
#include <ctime>;
using namespace std;
#include "function.h"
#include "function.cpp"

int main()
{
    srand(time(0));
    int n = 10;
    int *arrInt = new int[10];
    randInt(&arrInt[0], n);
    showInt(&arrInt[0], n);
    return 0;
}
</code>```

答: It is incorrect and unnecessary to include the .cpp file, so remove #include "function.cpp" and you should be fine.

Body:
I have a little problem with using multiple files.
I have a task to use three files: function.h, function.cpp, prog.cpp.

In function.h I defined each function.

In function.cpp I put the code of each function.

In prog.cpp I have to call the functions. There i don't have anything defined.

I have these errors:

"void __cdecl randInt(int *,int)" (?randInt@@YAXPAHH@Z) already defined in function.obj

"void __cdecl showInt(int *,int)" (?showInt@@YAXPAHH@Z) already defined in function.obj

One or more multiply defined symbols found

function.cpp:

#include <iostream>
using namespace std;

void randInt(int *arr, int size) {
    for (int *i = arr; i < arr + size; i++) {
        *i = rand() % 10;
    }

}
void showInt(int *arr, int size) {
    cout << "Int Massive" << endl;
    for (int *i = arr; i < arr + size; i++) {
        cout << *i << ", ";
    }
    cout << endl;
}

function.h:

#pragma once
void randInt(int *, int);
void showInt(int *, int);

prog.cpp:

#include <iostream>
#include <ctime>;
using namespace std;
#include "function.h"
#include "function.cpp"

int main()
{
    srand(time(0));
    int n = 10;
    int *arrInt = new int[10];
    randInt(&arrInt[0], n);
    showInt(&arrInt[0], n);
    return 0;
}


来源: stackexchange

问:
Interleaving lists based on input from a function
I am trying to create a function that interleaves a list of lists. The number of sublists in the main list is defined by user input. I was able to get the interleaved result to work, but it isn't correct simply because I hardcoded variables to store two lists containing interleaved items. I am a beginner using Python and don't have much experience in programming in general.

The code below includes a list constant that contains a list of tuples named inlist. The items in inlist will only be added to a sublist (mylist_a or mylist_b) if they are available, which is indicated by a 1 or 0 in each tuple.

I evaluate each tuple and add only those items that have a 1 in "inlist".

my code:

```<code>inlist = [('apples', 1), ('oranges', 0), ('bananas', 0), ('grapes', 1),
          ('strawberries', 1), ('pears', 1), ('cucumbers', 0), ('lettuce', 0),
          ('tomatos', 0), ('onions', 0), ('garlic', 1), ('pineapples', 1)]

mainlist = []
mylist_a = []
mylist_b = []
counter = 1
for i in inlist:
    if i[1] == 1:
        counter += 1
        if i[1] == 1 and counter % 2 == 0:
            mylist_a += i[0]
        elif i[1] == 1 and counter % 2 == 1:
            mylist_b += i[0]
mainlist = [mylist_a] + [mylist_b]
print 'list a: ' + str(mylist_a), 'list b: ' + str(mylist_b), 'counter % 2: '+str(counter % 2)
print mainlist
</code>```

Output of mainlist:

```<code>>>>[['apples', 'strawberries', 'garlic'], ['grapes', 'pears', 'pineapples']]
</code>```

This method is incorrect because I want the user to define the number of lists using a function and for the items in the "inlist" list to be distributed among all of the lists that are defined.

If the user wants 3 lists, the result would change to something like this:

```<code>>>>[['apples', 'pears'], ['grapes', 'garlic'], ['strawberries', 'pineapples']]
</code>```

答:
You can first create main_list without sublists and then divide them into numbers of sublists based on user input, something like this :

```<code>import more_itertools
inlist = [('apples', 1), ('oranges', 0), ('bananas', 0), ('grapes', 1),
          ('strawberries', 1), ('pears', 1), ('cucumbers', 0), ('lettuce', 0),
          ('tomatos', 0), ('onions', 0), ('garlic', 1), ('pineapples', 1)]
main_list = [txt[0] for txt in inlist if txt[1]]

list_count = 3

sub_lists = [list(elem) for elem in list(more_itertools.distribute(list_count, main_list))]
print sub_lists
</code>```

This will result in :

```<code>[['apples', 'pears'], ['grapes', 'garlic'], ['strawberries', 'pineapples']]
</code>```

You will need to import module more-itertools for this solution to work.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to create a function that interleaves a list of lists. The number of sublists in the main list is defined by user input. I was able to get the interleaved result to work, but it isn't correct simply because I hardcoded variables to store two lists containing interleaved items. I am a beginner using Python and don't have much experience in programming in general.

The code below includes a list constant that contains a list of tuples named inlist. The items in inlist will only be added to a sublist (mylist_a or mylist_b) if they are available, which is indicated by a 1 or 0 in each tuple.

I evaluate each tuple and add only those items that have a 1 in "inlist".

my code:

inlist = [('apples', 1), ('oranges', 0), ('bananas', 0), ('grapes', 1),
          ('strawberries', 1), ('pears', 1), ('cucumbers', 0), ('lettuce', 0),
          ('tomatos', 0), ('onions', 0), ('garlic', 1), ('pineapples', 1)]

mainlist = []
mylist_a = []
mylist_b = []
counter = 1
for i in inlist:
    if i[1] == 1:
        counter += 1
        if i[1] == 1 and counter % 2 == 0:
            mylist_a += i[0]
        elif i[1] == 1 and counter % 2 == 1:
            mylist_b += i[0]
mainlist = [mylist_a] + [mylist_b]
print 'list a: ' + str(mylist_a), 'list b: ' + str(mylist_b), 'counter % 2: '+str(counter % 2)
print mainlist

Output of mainlist:

>>>[['apples', 'strawberries', 'garlic'], ['grapes', 'pears', 'pineapples']]

This method is incorrect because I want the user to define the number of lists using a function and for the items in the "inlist" list to be distributed among all of the lists that are defined.

If the user wants 3 lists, the result would change to something like this:

>>>[['apples', 'pears'], ['grapes', 'garlic'], ['strawberries', 'pineapples']]

Body:
You can first create main_list without sublists and then divide them into numbers of sublists based on user input, something like this :

import more_itertools
inlist = [('apples', 1), ('oranges', 0), ('bananas', 0), ('grapes', 1),
          ('strawberries', 1), ('pears', 1), ('cucumbers', 0), ('lettuce', 0),
          ('tomatos', 0), ('onions', 0), ('garlic', 1), ('pineapples', 1)]
main_list = [txt[0] for txt in inlist if txt[1]]

list_count = 3

sub_lists = [list(elem) for elem in list(more_itertools.distribute(list_count, main_list))]
print sub_lists

This will result in :

[['apples', 'pears'], ['grapes', 'garlic'], ['strawberries', 'pineapples']]

You will need to import module more-itertools for this solution to work.


问:
Error when running G= graph(s,t) in matlab
I want to calculate L = laplacian(G) from a graph dataset. I imported the dataset which contains two columns: FromNodeId and ToNodeId:

```<code># Nodes: 3997962 Edges: 34681189
# FromNodeId    ToNodeId
0   1
0   2
0   31
0   73
0   80
0   113619
0   2468556
0   2823829
0   2823833
0   2846857
0   2947898
0   3011654
0   3701688
0   3849377
0   4036524
0   4036525
0   4036527
0   4036529
0   4036531
0   4036533
0   4036534
0   4036536
0   4036537
1   2
1   3
1   4
1   5
1   6
1   7
1   8
1   9
1   10
1   11
</code>```

To do so, I need to find G first so I use G = graph(FromNodeId, FromNodeId). When I did that, I got this error:

```<code>>> G = graph(fromNodeId,toNodeId)
Error using matlab.internal.graph.MLGraph
Source must be a dense double array of node indices.

Error in matlab.internal.graph.constructFromEdgeList (line 125)
G = underlyingCtor(double(s), double(t), totalNodes);

Error in graph (line 264)
                matlab.internal.graph.constructFromEdgeList(...
</code>```

I don't know why! Can I get a solution of that? Thank you.

答:
Turns out the problem lies in the fact that no zeros are allowed when using the Graph function in this manner. (See: Target must be a dense double array of node indices. How to Solve?)

I downloaded the dataset and ran it successfully with the following code. Note that this code uses a system command and is not compatible with all operating systems, but it should be simple enough to rewrite to whatever operating system you use. It also assumes the .txt file to be in the working directory.

```<code>% Removes first lines with comments in them; this system command was tested on Linux Ubuntu 14.04 and is probably not portable to Windows.
% If this system command doesn't work, manually remove the first four lines from the text file.
system('tail -n +5 com-lj.ungraph.txt > delimitedFile.txt');
% Read the newly created delimited file and add 1 to all nodes.
edges=dlmread('delimitedFile.txt')+1;
% Build the graph
G=graph(edges(:,1),edges(:,2));
</code>```

Assuming you've build your arrays similarly to how I did it, adding 1 to FromNodeIdFull and ToNodeIdFull should resolve your problem. In other words, the following code snippet should solve your problem; if it doesn't I advise you to rewrite based on the code presented above.

```<code>G=graph(FromNodeIdFull+1,ToNodeIdFull+1);
</code>```

Leaving my old answer here, as deleting it may cause confusion for others reading both this answer and the comments to it. Note that the answer below did NOT resolve the issue.

Just putting the comments by myself and NKN into an answer:

The problem lies in the fact that the arrays are sparse but graph() seems to expect full arrays. The following should work:

```<code>FromNodeIdFull=full(double(FromNodeId));
ToNodeIdFull=full(double(ToNodeId));
G=graph(FromNodeIdFull,ToNodeIdFull);
</code>```

Depending on whether your input arrays are already doubles or not you may be able to remove the double() from the first two lines.

Body:
I want to calculate L = laplacian(G) from a graph dataset. I imported the dataset which contains two columns: FromNodeId and ToNodeId:

# Nodes: 3997962 Edges: 34681189
# FromNodeId    ToNodeId
0   1
0   2
0   31
0   73
0   80
0   113619
0   2468556
0   2823829
0   2823833
0   2846857
0   2947898
0   3011654
0   3701688
0   3849377
0   4036524
0   4036525
0   4036527
0   4036529
0   4036531
0   4036533
0   4036534
0   4036536
0   4036537
1   2
1   3
1   4
1   5
1   6
1   7
1   8
1   9
1   10
1   11

To do so, I need to find G first so I use G = graph(FromNodeId, FromNodeId). When I did that, I got this error:

>> G = graph(fromNodeId,toNodeId)
Error using matlab.internal.graph.MLGraph
Source must be a dense double array of node indices.

Error in matlab.internal.graph.constructFromEdgeList (line 125)
G = underlyingCtor(double(s), double(t), totalNodes);

Error in graph (line 264)
                matlab.internal.graph.constructFromEdgeList(...

I don't know why! Can I get a solution of that? Thank you.

Body:
Turns out the problem lies in the fact that no zeros are allowed when using the Graph function in this manner. (See: Target must be a dense double array of node indices. How to Solve?)

I downloaded the dataset and ran it successfully with the following code. Note that this code uses a system command and is not compatible with all operating systems, but it should be simple enough to rewrite to whatever operating system you use. It also assumes the .txt file to be in the working directory.

% Removes first lines with comments in them; this system command was tested on Linux Ubuntu 14.04 and is probably not portable to Windows.
% If this system command doesn't work, manually remove the first four lines from the text file.
system('tail -n +5 com-lj.ungraph.txt > delimitedFile.txt');
% Read the newly created delimited file and add 1 to all nodes.
edges=dlmread('delimitedFile.txt')+1;
% Build the graph
G=graph(edges(:,1),edges(:,2));

Assuming you've build your arrays similarly to how I did it, adding 1 to FromNodeIdFull and ToNodeIdFull should resolve your problem. In other words, the following code snippet should solve your problem; if it doesn't I advise you to rewrite based on the code presented above.

G=graph(FromNodeIdFull+1,ToNodeIdFull+1);

Leaving my old answer here, as deleting it may cause confusion for others reading both this answer and the comments to it. Note that the answer below did NOT resolve the issue.

Just putting the comments by myself and NKN into an answer:

The problem lies in the fact that the arrays are sparse but graph() seems to expect full arrays. The following should work:

FromNodeIdFull=full(double(FromNodeId));
ToNodeIdFull=full(double(ToNodeId));
G=graph(FromNodeIdFull,ToNodeIdFull);

Depending on whether your input arrays are already doubles or not you may be able to remove the double() from the first two lines.


问:
SQL query returning results and need to show as comma separated
I have the following query which works well.

```<code>select     distinct d_invoice.*,
           center.centerid
from       d_invoice
inner join center
on         center.centerid = d_invoice._center
</code>```

Now the above query gives me the dr_id which is the PK of the table d_invoice

With the below query from a different table, it gives me the item_id, as one dr_id can have multiple items:

```<code>select item_id
from   d_invoice_items
where  dr_id = 10
</code>```

I want to join both queries so I can create a new column called as items and it will list down all the item_id in the comma separated.

答:
You can use STUFF and FOR XML PATH something like:

```<code>select distinct d.*,
    c.centerid,
    stuff((
            select ',' + item_id
            from d_invoice_items i
            where i.dr_id = d.dr_id
            for xml path('')
            ), 1, 1, '') as items
from d_invoice d
inner join center c on c.centerid = d._center;
</code>```

Body:
I have the following query which works well.

select     distinct d_invoice.*,
           center.centerid
from       d_invoice
inner join center
on         center.centerid = d_invoice._center

Now the above query gives me the dr_id which is the PK of the table d_invoice

With the below query from a different table, it gives me the item_id, as one dr_id can have multiple items:

select item_id
from   d_invoice_items
where  dr_id = 10

I want to join both queries so I can create a new column called as items and it will list down all the item_id in the comma separated.

Body:
You can use STUFF and FOR XML PATH something like:

select distinct d.*,
    c.centerid,
    stuff((
            select ',' + item_id
            from d_invoice_items i
            where i.dr_id = d.dr_id
            for xml path('')
            ), 1, 1, '') as items
from d_invoice d
inner join center c on c.centerid = d._center;


问:
Nokogiri check if value exists
I'm scraping some web stuff and I get the following error,

scrape.rb:27:in block in ': undefined methodtext' for nil:NilClass (NoMethodError)

when running my ruby task, due to the css not containing any content inside.

Is there a way to check if CSS is not undefined so it wont stop crawling? My code wont work :(

```<code>products.each do |product|

     web = Nokogiri::HTML(open(product))

      counter = products.index(product)

      if web.at_css('.entry-title').text != undefined
      puts "CSS content is not undefined"
      else
      puts "Error"
      end
</code>```

答:
I agree at_css & IF is the best solution for testing a class existence. Here's an example I whipped up..

```<code>user_agents = ["Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:43.0) Gecko/20100101 Firefox/43.0",
            "Mozilla/5.0 (compatible; Konqueror/3; Linux)",
            "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.4) Gecko/20030624",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:43.0) Gecko/20100101 Firefox/43.0",
            "Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.4a) Gecko/20030401",
            "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_2; de-at) AppleWebKit/531.21.8 (KHTML, like Gecko) Version/4.0.4 Safari/531.21.10",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.125 Safari/537.36",
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)",
            "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
            "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
            "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)",
            "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)",
            "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko",
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586",
            "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4b) Gecko/20030516 Mozilla Firebird/0.6",
            "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0",
            "Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B5110e Safari/601.1",
            "Mozilla/5.0 (iPad; CPU OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1",
            "Mozilla/5.0 (Linux; Android 5.1.1; Nexus 7 Build/LMY47V) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.76 Safari/537.36"]
user_agent = user_agents.sample

good_2_go = "https://gomovies.to/genre/action/1"
my_bad = "https://gomovies.to/genre/action/100"

crawls = []
crawls.push(good_2_go, my_bad)

crawls.each do |crawl|
  doc = Nokogiri::HTML(open(crawl, 'User-Agent' => user_agent).read, nil, 'utf-8')

  entries = doc.at_css('.ml-item')

  if entries
      puts crawl
      puts "Found entries class, proceeding with scrape.."
  else
      puts crawl
      puts "Could not find base class for entries"
  end
end
</code>```

This will STDOUT ...

```<code>=> https://gomovies.to/genre/action/1
   Found entries class, proceeding with scrape..
   https://gomovies.to/genre/action/100
   Could not find base class for entries
</code>```

Title: Nokogiri check if value exists

Body:
I'm scraping some web stuff and I get the following error,

scrape.rb:27:in block in ': undefined methodtext' for nil:NilClass (NoMethodError)

when running my ruby task, due to the css not containing any content inside.

Is there a way to check if CSS is not undefined so it wont stop crawling? My code wont work :(

products.each do |product|

     web = Nokogiri::HTML(open(product))

      counter = products.index(product)

      if web.at_css('.entry-title').text != undefined
      puts "CSS content is not undefined"
      else
      puts "Error"
      end

Body:
I agree at_css & IF is the best solution for testing a class existence. Here's an example I whipped up..

user_agents = ["Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:43.0) Gecko/20100101 Firefox/43.0",
            "Mozilla/5.0 (compatible; Konqueror/3; Linux)",
            "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.4) Gecko/20030624",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:43.0) Gecko/20100101 Firefox/43.0",
            "Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.4a) Gecko/20030401",
            "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_2; de-at) AppleWebKit/531.21.8 (KHTML, like Gecko) Version/4.0.4 Safari/531.21.10",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.125 Safari/537.36",
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)",
            "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
            "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
            "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)",
            "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)",
            "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko",
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586",
            "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4b) Gecko/20030516 Mozilla Firebird/0.6",
            "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0",
            "Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B5110e Safari/601.1",
            "Mozilla/5.0 (iPad; CPU OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1",
            "Mozilla/5.0 (Linux; Android 5.1.1; Nexus 7 Build/LMY47V) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.76 Safari/537.36"]
user_agent = user_agents.sample

good_2_go = "https://gomovies.to/genre/action/1"
my_bad = "https://gomovies.to/genre/action/100"

crawls = []
crawls.push(good_2_go, my_bad)

crawls.each do |crawl|
  doc = Nokogiri::HTML(open(crawl, 'User-Agent' => user_agent).read, nil, 'utf-8')

  entries = doc.at_css('.ml-item')

  if entries
      puts crawl
      puts "Found entries class, proceeding with scrape.."
  else
      puts crawl
      puts "Could not find base class for entries"
  end
end

This will STDOUT ...

=> https://gomovies.to/genre/action/1
   Found entries class, proceeding with scrape..
   https://gomovies.to/genre/action/100
   Could not find base class for entries


问:
Css unwanted right margin, sticky footer not fixed
On my site I've got unwanted white margin on the right side, I don't know why. All containers on my site are contained-fluid, and also I added to my css no padding and no margins for containers.

```<code>  html,
page {
    width: 100%!important;
     margin:0;
    font-family: "Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;
    padding-right:0px;
    padding-left:0px;
    color:#333;

}
container, container-fluid {
width:100%0!important;
padding:0!important;
margin:0!important;
}
</code>```

I'd like to put a footer on down of  site, I tried with position: absolute and margin-bottom, also tried overflow hidden but it doesn't work for me.

```<code> <div class="navbar navbar-inverse  navbottom">

   .navbottom {

background: url(../img/footer.jpg) no-repeat center center scroll;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    background-size: cover;
    -o-background-size: cover;
    background-color:#679003;

-moz-border-radius:0px;
border-radius: 0px;
border-style: none;
position: relative;
  margin-top: -50px; /* negative value of footer height */
  height: 50px;
  clear:both;
  padding-top:20px;
overflow:hidden;
margin-bottom:0!important;
</code>```

full html and css
https://jsbin.com/biwuyewipi/edit?html,css,output

site:
http://fotozorza.pl/

答:
Firefox inspector tells me that this is your top nav bar. I am not familiar with Wordpress, so sorry that I am not able to help you more.

Also inspector says, that the rest is fine.

Body:
On my site I've got unwanted white margin on the right side, I don't know why. All containers on my site are contained-fluid, and also I added to my css no padding and no margins for containers.

  html,
page {
    width: 100%!important;
     margin:0;
    font-family: "Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;
    padding-right:0px;
    padding-left:0px;
    color:#333;

}
container, container-fluid {
width:100%0!important;
padding:0!important;
margin:0!important;
}

I'd like to put a footer on down of  site, I tried with position: absolute and margin-bottom, also tried overflow hidden but it doesn't work for me.

   .navbottom {

background: url(../img/footer.jpg) no-repeat center center scroll;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    background-size: cover;
    -o-background-size: cover;
    background-color:#679003;

-moz-border-radius:0px;
border-radius: 0px;
border-style: none;
position: relative;
  margin-top: -50px; /* negative value of footer height */
  height: 50px;
  clear:both;
  padding-top:20px;
overflow:hidden;
margin-bottom:0!important;

full html and css
https://jsbin.com/biwuyewipi/edit?html,css,output

site:
http://fotozorza.pl/


答:
So something like:

```<code>def distribute_sublists(inlist,n=2):
    sub = [x for x,avail in inlist if avail]
    return [sub[i::n] for i in range(n)]
</code>```

where inlist is the list of tuples, and n is the number of "groups" over which you want to divide them. In a first step we construct a subresult sub of all elements that are available. In the second step we using list comprehension and the slice operator i::n to construct a sublist starting from i and make hops of n.

This gives:

```<code>>>> distribute_sublists(inlist,n=1)
[['apples', 'grapes', 'strawberries', 'pears', 'garlic', 'pineapples']]
>>> distribute_sublists(inlist,n=2)
[['apples', 'strawberries', 'garlic'], ['grapes', 'pears', 'pineapples']]
>>> distribute_sublists(inlist,n=3)
[['apples', 'pears'], ['grapes', 'garlic'], ['strawberries', 'pineapples']]
>>> distribute_sublists(inlist,n=4)
[['apples', 'garlic'], ['grapes', 'pineapples'], ['strawberries'], ['pears']]
>>> distribute_sublists(inlist,n=5)
[['apples', 'pineapples'], ['grapes'], ['strawberries'], ['pears'], ['garlic']]
</code>```

So it will distribute the first item to the first list, the second to the second until all n lists have one element, the next element will than be assigned to the first list again and so on in a Round Robin fashion.

The algorithm runs in O(n) with n the number of elements in inlist (not to be confused with the n in the function).

Title: Interleaving lists based on input from a function

Body:
So something like:

def distribute_sublists(inlist,n=2):
    sub = [x for x,avail in inlist if avail]
    return [sub[i::n] for i in range(n)]

where inlist is the list of tuples, and n is the number of "groups" over which you want to divide them. In a first step we construct a subresult sub of all elements that are available. In the second step we using list comprehension and the slice operator i::n to construct a sublist starting from i and make hops of n.

This gives:

>>> distribute_sublists(inlist,n=1)
[['apples', 'grapes', 'strawberries', 'pears', 'garlic', 'pineapples']]
>>> distribute_sublists(inlist,n=2)
[['apples', 'strawberries', 'garlic'], ['grapes', 'pears', 'pineapples']]
>>> distribute_sublists(inlist,n=3)
[['apples', 'pears'], ['grapes', 'garlic'], ['strawberries', 'pineapples']]
>>> distribute_sublists(inlist,n=4)
[['apples', 'garlic'], ['grapes', 'pineapples'], ['strawberries'], ['pears']]
>>> distribute_sublists(inlist,n=5)
[['apples', 'pineapples'], ['grapes'], ['strawberries'], ['pears'], ['garlic']]

So it will distribute the first item to the first list, the second to the second until all n lists have one element, the next element will than be assigned to the first list again and so on in a Round Robin fashion.

The algorithm runs in O(n) with n the number of elements in inlist (not to be confused with the n in the function).


问:
How to get weights from tensorflow fully_connected
I'm trying to extract the weights from a model after training it. Here's a toy example

import tensorflow as tf
import numpy as np

X_ = tf.placeholder(tf.float64, [None, 5], name="Input")
Y_ = tf.placeholder(tf.float64, [None, 1], name="Output")

X = ...
Y = ...
with tf.name_scope("LogReg"):
    pred = fully_connected(X_, 1, activation_fn=tf.nn.sigmoid)
    loss = tf.losses.mean_squared_error(labels=Y_, predictions=pred)
    training_ops = tf.train.GradientDescentOptimizer(0.01).minimize(loss)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(200):
        sess.run(training_ops, feed_dict={
            X_: X,
            Y_: Y
        })
        if (i + 1) % 100 == 0:
            print("Accuracy: ", sess.run(accuracy, feed_dict={
                X_: X,
                Y_: Y
            }))

# Get weights of *pred* here
```

I've looked at Get weights from tensorflow model
 and at the docs but can't find a way to retrieve the value of the weights.

So in the toy example case, suppose that X_ has shape (1000, 5), how can I get the 5 values in the 1-layer weights after

答:
There are some issues in your code that needs to be fixed:

1- You need to use variable_scope instead of name_scope at the following line (please refer to the TensorFlow documentation for difference between them):

```<code>with tf.name_scope("LogReg"):
</code>```

2- To be able to retrieve a variable later in code, you need to know it's name. So, you need to assign a name to the variable of interest (if you don't support one, there will be a default one assigned, but then you need to figure out what it is!):

```<code>pred = tf.contrib.layers.fully_connected(X_, 1, activation_fn=tf.nn.sigmoid, scope = 'fc1')
</code>```

Now let's see how the above fixes can help us to get a variable's value. Each layer has two types of variables: weights and biases. In the following code snippet (a modified version of yours) I will only show how to retrieve the weights for the fully connected layer:

```<code>X_ = tf.placeholder(tf.float64, [None, 5], name="Input")
Y_ = tf.placeholder(tf.float64, [None, 1], name="Output")

X = np.random.randint(1,10,[10,5])
Y = np.random.randint(0,2,[10,1])

with tf.variable_scope("LogReg"):
    pred = tf.fully_connected(X_, 1, activation_fn=tf.nn.sigmoid, scope = 'fc1')
    loss = tf.losses.mean_squared_error(labels=Y_, predictions=pred)
    training_ops = tf.train.GradientDescentOptimizer(0.01).minimize(loss)

with tf.Session() as sess:

    all_vars= tf.global_variables()
    def get_var(name):
        for i in range(len(all_vars)):
            if all_vars[i].name.startswith(name):
                return all_vars[i]
        return None
    fc1_var = get_var('LogReg/fc1/weights')

    sess.run(tf.global_variables_initializer())
    for i in range(200):
        _,fc1_var_np = sess.run([training_ops,fc1_var], feed_dict={
        X_: X,
        Y_: Y
        })
        print fc1_var_np
</code>```

Body:
I'm trying to extract the weights from a model after training it. Here's a toy example

import tensorflow as tf
import numpy as np

X_ = tf.placeholder(tf.float64, [None, 5], name="Input")
Y_ = tf.placeholder(tf.float64, [None, 1], name="Output")

X = ...
Y = ...
with tf.name_scope("LogReg"):
    pred = fully_connected(X_, 1, activation_fn=tf.nn.sigmoid)
    loss = tf.losses.mean_squared_error(labels=Y_, predictions=pred)
    training_ops = tf.train.GradientDescentOptimizer(0.01).minimize(loss)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(200):
        sess.run(training_ops, feed_dict={
            X_: X,
            Y_: Y
        })
        if (i + 1) % 100 == 0:
            print("Accuracy: ", sess.run(accuracy, feed_dict={
                X_: X,
                Y_: Y
            }))

# Get weights of *pred* here

I've looked at Get weights from tensorflow model
 and at the docs but can't find a way to retrieve the value of the weights.

So in the toy example case, suppose that X_ has shape (1000, 5), how can I get the 5 values in the 1-layer weights after

Body:
There are some issues in your code that needs to be fixed:

1- You need to use variable_scope instead of name_scope at the following line (please refer to the TensorFlow documentation for difference between them):

with tf.name_scope("LogReg"):

2- To be able to retrieve a variable later in code, you need to know it's name. So, you need to assign a name to the variable of interest (if you don't support one, there will be a default one assigned, but then you need to figure out what it is!):

pred = tf.contrib.layers.fully_connected(X_, 1, activation_fn=tf.nn.sigmoid, scope = 'fc1')

Now let's see how the above fixes can help us to get a variable's value. Each layer has two types of variables: weights and biases. In the following code snippet (a modified version of yours) I will only show how to retrieve the weights for the fully connected layer:

X_ = tf.placeholder(tf.float64, [None, 5], name="Input")
Y_ = tf.placeholder(tf.float64, [None, 1], name="Output")

X = np.random.randint(1,10,[10,5])
Y = np.random.randint(0,2,[10,1])

with tf.variable_scope("LogReg"):
    pred = tf.fully_connected(X_, 1, activation_fn=tf.nn.sigmoid, scope = 'fc1')
    loss = tf.losses.mean_squared_error(labels=Y_, predictions=pred)
    training_ops = tf.train.GradientDescentOptimizer(0.01).minimize(loss)

with tf.Session() as sess:

    all_vars= tf.global_variables()
    def get_var(name):
        for i in range(len(all_vars)):
            if all_vars[i].name.startswith(name):
                return all_vars[i]
        return None
    fc1_var = get_var('LogReg/fc1/weights')

    sess.run(tf.global_variables_initializer())
    for i in range(200):
        _,fc1_var_np = sess.run([training_ops,fc1_var], feed_dict={
        X_: X,
        Y_: Y
        })
        print fc1_var_np


问:
Interpret Scala syntax for varargs

Possible Duplicate:

  Syntax sugar: _*

I wrote a function that gets passed a format string (for String.format(...)) and a varargs array of parameters (among other things). The method looks like this:

```<code>def myMethod(foo: Number, formatStr: String, params: Any*): Unit = {
  // .. some stuff with foo
  println(formatStr, params.map(_.asInstanceOf[AnyRef]) : _*)
}
</code>```

I got the syntax for the params argument here. It works! But how? I do not understand the syntax of the second argument to println, particularly the ending part (: _*). It is obviously calling map and expanding the array to a sequence of AnyRefs.

答:
The ending part : _* converts a collection into vararg parameters.

It looks weird, I know.

ContentLicense: CC BY-SA 2.5

Title: Interpret Scala syntax for varargs

Body:
Possible Duplicate:

  Syntax sugar: _*

I wrote a function that gets passed a format string (for String.format(...)) and a varargs array of parameters (among other things). The method looks like this:

def myMethod(foo: Number, formatStr: String, params: Any*): Unit = {
  // .. some stuff with foo
  println(formatStr, params.map(_.asInstanceOf[AnyRef]) : _*)
}

I got the syntax for the params argument here. It works! But how? I do not understand the syntax of the second argument to println, particularly the ending part (: _*). It is obviously calling map and expanding the array to a sequence of AnyRefs.


问:
Using touch and sed within a find -ok command
I have some wav files. For each of those files I would like to create a new text file with the same name (obviously with the wav extension being replaced with txt).

I first tried this:

```<code>find . -name *.wav -exec 'touch $(echo '{}" | sed -r 's/[^.]+\$/txt/')" \;
</code>```

which outputted

< touch $(echo {} | sed -r 's/[^.]+$/txt/') ... ./The_stranglers-Golden_brown.wav > ?

Then find complained after I hit y key with:

find: ‘touch $(echo ./music.wav | sed -r 's/[^.]+$/txt/')’: No such file or directory

I figured out I was using a pipe and actually needed a shell. I then ran:

```<code>find . -name *.wav -exec sh -c 'touch $(echo "'{}"\" | sed -r 's/[^.]+\$/txt/')" \;
</code>```

Which did the job.

Actually, I do not really get what is being done internally, but I guess a shell is spawned on every file right ? I fear this is memory costly.

Then, what if I need to run this command on a large bunch of files and directories !?

Now is there a way to do this in a more efficient way ?

Basically I need to transform the current file's name and to feed touch command.

Thank you.

答:
This find with bash parameter-expansion will do the trick for you. You don't need sed at all.

```<code>find . -type f -name "*.wav" -exec sh -c 'x=$1; file="${x##*/}"; woe="${file%.*}"; touch "${woe}.txt"; ' sh {} \;
</code>```

The idea is the part

x=$1 represents each of the entry returned from the output of find

file="${x##*/}" strips the path of the file leaving only the last file name part (only filename.ext)

The part woe="${file%.*}" stores the name without extension, and the new file is created with an extension .txt from the name found.

EDIT

Parameter expansion sets us free from using Command substitution $() sub-process and sed.

After looking at sh man page, I figured out that the command up above could be simplified.

Synopsis -c [-aCefnuvxIimqVEbp] [+aCefnuvxIimqVEbp] [-o option_name] [+o option_name] command_string [command_name [argument ...]]

...

-c Read commands from the command_string operand instead of from the stan‐dard input. Special parameter 0 will be set from the command_name oper‐and and the positional parameters ($1, $2, etc.)  set from the remaining argument operands.

We can directly pass the file path, skipping the shell's name (which is useless inside the script anyway). So {} is passed as the command_name $0 which can be expanded right away.

We end up with a cleaner command.

```<code>find . -name *.wav -exec sh -c 'touch "${0%.*}".txt ;' {} \;
</code>```

Body:
I have some wav files. For each of those files I would like to create a new text file with the same name (obviously with the wav extension being replaced with txt).

I first tried this:

find . -name *.wav -exec 'touch $(echo '{}" | sed -r 's/[^.]+\$/txt/')" \;

which outputted

< touch $(echo {} | sed -r 's/[^.]+$/txt/') ... ./The_stranglers-Golden_brown.wav > ?

Then find complained after I hit y key with:

find: ‘touch $(echo ./music.wav | sed -r 's/[^.]+$/txt/')’: No such file or directory

I figured out I was using a pipe and actually needed a shell. I then ran:

find . -name *.wav -exec sh -c 'touch $(echo "'{}"\" | sed -r 's/[^.]+\$/txt/')" \;

Which did the job.

Actually, I do not really get what is being done internally, but I guess a shell is spawned on every file right ? I fear this is memory costly.

Then, what if I need to run this command on a large bunch of files and directories !?

Now is there a way to do this in a more efficient way ?

Basically I need to transform the current file's name and to feed touch command.

Thank you.

Body:
This find with bash parameter-expansion will do the trick for you. You don't need sed at all.

find . -type f -name "*.wav" -exec sh -c 'x=$1; file="${x##*/}"; woe="${file%.*}"; touch "${woe}.txt"; ' sh {} \;

The idea is the part

x=$1 represents each of the entry returned from the output of find

file="${x##*/}" strips the path of the file leaving only the last file name part (only filename.ext)

The part woe="${file%.*}" stores the name without extension, and the new file is created with an extension .txt from the name found.

EDIT

Parameter expansion sets us free from using Command substitution $() sub-process and sed.

After looking at sh man page, I figured out that the command up above could be simplified.

Synopsis -c [-aCefnuvxIimqVEbp] [+aCefnuvxIimqVEbp] [-o option_name] [+o option_name] command_string [command_name [argument ...]]

...

-c Read commands from the command_string operand instead of from the stan‐dard input. Special parameter 0 will be set from the command_name oper‐and and the positional parameters ($1, $2, etc.)  set from the remaining argument operands.

We can directly pass the file path, skipping the shell's name (which is useless inside the script anyway). So {} is passed as the command_name $0 which can be expanded right away.

We end up with a cleaner command.

find . -name *.wav -exec sh -c 'touch "${0%.*}".txt ;' {} \;


问:
Finding probability
I am trying to find out how I would work out the odds for the results in a coin toss simulator. There is a 50% chance of heads and a 50% of tails.
How would I go about working out the odds of the result it returns happening?
Here is my code:</p>

```<code>import random
head = 0
tail = 0
length  = int(input('How many coins do you want to flip? '))
for i in range(length):
    side = random.randint(0, 1)
    if side == 1:
        head = head + 1
    else:
        tail = tail + 1
print('There where ' + str(tail) + ' tails and ' + str(head) + ' heads')
</code>```

答:
Probabilities of the result that you have got in the simulation can be printed like this:</p>

```<code>print('Tail: ' + str(float(tail) / length) + ' Head ' + str(float(head)/length))
</code>```

Title: Finding probability

Body:
I am trying to find out how I would work out the odds for the results in a coin toss simulator. There is a 50% chance of heads and a 50% of tails.
How would I go about working out the odds of the result it returns happening?
Here is my code:

import random
head = 0
tail = 0
length  = int(input('How many coins do you want to flip? '))
for i in range(length):
    side = random.randint(0, 1)
    if side == 1:
        head = head + 1
    else:
        tail = tail + 1
print('There where ' + str(tail) + ' tails and ' + str(head) + ' heads')

Body:
Probabilities of the result that you have got in the simulation can be printed like this:

print('Tail: ' + str(float(tail) / length) + ' Head ' + str(float(head)/length))


问:
Replace second tuple value in list of tuples
I have a list A, [('a', 3), ('b', 0), ('c',0)], and want to replace ('b',0) with ('b', 13).
And return a new list B, [('a', 3), ('b', 13), ('c',0)]. How do I do this in haskell?

Thanks

答:
You may also do as follows;</p>

```<code>set :: (Char,Int) -> [(Char,Int)] -> [(Char,Int)]
set (k,v) []                  = []
set (k,v) (t:ts) | k == fst t = (k,v) : ts
                 | otherwise  = t : set (k,v) ts
</code>```

Body:
You may also do as follows;

set :: (Char,Int) -> [(Char,Int)] -> [(Char,Int)]
set (k,v) []                  = []
set (k,v) (t:ts) | k == fst t = (k,v) : ts
                 | otherwise  = t : set (k,v) ts


问:
Alfresco for financial data (forms and data lists)
I need to build a solution for financial data analysis comprised of:

```<code>* storage     * forms     * ACL
* workflows   * reports   * custom logic
</code>```

It mainly needs to present forms to different users, collect structured (form) data over different workflows, report do different users etc.

I'm investigating Alfresco as a base platform.

It already has the Alfresco repository for storage with built in ACL and Workflows, and also there is the forms module.

The recent data lists feature seems a good fit, maybe complemented by the WCM.

I am wary as the data list feature is pretty young (and incomplete here there).

How does the Alfresco Repository scale against the reporting needs (intense reads, grouping, computing averages &c)?

Has anyone tried to take alfresco on this path (forms/data/reports platform), is it a good fit, any hurdles on the road, alternative ideas (build your own, use this other solution)?

答:
I can provide a limited answer here. We are using alfresco in production, not strictly for financial data analysis, but we're in the sector.
As such, we have some reports based strictly on the data from alfresco itself. We're still not using the data lists feature, we just recently upgraded from alfresco 3.0 to the newest version, but we do collect information and we do some counting/calculating. It all seems ok, and what's most important, it scales pretty well. Also what's good about alfresco is that depending on "seriousness" of your needs, you can leverage different APIs - javascript scripts are pretty quick to deploy and Java API is good for connecting your alfresco numbers to other numbers.

If you decide to take it the alfresco road, I will suggest to hire experienced alfresco developer for initial setup - as some not-so-smart choices in the beginning cost you a great deal later down the path.

Body:
I need to build a solution for financial data analysis comprised of:

* storage     * forms     * ACL
* workflows   * reports   * custom logic

It mainly needs to present forms to different users, collect structured (form) data over different workflows, report do different users etc.

I'm investigating Alfresco as a base platform.

It already has the Alfresco repository for storage with built in ACL and Workflows, and also there is the forms module.

The recent data lists feature seems a good fit, maybe complemented by the WCM.

I am wary as the data list feature is pretty young (and incomplete here there).

How does the Alfresco Repository scale against the reporting needs (intense reads, grouping, computing averages &c)?

Has anyone tried to take alfresco on this path (forms/data/reports platform), is it a good fit, any hurdles on the road, alternative ideas (build your own, use this other solution)?


问:
Convert dd-mm-yyyy string to date
i am trying to convert a string in the format dd-mm-yyyy into a date object in JavaScript using the following:

```<code> var from = $("#datepicker").val();
 var to = $("#datepickertwo").val();
 var f = new Date(from);
 var t = new Date(to);
</code>```

("#datepicker").val() contains a date in the format dd-mm-yyyy.
When I do the following, I get "Invalid Date":

```<code>alert(f);
</code>```

Is this because of the '-' symbol? How can I overcome this?

答:
```<code>new Date().toLocaleDateString();
</code>```

simple as that, just pass your date to js Date Object

Title: Convert dd-mm-yyyy string to date

Body:
i am trying to convert a string in the format dd-mm-yyyy into a date object in JavaScript using the following:

 var from = $("#datepicker").val();
 var to = $("#datepickertwo").val();
 var f = new Date(from);
 var t = new Date(to);

("#datepicker").val() contains a date in the format dd-mm-yyyy.
When I do the following, I get "Invalid Date":

alert(f);

Is this because of the '-' symbol? How can I overcome this?

Body:
new Date().toLocaleDateString();

simple as that, just pass your date to js Date Object


问:
This is a bug in Date class or i mistake (Java/android)
i write this code

```<code>Date xx2 = new Date(2017,3,31);
Date xx3 = new Date(2017,4,1);

Assistance.print("--> y:"+xx2.getYear()+"  m:"+xx2.getMonth()+" d:"+xx2.getDate());
Assistance.print("--> y:"+xx3.getYear()+"  m:"+xx3.getMonth()+" d:"+xx3.getDate());
</code>```

but i get same result !!!

Result:

--> y: 2017  m:4   d:1

--> y: 2017  m:4   d:1

What?

答: Months are 0 indexed. January == 0, so Date xx2 is April 31st. There is no such date on the calendar. The 31st day from the start of April is May 1st. That is why both dates are the same.

Body:
i write this code

Date xx2 = new Date(2017,3,31);
Date xx3 = new Date(2017,4,1);

Assistance.print("--> y:"+xx2.getYear()+"  m:"+xx2.getMonth()+" d:"+xx2.getDate());
Assistance.print("--> y:"+xx3.getYear()+"  m:"+xx3.getMonth()+" d:"+xx3.getDate());

but i get same result !!!

Result:

--> y: 2017  m:4   d:1

--> y: 2017  m:4   d:1

What?


答:
This filters the list and then deinterweaves it.

```<code>inlist = [('apples', 1), ('oranges', 0), ('bananas', 0), ('grapes', 1),
          ('strawberries', 1), ('pears', 1), ('cucumbers', 0), ('lettuce', 0),
          ('tomatos', 0), ('onions', 0), ('garlic', 1), ('pineapples', 1)]

from itertools import cycle, izip

def deinterweave(L, n):
    r = [list() for _ in range(n)]
    for item, o in izip(L, cycle(r)):
        o.append(item)
    return r

filtered = [item for item, flag in inlist if flag == 1]

print deinterweave(filtered, 2)
print deinterweave(filtered, 3)
</code>```

Shows that:

```<code>>>> print deinterweave(filtered, 2)
[['apples', 'strawberries', 'garlic'], ['grapes', 'pears', 'pineapples']]
>>> print deinterweave(filtered, 3)
[['apples', 'pears'], ['grapes', 'garlic'], ['strawberries', 'pineapples']]
</code>```

Body:
I am trying to create a function that interleaves a list of lists. The number of sublists in the main list is defined by user input. I was able to get the interleaved result to work, but it isn't correct simply because I hardcoded variables to store two lists containing interleaved items. I am a beginner using Python and don't have much experience in programming in general.

The code below includes a list constant that contains a list of tuples named inlist. The items in inlist will only be added to a sublist (mylist_a or mylist_b) if they are available, which is indicated by a 1 or 0 in each tuple.

I evaluate each tuple and add only those items that have a 1 in "inlist".

my code:

inlist = [('apples', 1), ('oranges', 0), ('bananas', 0), ('grapes', 1),
          ('strawberries', 1), ('pears', 1), ('cucumbers', 0), ('lettuce', 0),
          ('tomatos', 0), ('onions', 0), ('garlic', 1), ('pineapples', 1)]

mainlist = []
mylist_a = []
mylist_b = []
counter = 1
for i in inlist:
    if i[1] == 1:
        counter += 1
        if i[1] == 1 and counter % 2 == 0:
            mylist_a += i[0]
        elif i[1] == 1 and counter % 2 == 1:
            mylist_b += i[0]
mainlist = [mylist_a] + [mylist_b]
print 'list a: ' + str(mylist_a), 'list b: ' + str(mylist_b), 'counter % 2: '+str(counter % 2)
print mainlist

Output of mainlist:

>>>[['apples', 'strawberries', 'garlic'], ['grapes', 'pears', 'pineapples']]

This method is incorrect because I want the user to define the number of lists using a function and for the items in the "inlist" list to be distributed among all of the lists that are defined.

If the user wants 3 lists, the result would change to something like this:

>>>[['apples', 'pears'], ['grapes', 'garlic'], ['strawberries', 'pineapples']]

Body:
This filters the list and then deinterweaves it.

inlist = [('apples', 1), ('oranges', 0), ('bananas', 0), ('grapes', 1),
          ('strawberries', 1), ('pears', 1), ('cucumbers', 0), ('lettuce', 0),
          ('tomatos', 0), ('onions', 0), ('garlic', 1), ('pineapples', 1)]

from itertools import cycle, izip

def deinterweave(L, n):
    r = [list() for _ in range(n)]
    for item, o in izip(L, cycle(r)):
        o.append(item)
    return r

filtered = [item for item, flag in inlist if flag == 1]

print deinterweave(filtered, 2)
print deinterweave(filtered, 3)

Shows that:

>>> print deinterweave(filtered, 2)
[['apples', 'strawberries', 'garlic'], ['grapes', 'pears', 'pineapples']]
>>> print deinterweave(filtered, 3)
[['apples', 'pears'], ['grapes', 'garlic'], ['strawberries', 'pineapples']]


问:
Uploading using FTP but website not adapting to changes (not cache)
I am developing a Wordpress theme for a blog I want to start.

I am using Dreamweaver to upload my files to the server using FTP. It appears that the FTP is working perfectly. I have edited files, uploaded, then checked on the server and the changes are being made.

The problem is the changed are not showing up on my website. They are showing up maybe 5 - 10 minutes after, if at all. The strange thing is .css files work and update perfectly, but the .php files do not.

The issue does not appear to be the cache. I am clearing cache, doing hard-refreshes and using incognito to develop.

答:
change your css links to

```<code><link href="stack.css?ver=<?php echo rand(1,10000) ?>">
</code>```

this may help

Body:
change your css links to

<link href="stack.css?ver=<?php echo rand(1,10000) ?>">

this may help


问:
Android: Expand/collapse animation
Let's say I have a vertical linearLayout with :

```<code>[v1]
[v2]
</code>```

By default v1 has visibily = GONE. I would like to show v1 with an expand animation and push down v2 at the same time.

I tried something like this:

```<code>Animation a = new Animation()
{
    int initialHeight;

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        final int newHeight = (int)(initialHeight * interpolatedTime);
        v.getLayoutParams().height = newHeight;
        v.requestLayout();
    }

    @Override
    public void initialize(int width, int height, int parentWidth, int parentHeight) {
        super.initialize(width, height, parentWidth, parentHeight);
        initialHeight = height;
    }

    @Override
    public boolean willChangeBounds() {
        return true;
    }
};
</code>```

But with this solution, I have a blink when the animation starts. I think it's caused by v1 displaying full size before the animation is applied.

With javascript, this is one line of jQuery! Any simple way to do this with android?

答:
Adding to Tom Esterez's excellent answer and Erik B's excellent update to it, I thought I'd post my own take, compacting the expand and contract methods into one. This way, you could for example have an action like this...

```<code>button.setOnClickListener(v -> expandCollapse(view));
</code>```

... which calls the method below and letting it figure out what to do after each onClick()...

```<code>public static void expandCollapse(View view) {

    boolean expand = view.getVisibility() == View.GONE;
    Interpolator easeInOutQuart = PathInterpolatorCompat.create(0.77f, 0f, 0.175f, 1f);

    view.measure(
        View.MeasureSpec.makeMeasureSpec(((View) view.getParent()).getWidth(), View.MeasureSpec.EXACTLY),
        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
    );

    int height = view.getMeasuredHeight();
    int duration = (int) (height/view.getContext().getResources().getDisplayMetrics().density);

    Animation animation = new Animation() {
        @Override protected void applyTransformation(float interpolatedTime, Transformation t) {
            if (expand) {
                view.getLayoutParams().height = 1;
                view.setVisibility(View.VISIBLE);
                if (interpolatedTime == 1) {
                    view.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT;
                } else {
                    view.getLayoutParams().height = (int) (height * interpolatedTime);
                }
                view.requestLayout();
            } else {
                if (interpolatedTime == 1) {
                    view.setVisibility(View.GONE);
                } else {
                    view.getLayoutParams().height = height - (int) (height * interpolatedTime);
                    view.requestLayout();
                }
            }
        }
        @Override public boolean willChangeBounds() {
            return true;
        }
    };

    animation.setInterpolator(easeInOutQuart);
    animation.setDuration(duration);
    view.startAnimation(animation);

}
</code>```

Title: Android: Expand/collapse animation

Body:
Let's say I have a vertical linearLayout with :

[v1]
[v2]

By default v1 has visibily = GONE. I would like to show v1 with an expand animation and push down v2 at the same time.

I tried something like this:

Animation a = new Animation()
{
    int initialHeight;

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        final int newHeight = (int)(initialHeight * interpolatedTime);
        v.getLayoutParams().height = newHeight;
        v.requestLayout();
    }

    @Override
    public void initialize(int width, int height, int parentWidth, int parentHeight) {
        super.initialize(width, height, parentWidth, parentHeight);
        initialHeight = height;
    }

    @Override
    public boolean willChangeBounds() {
        return true;
    }
};

But with this solution, I have a blink when the animation starts. I think it's caused by v1 displaying full size before the animation is applied.

With javascript, this is one line of jQuery! Any simple way to do this with android?

Body:
Adding to Tom Esterez's excellent answer and Erik B's excellent update to it, I thought I'd post my own take, compacting the expand and contract methods into one. This way, you could for example have an action like this...

button.setOnClickListener(v -> expandCollapse(view));

... which calls the method below and letting it figure out what to do after each onClick()...

public static void expandCollapse(View view) {

    boolean expand = view.getVisibility() == View.GONE;
    Interpolator easeInOutQuart = PathInterpolatorCompat.create(0.77f, 0f, 0.175f, 1f);

    view.measure(
        View.MeasureSpec.makeMeasureSpec(((View) view.getParent()).getWidth(), View.MeasureSpec.EXACTLY),
        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
    );

    int height = view.getMeasuredHeight();
    int duration = (int) (height/view.getContext().getResources().getDisplayMetrics().density);

    Animation animation = new Animation() {
        @Override protected void applyTransformation(float interpolatedTime, Transformation t) {
            if (expand) {
                view.getLayoutParams().height = 1;
                view.setVisibility(View.VISIBLE);
                if (interpolatedTime == 1) {
                    view.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT;
                } else {
                    view.getLayoutParams().height = (int) (height * interpolatedTime);
                }
                view.requestLayout();
            } else {
                if (interpolatedTime == 1) {
                    view.setVisibility(View.GONE);
                } else {
                    view.getLayoutParams().height = height - (int) (height * interpolatedTime);
                    view.requestLayout();
                }
            }
        }
        @Override public boolean willChangeBounds() {
            return true;
        }
    };

    animation.setInterpolator(easeInOutQuart);
    animation.setDuration(duration);
    view.startAnimation(animation);

}


问:
PHP MySQL order by first column, if second NULL
I have table:

```<code>id  |  post_date  |  bumped_post_date
1   |    date     |       NULL
2   |    date     |       date2
</code>```

Ok, I know how to order by post_date, but I wan't to order by post_date only when bumped_post_date is NULL.

When bumped_post_date is not NULL, then order by it, not by post_date ( But if NULL, then order by post_date ). Thanks and sorry for my bad English.

答:
```<code>ORDER BY COALESCE( bumped_post_date, post_date )
</code>```

Coalesce() function returns the first non-null argument.

Body:
I have table:

id  |  post_date  |  bumped_post_date
1   |    date     |       NULL
2   |    date     |       date2

Ok, I know how to order by post_date, but I wan't to order by post_date only when bumped_post_date is NULL.

When bumped_post_date is not NULL, then order by it, not by post_date ( But if NULL, then order by post_date ). Thanks and sorry for my bad English.

Body:
ORDER BY COALESCE( bumped_post_date, post_date )

Coalesce() function returns the first non-null argument.


问:
When I LEFT JOIN 2 table, how do I return 0 if the value is NULL?
I'm trying to set 0 to any null value in a LEFT JOIN, using coalesce() or ifnull(), in SQLite.
I know this question have been asked a lot, however, I'm stuck.

```<code>BUDGET
amount category
2      food
2      book
2      movie

EXPENSE
amount category
2      food
2      book

EXPECTED RESULT
budsum budcat expsum
2      food   2
2      book   2
2      movie  0
</code>```

This is the query that I've done.

```<code>SELECT SUM(budget.amount) AS budsum, budget.category AS budcat,
SUM(coalesce(expense.amount,0)) AS expsum
FROM budget
LEFT JOIN expense
ON budcat=expense.category
GROUP BY budcat;

SELECT SUM(budget.amount) AS budsum, budget.category AS budcat,
SUM(coalesce(expense.amount,0)) AS expsum
FROM budget
LEFT JOIN expense
ON budcat=expense.category
GROUP BY budcat;
</code>```

答:
Use coalesce on the sum instead.

```<code>select SUM(budget.amount) as budsum,
    budget.category as budcat,
    coalesce(SUM(expense.amount), 0) as expsum
from budget
left join expense on budget.category = expense.category
group by budget.category;
</code>```

Body:
I'm trying to set 0 to any null value in a LEFT JOIN, using coalesce() or ifnull(), in SQLite.
I know this question have been asked a lot, however, I'm stuck.

BUDGET
amount category
2      food
2      book
2      movie

EXPENSE
amount category
2      food
2      book

EXPECTED RESULT
budsum budcat expsum
2      food   2
2      book   2
2      movie  0

This is the query that I've done.

SELECT SUM(budget.amount) AS budsum, budget.category AS budcat,
SUM(coalesce(expense.amount,0)) AS expsum
FROM budget
LEFT JOIN expense
ON budcat=expense.category
GROUP BY budcat;

SELECT SUM(budget.amount) AS budsum, budget.category AS budcat,
SUM(coalesce(expense.amount,0)) AS expsum
FROM budget
LEFT JOIN expense
ON budcat=expense.category
GROUP BY budcat;

Body:
Use coalesce on the sum instead.

select SUM(budget.amount) as budsum,
    budget.category as budcat,
    coalesce(SUM(expense.amount), 0) as expsum
from budget
left join expense on budget.category = expense.category
group by budget.category;


问:
Number of possible paths
Why there are 2^k possible paths from S to T in the following graph.
Can anyone explain.
Note:all directions are from left to right in figure .

答:
In counting configurations, it is sometimes helpful to find a way to encode the configurations and then count the possible codes. This works as long as there is a 1-1 correspondence between the objects coded and the codes.

In this case you either take the top branch or the bottom branch at each stage. Code the paths as k-bit binary numbers by using a 0 at a given bit position if the corresponding path takes the top branch at that stage and otherwise a 1. This is clearly a 1-1 correspondence, hence the number of such paths is the number of k-bit numbers, which is 2^k (counting the number of k-bit numbers is essentially the same problem, so this isn't exactly a proof, but if you are already familiar with how k-bit numbers work, this could shed light on the path question).

For example (with k = 4):

```<code>path code num
vvvv 0000 0
vvv^ 0001 1
vv^v 0010 2
vv^^ 0011 3
v^vv 0100 4
v^v^ 0101 5
v^^v 0110 6
v^^^ 0111 7
^vvv 1000 8
^vv^ 1001 9
^v^v 1010 10
^v^^ 1011 11
^^vv 1100 12
^^v^ 1101 13
^^^v 1110 14
^^^^ 1111 15
</code>```

(Generated by the following Python 3 script, if you want to play around with it:)

```<code>def pathCodes(k):
    print('path code num')
    for n in range(2**k):
        b = bin(n)[2:]
        b = ('0'*(k-len(b))) + b
        s = b.replace('0','v')
        s = s.replace('1','^')
        print(s,b,n)
</code>```

Title: Number of possible paths

Body:
In counting configurations, it is sometimes helpful to find a way to encode the configurations and then count the possible codes. This works as long as there is a 1-1 correspondence between the objects coded and the codes.

In this case you either take the top branch or the bottom branch at each stage. Code the paths as k-bit binary numbers by using a 0 at a given bit position if the corresponding path takes the top branch at that stage and otherwise a 1. This is clearly a 1-1 correspondence, hence the number of such paths is the number of k-bit numbers, which is 2^k (counting the number of k-bit numbers is essentially the same problem, so this isn't exactly a proof, but if you are already familiar with how k-bit numbers work, this could shed light on the path question).

For example (with k = 4):

path code num
vvvv 0000 0
vvv^ 0001 1
vv^v 0010 2
vv^^ 0011 3
v^vv 0100 4
v^v^ 0101 5
v^^v 0110 6
v^^^ 0111 7
^vvv 1000 8
^vv^ 1001 9
^v^v 1010 10
^v^^ 1011 11
^^vv 1100 12
^^v^ 1101 13
^^^v 1110 14
^^^^ 1111 15

(Generated by the following Python 3 script, if you want to play around with it:)

def pathCodes(k):
    print('path code num')
    for n in range(2**k):
        b = bin(n)[2:]
        b = ('0'*(k-len(b))) + b
        s = b.replace('0','v')
        s = s.replace('1','^')
        print(s,b,n)


问:
iOS Playground doesn't show UI preview
I've created a simple playground with XCode 7.1 and I've typed this simple code:

```<code>import UIKit
import XCPlayground

var str = "Hello, playground"

let color = UIColor (red: 1 , green: 1 , blue: 0 , alpha: 0 )

let view = UIView()
view.backgroundColor = UIColo (colorLiteralRed: 1 , green: 0 , blue: 0 , alpha: 0 )

view.frame = CGRect (x: 0 ,y: 0 ,width: 100 ,height: 100 )

let label = UILabel (frame: CGRect (x: 5 , y: 5 , width: 50 , height: 20 ))

label.text = str

view.addSubview(label)
</code>```

When the playground runs, it doesn't show UIKit object preview, but only debug information:

What am I doing wrong?

答:
In Xcode 8.3 I'm still having issues. The only thing that works is shutting down Xcode and relaunching it. I tried quitting the simulator since I notice it is running the simulator, but this didn't fix the issue. Will file a radar.</p>

```<code>import UIKit

import PlaygroundSupport

let frame = CGRect(x: 0, y: 0, width: 300, height: 700)
let container = UIView(frame: frame)
container.backgroundColor = .red

let inner = UIView(frame: CGRect(x: 100, y: 100, width: 20, height: 40))

inner.backgroundColor = .blue
container.addSubview(inner)

PlaygroundPage.current.liveView = container
PlaygroundPage.current.needsIndefiniteExecution = true
</code>```

Title: iOS Playground doesn't show UI preview

Body:
I've created a simple playground with XCode 7.1 and I've typed this simple code:

import UIKit
import XCPlayground

var str = "Hello, playground"

let color = UIColor (red: 1 , green: 1 , blue: 0 , alpha: 0 )

let view = UIView()
view.backgroundColor = UIColo (colorLiteralRed: 1 , green: 0 , blue: 0 , alpha: 0 )

view.frame = CGRect (x: 0 ,y: 0 ,width: 100 ,height: 100 )

let label = UILabel (frame: CGRect (x: 5 , y: 5 , width: 50 , height: 20 ))

label.text = str

view.addSubview(label)

When the playground runs, it doesn't show UIKit object preview, but only debug information:

What am I doing wrong?

Body:
In Xcode 8.3 I'm still having issues. The only thing that works is shutting down Xcode and relaunching it. I tried quitting the simulator since I notice it is running the simulator, but this didn't fix the issue. Will file a radar.

import UIKit

import PlaygroundSupport

let frame = CGRect(x: 0, y: 0, width: 300, height: 700)
let container = UIView(frame: frame)
container.backgroundColor = .red

let inner = UIView(frame: CGRect(x: 100, y: 100, width: 20, height: 40))

inner.backgroundColor = .blue
container.addSubview(inner)

PlaygroundPage.current.liveView = container
PlaygroundPage.current.needsIndefiniteExecution = true


问:
Global values - anti-pattern?
I was recently told, that accessing process.env values anywhere else, but start-up file is an anti-pattern. Is that true? If so, how am I supposed to access values assigned there? Should I assign them to global scope? I don't really understand WHY this would be anti-pattern, could someone explain this to me?

答:
Config variables from environment tend to be non-readable often. So, you can possibly end up with something like process.env.PRODUCTION_DATABASES_MONGO_PORT that will mess up your code. And if your have a lot of process.env-s in different files it might be hard to understand what possible options are (should you run NODE_ENV=dev node index or NODE_ENV=development node index or FOO=true node index?).

As most simple solution that doesn't require any dependency injection you can simply create config.js in the root folder with something like:

```<code>module.exports = {
  databases: {
    mongo: {
      port: process.env.BLAH_BLAH_BLAH
    }
  }
  // ...
};
</code>```

and just require it wherever you want.

Title: Global values - anti-pattern?

Body:
Config variables from environment tend to be non-readable often. So, you can possibly end up with something like process.env.PRODUCTION_DATABASES_MONGO_PORT that will mess up your code. And if your have a lot of process.env-s in different files it might be hard to understand what possible options are (should you run NODE_ENV=dev node index or NODE_ENV=development node index or FOO=true node index?).

As most simple solution that doesn't require any dependency injection you can simply create config.js in the root folder with something like:

module.exports = {
  databases: {
    mongo: {
      port: process.env.BLAH_BLAH_BLAH
    }
  }
  // ...
};

and just require it wherever you want.


问:
How to create a text box containing fully clickable text in one click
I'm trying to create a text box mixture of HTML/CSS/JS. My requirement is that when I click on text its completely selected and can be copied but no one can change it when posted in blog. It looks like this:
Clickable box
Help me please.! Thanks in advance.
I need complete code combination of HTML/CSS/JS. I am a beginner however the alternate of this question is given in the link but there is need some improvement in my case that no one could be able to delete the text inside it. If some one could be able to design same box as I provided in 1st link, then It'll be great. Thanks once again.!</p>

答:
You can add this.select() to a onClick. That will make sure, that the whole text is selected, whenever you click your input.
Adding readonly attribute will make sure, that user isn't going to be able to edit the text.</p>

```<code><input onClick="this.select();" value="Sample Text" readonly/>
</code>```

Body:
You can add this.select() to a onClick. That will make sure, that the whole text is selected, whenever you click your input.
Adding readonly attribute will make sure, that user isn't going to be able to edit the text.

<input onClick="this.select();" value="Sample Text" readonly/>


问:
if/else and if/elseif
If I have a statement block like this:

```<code>if (/*condition here*/){ }
else{ }
</code>```

or like this:

```<code>if (/*condition here*/)
else if (/*condition here*/) {}
else if (/*condition here*/) {}
</code>```

What is the difference?

It seems that with if/else, if part is for true state and the else part is for all other possible options (false). An else-if would be useful for a number of conditions. This is my understanding, is there anything more I should be aware of?

答:
```<code>import java.util.*;

public class JavaApplication21 {
    public static void main(String[] args) {

        Scanner obj = new Scanner(System.in);
        System.out.println("You are watching an example of if & else if statements");

        int choice, a, b, c, d;
        System.out.println(" Enter 1-Addition & 2-Substraction");

        int option = obj.nextInt();
        switch (option) {
            case (1):
                System.out.println("how many numbers you want to add.... it can add up to 3 numbers only");
                choice = obj.nextInt();
                if (choice == 2) {
                    System.out.println("Enter 1st number");
                    a = obj.nextInt();

                    System.out.println("Enter 2nd number");
                    b = obj.nextInt();

                    c = a + b;

                    System.out.println("Answer of adding " + a + " & " + b + " is= " + c);
                } else if (choice == 3) {
                    System.out.println("Enter 1st number");
                    a = obj.nextInt();

                    System.out.println("Enter 2nd number");
                    b = obj.nextInt();

                    System.out.println("Enter 3rd number");
                    c = obj.nextInt();

                    d = a + b + c;

                    System.out.println("Answer of adding " + a + " , " + b + " & " + c + "  is= " + d);
                }
            case (2):
                System.out.println("how many numbers you want to substract.... it can substract up to 3 numbers only");
                choice = obj.nextInt();
                if (choice == 2) {
                    System.out.println("Enter 1st number");
                    a = obj.nextInt();

                    System.out.println("Enter 2nd number");
                    b = obj.nextInt();

                    c = a - b;
                    System.out.println("Answer of substracting " + a + " & " + b + " is= " + c);
                } else if (choice == 3) {
                    System.out.println("Enter 1st number");
                    a = obj.nextInt();

                    System.out.println("Enter 2nd number");
                    b = obj.nextInt();

                    System.out.println("Enter 3rd number");
                    c = obj.nextInt();

                    d = a - b - c;
                    System.out.println("Answer of substracting " + a + " , " + b + " & " + c + "  is= " + d);
                }
            default:
                System.out.println("no option you have chosen" + option);
        }
    }
}
</code>```

OwnerDisplayName: techie

Title: if/else and if/elseif

Body:
If I have a statement block like this:

if (/*condition here*/){ }
else{ }

or like this:

if (/*condition here*/)
else if (/*condition here*/) {}
else if (/*condition here*/) {}

What is the difference?

It seems that with if/else, if part is for true state and the else part is for all other possible options (false). An else-if would be useful for a number of conditions. This is my understanding, is there anything more I should be aware of?


问:
Override context menu colors in Android
Let's see,

i know how to change the style of a ListView (the orange color when an item is selected):

android:listSelector="@drawable/xxx" and a drawable with a bitmap or a @color

```<code><selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:drawable="@drawable/image" />
    <item android:drawable="@android:color/transparent" />
</selector>
</code>```

The thing is, in order to have a coherent design, i have to do the same thing for a context menu but i just can't see where to change it. There is no listSelector, nothing to change.

答:
Here is how you do it. Go to resources > styles.xml and override the theme's itemBackgroud attribute value as follows:

```<code><!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="android:itemBackground">"YOUR_COLOUR_HERE"</item>
</style>
</code>```

If this doesn't work, check in AndroidManifet.xml that you are really using the same theme at App level:

```<code><application
    ...
    android:theme="@style/AppTheme">

    ...

 </application>
</code>```

Title: Override context menu colors in Android

Body:
Let's see,

i know how to change the style of a ListView (the orange color when an item is selected):

android:listSelector="@drawable/xxx" and a drawable with a bitmap or a @color

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:drawable="@drawable/image" />
    <item android:drawable="@android:color/transparent" />
</selector>

The thing is, in order to have a coherent design, i have to do the same thing for a context menu but i just can't see where to change it. There is no listSelector, nothing to change.

Body:
Here is how you do it. Go to resources > styles.xml and override the theme's itemBackgroud attribute value as follows:

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="android:itemBackground">"YOUR_COLOUR_HERE"</item>
</style>

If this doesn't work, check in AndroidManifet.xml that you are really using the same theme at App level:

<application
    ...
    android:theme="@style/AppTheme">

    ...

 </application>


问:
How to detect duplicate words in a list and count them in a specific way
I've been learning python 3 for about 1 week now and I just can't find a way to do this, so here is my question.

I have this list:

```<code>['apple', 'banana', 'apple', 'tomato', 'carrot', 'apple', 'banana']
</code>```

Now I want to detect the duplicated words, count them, put the result in front of the word and print in a single string like this example:

Apple 3, Banana 2, tomato, carrot

Order doesn't matter.

答:
Here's a simple solution:

```<code>    list = ['apple', 'banana', 'apple', 'tomato', 'carrot', 'apple', 'banana']
    d = {x:list.count(x) for x in list}
    print d
</code>```

Output is:
{'tomato': 1, 'carrot': 1, 'apple': 3, 'banana': 2}

Body:
I've been learning python 3 for about 1 week now and I just can't find a way to do this, so here is my question.

I have this list:

['apple', 'banana', 'apple', 'tomato', 'carrot', 'apple', 'banana']

Now I want to detect the duplicated words, count them, put the result in front of the word and print in a single string like this example:

Apple 3, Banana 2, tomato, carrot

Order doesn't matter.

Body:
Here's a simple solution:

    list = ['apple', 'banana', 'apple', 'tomato', 'carrot', 'apple', 'banana']
    d = {x:list.count(x) for x in list}
    print d

Output is:
{'tomato': 1, 'carrot': 1, 'apple': 3, 'banana': 2}


问:
Is there a way to modify this YouTube download script to access the 4K version of the video?
I've been using the script below to download technical videos for later analysis. The script has worked well for me and retrieves the highest resolution version available for the videos that I have needed.

Now I've come across a 4K YouTube video, and my script only saves an mp4 with 1280x720.

I'd like to know if there is a way to adjust my current script to download higher resolution versions of this video. I understand there are python packages that might address this, but right now I would like stick to this step-by-step method if possible.

above: info from Quicktime and OSX

```<code>"""
length:   175 seconds
quality:  hd720
type:     video/mp4; codecs="avc1.64001F, mp4a.40.2"
Last-Modified: Sun, 21 Aug 2016 10:41:48 GMT
Content-Type: video/mp4
Date: Sat, 01 Apr 2017 16:50:16 GMT
Expires: Sat, 01 Apr 2017 16:50:16 GMT
Cache-Control: private, max-age=21294
Accept-Ranges: bytes
Content-Length: 35933033
Connection: close
Alt-Svc: quic=":443"; ma=2592000
X-Content-Type-Options: nosniff
Server: gvs 1.
"""

import urlparse, urllib2

vid        = "vzS1Vkpsi5k"
save_title = "YouTube SpaceX - Booster Number 4 - Thaicom 8 06-06-2016"
url_init   = "https://www.youtube.com/get_video_info?video_id=" + vid

resp = urllib2.urlopen(url_init, timeout=10)
data = resp.read()
info =  urlparse.parse_qs(data)
title = info['title']

print "length:  ", info['length_seconds'][0] + " seconds"

stream_map   = info['url_encoded_fmt_stream_map'][0]
vid_info     = stream_map.split(",")

mp4_filename = save_title + ".mp4"

for video in vid_info:
    item = urlparse.parse_qs(video)

    print 'quality: ', item['quality'][0]
    print 'type:    ', item['type'][0]

    url_download  = item['url'][0]
    resp          = urllib2.urlopen(url_download)

    print resp.headers

    length  = int(resp.headers['Content-Length'])
    my_file = open(mp4_filename, "w+")

    done, i = 0, 0
    buff    = resp.read(1024)
    while buff:

        my_file.write(buff)
        done += 1024
        percent = done * 100.0 / length
        buff = resp.read(1024)

        if not i%1000:
            percent = done * 100.0 / length
            print str(percent) + "%"

        i += 1
    break
</code>```

答:
Ok, so I have not taken the time to get to the bottom of this. However, I did find that when you do:

stream_map   = info['url_encoded_fmt_stream_map'][0]

Somehow you only get a selection of a single 720p option, one 'medium' and two 'small'.

However, if you change that line into:

stream_map   = info['adaptive_fmts'][0]

you will get all the available versions, including the 2160p  one. Thus, the 4K one.

PS: You'd have to comment out the print quality and print type command since those labels aren't always available in the new throughput. When commenting them out however, and adapting your script as explained above, I was able to successfully download the 4K version.

Body:
I've been using the script below to download technical videos for later analysis. The script has worked well for me and retrieves the highest resolution version available for the videos that I have needed.

Now I've come across a 4K YouTube video, and my script only saves an mp4 with 1280x720.

I'd like to know if there is a way to adjust my current script to download higher resolution versions of this video. I understand there are python packages that might address this, but right now I would like stick to this step-by-step method if possible.

above: info from Quicktime and OSX

"""
length:   175 seconds
quality:  hd720
type:     video/mp4; codecs="avc1.64001F, mp4a.40.2"
Last-Modified: Sun, 21 Aug 2016 10:41:48 GMT
Content-Type: video/mp4
Date: Sat, 01 Apr 2017 16:50:16 GMT
Expires: Sat, 01 Apr 2017 16:50:16 GMT
Cache-Control: private, max-age=21294
Accept-Ranges: bytes
Content-Length: 35933033
Connection: close
Alt-Svc: quic=":443"; ma=2592000
X-Content-Type-Options: nosniff
Server: gvs 1.
"""

import urlparse, urllib2

vid        = "vzS1Vkpsi5k"
save_title = "YouTube SpaceX - Booster Number 4 - Thaicom 8 06-06-2016"
url_init   = "https://www.youtube.com/get_video_info?video_id=" + vid

resp = urllib2.urlopen(url_init, timeout=10)
data = resp.read()
info =  urlparse.parse_qs(data)
title = info['title']

print "length:  ", info['length_seconds'][0] + " seconds"

stream_map   = info['url_encoded_fmt_stream_map'][0]
vid_info     = stream_map.split(",")

mp4_filename = save_title + ".mp4"

for video in vid_info:
    item = urlparse.parse_qs(video)

    print 'quality: ', item['quality'][0]
    print 'type:    ', item['type'][0]

    url_download  = item['url'][0]
    resp          = urllib2.urlopen(url_download)

    print resp.headers

    length  = int(resp.headers['Content-Length'])
    my_file = open(mp4_filename, "w+")

    done, i = 0, 0
    buff    = resp.read(1024)
    while buff:

        my_file.write(buff)
        done += 1024
        percent = done * 100.0 / length
        buff = resp.read(1024)

        if not i%1000:
            percent = done * 100.0 / length
            print str(percent) + "%"

        i += 1
    break


问:
Css unwanted right margin, sticky footer not fixed
On my site I've got unwanted white margin on the right side, I don't know why. All containers on my site are contained-fluid, and also I added to my css no padding and no margins for containers.

```<code>  html,
page {
    width: 100%!important;
     margin:0;
    font-family: "Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;
    padding-right:0px;
    padding-left:0px;
    color:#333;

}
container, container-fluid {
width:100%0!important;
padding:0!important;
margin:0!important;
}
</code>```

I'd like to put a footer on down of  site, I tried with position: absolute and margin-bottom, also tried overflow hidden but it doesn't work for me.

```<code> <div class="navbar navbar-inverse  navbottom">

   .navbottom {

background: url(../img/footer.jpg) no-repeat center center scroll;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    background-size: cover;
    -o-background-size: cover;
    background-color:#679003;

-moz-border-radius:0px;
border-radius: 0px;
border-style: none;
position: relative;
  margin-top: -50px; /* negative value of footer height */
  height: 50px;
  clear:both;
  padding-top:20px;
overflow:hidden;
margin-bottom:0!important;
</code>```

full html and css
https://jsbin.com/biwuyewipi/edit?html,css,output

site:
http://fotozorza.pl/

答:
this is because of google map width change it to 98vw.

EDIT :
 add following snippet to css

```<code>.row{ margin-right:0px; margin-left:0px; }
</code>```

and reduce the width of google map i_frame. this is the cause of problem.

Body:
On my site I've got unwanted white margin on the right side, I don't know why. All containers on my site are contained-fluid, and also I added to my css no padding and no margins for containers.

  html,
page {
    width: 100%!important;
     margin:0;
    font-family: "Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;
    padding-right:0px;
    padding-left:0px;
    color:#333;

}
container, container-fluid {
width:100%0!important;
padding:0!important;
margin:0!important;
}

I'd like to put a footer on down of  site, I tried with position: absolute and margin-bottom, also tried overflow hidden but it doesn't work for me.

   .navbottom {

background: url(../img/footer.jpg) no-repeat center center scroll;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    background-size: cover;
    -o-background-size: cover;
    background-color:#679003;

-moz-border-radius:0px;
border-radius: 0px;
border-style: none;
position: relative;
  margin-top: -50px; /* negative value of footer height */
  height: 50px;
  clear:both;
  padding-top:20px;
overflow:hidden;
margin-bottom:0!important;

full html and css
https://jsbin.com/biwuyewipi/edit?html,css,output

site:
http://fotozorza.pl/

Body:
this is because of google map width change it to 98vw.

EDIT :
 add following snippet to css

.row{ margin-right:0px; margin-left:0px; }

and reduce the width of google map i_frame. this is the cause of problem.


问:
File sharing violation occurs after creation of file?
So, I'm attempting to create a .txt file, and then write some silly data to it. But I'm getting a sharing violation. I sense that it may be because I'm attempting to create a StreamWriter for a file directly after creating it, but that doesn't make sense. So I'm a bit lost. I've tried removing all the other StreamWriters and Readers in the class except for the erroneous line, and I'm still getting a violation. The error I'm getting,

```<code>IOException: Sharing violation on path C:\Users\USER\Desktop\Accessible\Assets\IO\Books\A community of learners\frog\frog_status.txt
System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean anonymous, FileOptions options)
System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share)
(wrapper remoting-invoke-with-check) System.IO.FileStream:.ctor (string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare)
</code>```

Points to the line:

```<code>StreamWriter sw = new StreamWriter(statusTxtPath);
</code>```

In the following function:

```<code>private IEnumerator GatherStatusInfo(string folderPath, string mediaName) {

        string statusTxtPath = folderPath + @"/" + mediaName + "_status.txt";
        _currentInfoBeingCreated._readingStatusTxtPath = statusTxtPath;

        if(BuildManager.instance._isResetStatusFilesWhenStarting) {
            if(File.Exists(statusTxtPath))
                File.Delete(statusTxtPath);
        }

        if(!File.Exists(statusTxtPath)) {
            File.Create(statusTxtPath);
            StreamWriter sw = new StreamWriter(statusTxtPath);
            sw.WriteLine(MediaStatus.Unread);
            sw.WriteLine("0");
            _currentInfoBeingCreated._status = MediaStatus.Unread;
            _currentInfoBeingCreated._pageLastRead = 0;
            sw.Flush();
            sw.Close();

        } else {

            StreamReader statusReader = new StreamReader(statusTxtPath);
            _currentInfoBeingCreated._status = (MediaStatus) Enum.Parse(typeof(MediaStatus), statusReader.ReadLine());
            _currentInfoBeingCreated._pageLastRead = (int) ConversionUtils.instance.String2Float(statusReader.ReadLine());
            statusReader.Close();
        }

        yield return 0;
    }
</code>```

Any idea why that dog won't hunt?

答:
I'm new in this programming language, I know some Ansi C mainly from programming micro controllers but I'm now learning C# and I was having kind of the same problem.

System.IO.IOException

  Sharing violation on path /.../...

I found that having the following code, raises an exception.

```<code>if(!File.Exists(path))
   File.Create(path);
</code>```

The solution I found to solve this actually uses less and simpler code.

```<code>File.AppendAllText(path, str);
</code>```

With this line the program will open the file if it already exists and append the text to the end of it, if it doesn't exist  will create it and append the text.

Being:  path -> the path of the file

str    -> the text that you want to write to the file

I found a hint for the solution on this Xamarin forum page.

Body:
So, I'm attempting to create a .txt file, and then write some silly data to it. But I'm getting a sharing violation. I sense that it may be because I'm attempting to create a StreamWriter for a file directly after creating it, but that doesn't make sense. So I'm a bit lost. I've tried removing all the other StreamWriters and Readers in the class except for the erroneous line, and I'm still getting a violation. The error I'm getting,

IOException: Sharing violation on path C:\Users\USER\Desktop\Accessible\Assets\IO\Books\A community of learners\frog\frog_status.txt
System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean anonymous, FileOptions options)
System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share)
(wrapper remoting-invoke-with-check) System.IO.FileStream:.ctor (string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare)

Points to the line:

StreamWriter sw = new StreamWriter(statusTxtPath);

In the following function:

private IEnumerator GatherStatusInfo(string folderPath, string mediaName) {

        string statusTxtPath = folderPath + @"/" + mediaName + "_status.txt";
        _currentInfoBeingCreated._readingStatusTxtPath = statusTxtPath;

        if(BuildManager.instance._isResetStatusFilesWhenStarting) {
            if(File.Exists(statusTxtPath))
                File.Delete(statusTxtPath);
        }

        if(!File.Exists(statusTxtPath)) {
            File.Create(statusTxtPath);
            StreamWriter sw = new StreamWriter(statusTxtPath);
            sw.WriteLine(MediaStatus.Unread);
            sw.WriteLine("0");
            _currentInfoBeingCreated._status = MediaStatus.Unread;
            _currentInfoBeingCreated._pageLastRead = 0;
            sw.Flush();
            sw.Close();

        } else {

            StreamReader statusReader = new StreamReader(statusTxtPath);
            _currentInfoBeingCreated._status = (MediaStatus) Enum.Parse(typeof(MediaStatus), statusReader.ReadLine());
            _currentInfoBeingCreated._pageLastRead = (int) ConversionUtils.instance.String2Float(statusReader.ReadLine());
            statusReader.Close();
        }

        yield return 0;
    }

Any idea why that dog won't hunt?

Body:
I'm new in this programming language, I know some Ansi C mainly from programming micro controllers but I'm now learning C# and I was having kind of the same problem.

System.IO.IOException

  Sharing violation on path /.../...

I found that having the following code, raises an exception.

if(!File.Exists(path))
   File.Create(path);

The solution I found to solve this actually uses less and simpler code.

File.AppendAllText(path, str);

With this line the program will open the file if it already exists and append the text to the end of it, if it doesn't exist  will create it and append the text.

Being:  path -> the path of the file

str    -> the text that you want to write to the file

I found a hint for the solution on this Xamarin forum page.


问:
Why am I getting so many br tags
I started writing html code and when I view it on chrome, the table is displayed after a long white space. When I inspect the element, on chrome, I get a lot of br tags but I have not given any br tags in the code

How come?

<!DOCTYPE html>

  <title> Practice </title>

 <big><big> Registration Form <big><big>

<form name="My Form" action="" method="">

 Username
 <input type="text" name="t1" size="6"/>

 Password
 <input type="password" name="t2" size="6"/>

 Name
 <input type="text" name="t3" size="30"/>

 Address
 <input type="text" name="t4" size="30"/>

 Country
<select name="s1">
<option> Select Your Country </option>
<option> Afghanistan </option>
<option> Bangladesh </option>
<option> China </option>
<option> India </option>
<option> Russia </option>
</select>

 Zip Code
 <input type="text" name="t5" size="6"/>

 Email
 <input type="text" name="t6" size="30"/>

Sex
<input type="radio" name="r1" value="100" checked/>Male
<input type="radio" name="r1" value="102"/>Female

Language
<input type="checkbox" name="r1" value="100" checked/>English
<input type="checkbox" name="r2" value="102"/>Non English

 About
<textarea name="a1" rows="5" cols="32"> </textarea>

<input type="submit" name="b2" value="submit here"/>

</form>

```

答:
I don't think this is
. Use Inspect Element to check what's causing so much gap before table. There might be some kind of margin before table.

Title: Why am I getting so many br tags

Body: I don't think this is <br>. Use Inspect Element to check what's causing so much gap before table. There might be some kind of margin before table.


问:
C# error while deserializing JSON
I am using json.net to deserialize incoming json in a WebApi service.

```<code>var lines = JsonConvert.DeserializeObject<RootObject>(json);
</code>```

After reading a number of other similar answers, it is still throwing this error:

```<code>The best overloaded method match for  'Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(string)' has some invalid arguments
</code>```

Input json that is used in Postman for post:

```<code>{ "data": [
{"zipcode":"56033","line1":"610 4TH ST","city":"FROST","state":"MN","cid":"1770"},
{"zipcode":"56033","line1":"45375 30TH ST","city":"FROST","state":"MN","cid":"1771"},
{"zipcode":"56033","line1":"115 4TH ST","city":"FROST","state":"MN","cid":"1772"}
]}
</code>```

The poco classes were created using: http://json2csharp.com .

```<code>  public class Datum
  {
    public string zipcode { get; set; }
    public string line1 { get; set; }
    public string city { get; set; }
    public string state { get; set; }
    public string cid { get; set; }
  }

  public class RootObject
  {
    public List<Datum> data { get; set; }
  }
</code>```

Here is what I see when I debug the api:

```<code>{{
  "data": [
    {
      "zipcode": "56032-0056",
      "line1": "208 MAIN BOX 56",
      "city": "FREEBORN",
      "state": "MN",
      "cid": "1732"
    },
    {
      "zipcode": "56033",
      "line1": "610 4TH ST",
      "city": "FROST",
      "state": "MN",
      "cid": "1770"
    },
    {
      "zipcode": "56033",
      "line1": "45375 30TH ST",
      "city": "FROST",
      "state": "MN",
      "cid": "1771"
    },
    {
      "zipcode": "56033",
      "line1": "115 4TH ST",
      "city": "FROST",
      "state": "MN",
      "cid": "1772"
    },
    {
      "zipcode": "56033",
      "line1": "E 4TH ST",
      "city": "FROST",
      "state": "MN",
      "cid": "1773"
    }
  ]
}}
</code>```

Not sure why webapi is adding an extra set of curly braces or how to prevent them.

Anyone see what I am missing?

答: If your json variable is a string, it will work.  Here's a .NET Fiddle demonstrating.</p>

Title: C# error while deserializing JSON

Body:
I am using json.net to deserialize incoming json in a WebApi service.

var lines = JsonConvert.DeserializeObject<RootObject>(json);

After reading a number of other similar answers, it is still throwing this error:

The best overloaded method match for  'Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(string)' has some invalid arguments

Input json that is used in Postman for post:

{ "data": [
{"zipcode":"56033","line1":"610 4TH ST","city":"FROST","state":"MN","cid":"1770"},
{"zipcode":"56033","line1":"45375 30TH ST","city":"FROST","state":"MN","cid":"1771"},
{"zipcode":"56033","line1":"115 4TH ST","city":"FROST","state":"MN","cid":"1772"}
]}

The poco classes were created using: http://json2csharp.com .

  public class Datum
  {
    public string zipcode { get; set; }
    public string line1 { get; set; }
    public string city { get; set; }
    public string state { get; set; }
    public string cid { get; set; }
  }

  public class RootObject
  {
    public List<Datum> data { get; set; }
  }

Here is what I see when I debug the api:

{{
  "data": [
    {
      "zipcode": "56032-0056",
      "line1": "208 MAIN BOX 56",
      "city": "FREEBORN",
      "state": "MN",
      "cid": "1732"
    },
    {
      "zipcode": "56033",
      "line1": "610 4TH ST",
      "city": "FROST",
      "state": "MN",
      "cid": "1770"
    },
    {
      "zipcode": "56033",
      "line1": "45375 30TH ST",
      "city": "FROST",
      "state": "MN",
      "cid": "1771"
    },
    {
      "zipcode": "56033",
      "line1": "115 4TH ST",
      "city": "FROST",
      "state": "MN",
      "cid": "1772"
    },
    {
      "zipcode": "56033",
      "line1": "E 4TH ST",
      "city": "FROST",
      "state": "MN",
      "cid": "1773"
    }
  ]
}}

Not sure why webapi is adding an extra set of curly braces or how to prevent them.

Anyone see what I am missing?