问:
Extract individual existing words in domain names
I'm looking for a Ruby gem (preferably) that will cut domain names up into their words.

```<code>whatwomenwant.com => 3 words, "what", "women", "want".
</code>```

If it can ignore things like numbers and gibberish then great.

答:
You'll need a word list such as those produced by Project Gutenberg or available in the source for ispell &c.  Then you can use the following code to decompose a domain into words:

```<code>WORD_LIST = [
  'experts',
  'expert',
  'exchange',
  'sex',
  'change',
]

def words_that_phrase_begins_with(phrase)
  WORD_LIST.find_all do |word|
    phrase.start_with?(word)
  end
end

def phrase_to_words(phrase, words = [], word_list = [])
  if phrase.empty?
    word_list << words
  else
    words_that_phrase_begins_with(phrase).each do |word|
      remainder = phrase[word.size..-1]
      phrase_to_words(remainder, words + [word], word_list)
    end
  end
  word_list
end

p phrase_to_words('expertsexchange')
# => [["experts", "exchange"], ["expert", "sex", "change"]]
</code>```

If given a phrase that has any unrecognized words, it returns an empty array:

```<code>p phrase_to_words('expertsfoo')
# => []
</code>```

If the word list is long, this will be slow.  You can make this algorithm faster by preprocessing the word list into a tree.  The preprocessing itself will take time, so whether it's worth it will depend upon how many domains you want to test.

Here's some code to turn the word list into a tree:

```<code>def add_word_to_tree(tree, word)
  first_letter = word[0..0].to_sym
  remainder = word[1..-1]
  tree[first_letter] ||= {}
  if remainder.empty?
    tree[first_letter][:word] = true
  else
    add_word_to_tree(tree[first_letter], remainder)
  end
end

def make_word_tree
  root = {}
  WORD_LIST.each do |word|
    add_word_to_tree(root, word)
  end
  root
end

def word_tree
  @word_tree ||= make_word_tree
end
</code>```

This produces a tree that looks like this:

{:c=>{:h=>{:a=>{:n=>{:g=>{:e=>{:word=>true}}}}}}, :s=>{:e=>{:x=>{:word=>true}}}, :e=>{:x=>{:c=>{:h=>{:a=>{:n=>{:g=>{:e=>{:word=>true}}}}}}, :p=>{:e=>{:r=>{:t=>{:word=>true, :s=>{:word=>true}}}}}}}}

It looks like Lisp, doesn't it?  Each node in the tree is a hash.  Each hash key is either a letter, with the value being another node, or it is the symbol :word with the value being true.  Nodes with :word are words.

Modifying words_that_phrase_begins_with to use the new tree structure will make it faster:

```<code>def words_that_phrase_begins_with(phrase)
  node = word_tree
  words = []
  phrase.each_char.with_index do |c, i|
    node = node[c.to_sym]
    break if node.nil?
    words << phrase[0..i] if node[:word]
  end
  words
end
</code>```

Body:
I'm looking for a Ruby gem (preferably) that will cut domain names up into their words.

whatwomenwant.com => 3 words, "what", "women", "want".

If it can ignore things like numbers and gibberish then great.

Body:
You'll need a word list such as those produced by Project Gutenberg or available in the source for ispell &c.  Then you can use the following code to decompose a domain into words:

WORD_LIST = [
  'experts',
  'expert',
  'exchange',
  'sex',
  'change',
]

def words_that_phrase_begins_with(phrase)
  WORD_LIST.find_all do |word|
    phrase.start_with?(word)
  end
end

def phrase_to_words(phrase, words = [], word_list = [])
  if phrase.empty?
    word_list << words
  else
    words_that_phrase_begins_with(phrase).each do |word|
      remainder = phrase[word.size..-1]
      phrase_to_words(remainder, words + [word], word_list)
    end
  end
  word_list
end

p phrase_to_words('expertsexchange')
# => [["experts", "exchange"], ["expert", "sex", "change"]]

If given a phrase that has any unrecognized words, it returns an empty array:

p phrase_to_words('expertsfoo')
# => []

If the word list is long, this will be slow.  You can make this algorithm faster by preprocessing the word list into a tree.  The preprocessing itself will take time, so whether it's worth it will depend upon how many domains you want to test.

Here's some code to turn the word list into a tree:

def add_word_to_tree(tree, word)
  first_letter = word[0..0].to_sym
  remainder = word[1..-1]
  tree[first_letter] ||= {}
  if remainder.empty?
    tree[first_letter][:word] = true
  else
    add_word_to_tree(tree[first_letter], remainder)
  end
end

def make_word_tree
  root = {}
  WORD_LIST.each do |word|
    add_word_to_tree(root, word)
  end
  root
end

def word_tree
  @word_tree ||= make_word_tree
end

This produces a tree that looks like this:

{:c=>{:h=>{:a=>{:n=>{:g=>{:e=>{:word=>true}}}}}}, :s=>{:e=>{:x=>{:word=>true}}}, :e=>{:x=>{:c=>{:h=>{:a=>{:n=>{:g=>{:e=>{:word=>true}}}}}}, :p=>{:e=>{:r=>{:t=>{:word=>true, :s=>{:word=>true}}}}}}}}

It looks like Lisp, doesn't it?  Each node in the tree is a hash.  Each hash key is either a letter, with the value being another node, or it is the symbol :word with the value being true.  Nodes with :word are words.

Modifying words_that_phrase_begins_with to use the new tree structure will make it faster:

def words_that_phrase_begins_with(phrase)
  node = word_tree
  words = []
  phrase.each_char.with_index do |c, i|
    node = node[c.to_sym]
    break if node.nil?
    words << phrase[0..i] if node[:word]
  end
  words
end


来源: stackexchange

问:
generate all possible combinations of n bit binary numbers wherein k bits are always set using backtracking only
Getting stuck on how to set the bits while backtracking. Unable to exclude 001,010 and 100 in the output. providing an algorithm would be greatly helpful.

Eg:n=3,k=2,arr={0,0,0},index=0

```<code>void printwithKbitset(int n,int k,int arr[],int index)
{
   if(k==0)
    {
        for(int i=0;i<3;i++)
            cout<<arr[i];
        cout<<"\n";
   return;
   }
    if(n>1)
        printwithKbitset(n-1,k,arr,index+1);
   if(k>0)
   {
   arr[index]=1;
   printwithKbitset(n,k-1,arr,index);
 arr[index]=0;
    }

Output:
001
011
010
101
110
100
</code>```

答:
The way to go is using std::next_permutation:

```<code>#include <algorithm>
#include <iostream>
#include <vector>

void print(const std::vector<int>& v)
{
    for (auto e : v) {
        std::cout << e << " ";
    }
    std::cout << std::endl;
}

int main()
{
    std::vector<int> v {0, 1, 1};

    do {
        print(v);
    } while (std::next_permutation(std::begin(v), std::end(v)));
}
</code>```

Demo

ContentLicense: CC BY-SA 3.0

Body:
Getting stuck on how to set the bits while backtracking. Unable to exclude 001,010 and 100 in the output. providing an algorithm would be greatly helpful.

Eg:n=3,k=2,arr={0,0,0},index=0

void printwithKbitset(int n,int k,int arr[],int index)
{
   if(k==0)
    {
        for(int i=0;i<3;i++)
            cout<<arr[i];
        cout<<"\n";
   return;
   }
    if(n>1)
        printwithKbitset(n-1,k,arr,index+1);
   if(k>0)
   {
   arr[index]=1;
   printwithKbitset(n,k-1,arr,index);
 arr[index]=0;
    }

Output:
001
011
010
101
110
100

Body:
The way to go is using std::next_permutation:

#include <algorithm>
#include <iostream>
#include <vector>

void print(const std::vector<int>& v)
{
    for (auto e : v) {
        std::cout << e << " ";
    }
    std::cout << std::endl;
}

int main()
{
    std::vector<int> v {0, 1, 1};

    do {
        print(v);
    } while (std::next_permutation(std::begin(v), std::end(v)));
}

Demo


问:
Mocking platform detection in Jest and React Native
Some of the code I am trying to test detects the platform, using, e.g.:

import { Platform } from 'react-native';
...

if (Platform.OS === 'android') {
  ...
} else {
  ...
}
```

Is there a sensible way to mock this with Jest and/or something else, so I can test both branches in one test run?

Or is the smart way to decouple it and put the platform into, e.g., a context variable? Although it always feels restructuring code to make it easier to test is something of a cheat.

答:
You can mock whatever you want from React-Native like this:

describe('notifications actions tests', () => {
  let Platform;

  beforeEach(() => {
    jest.mock('react-native', () => ({
          Platform: {
           ...
        }));

    Platform = require('react-native').Platform; // incase u would like to refer to Platform in your tests
  });
```

ContentLicense: CC BY-SA 4.0

Body:
Some of the code I am trying to test detects the platform, using, e.g.:

import { Platform } from 'react-native';
...

if (Platform.OS === 'android') {
  ...
} else {
  ...
}

Is there a sensible way to mock this with Jest and/or something else, so I can test both branches in one test run?

Or is the smart way to decouple it and put the platform into, e.g., a context variable? Although it always feels restructuring code to make it easier to test is something of a cheat.


问:
Getting error Required android.support.v4.app.Fragment
I'm getting this error

Required android.support.v4.app.Fragment

Found in in.ashirvad.dhruv.krust.EventFragment

```<code>public void displayView(int viewId) {

    Fragment fragment = null;
    String title = getString(R.string.app_name);

    switch (viewId) {
        case R.id.nav_about:
            fragment = new NewsFragment();
            title  = "News";

            break;
        case R.id.nav_events:
            fragment = new EventFragment();
            title = "Events";
            break;

    }

    if (fragment != null) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.content_frame, fragment);
        ft.commit();
    }

    // set the toolbar title
    if (getSupportActionBar() != null) {
        getSupportActionBar().setTitle(title);
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);

}
</code>```

P.S.- in.ashirvad.dhruv.krust is my package name

答: Please add libraries you've used in this class. My wild guess is you are using the standard Fragment library rather than the v4 one.</p>

Body:
I'm getting this error

Required android.support.v4.app.Fragment

Found in in.ashirvad.dhruv.krust.EventFragment

public void displayView(int viewId) {

    Fragment fragment = null;
    String title = getString(R.string.app_name);

    switch (viewId) {
        case R.id.nav_about:
            fragment = new NewsFragment();
            title  = "News";

            break;
        case R.id.nav_events:
            fragment = new EventFragment();
            title = "Events";
            break;

    }

    if (fragment != null) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.content_frame, fragment);
        ft.commit();
    }

    // set the toolbar title
    if (getSupportActionBar() != null) {
        getSupportActionBar().setTitle(title);
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);

}

P.S.- in.ashirvad.dhruv.krust is my package name


问:
How to use group by to have parent-child fields
I have a table like this:

```<code>title - description
 A          AA
 B          B
 A          AAA
 B          BBBBB
</code>```

now I would like to have a json like this:

```<code>A
  AA
  AAA
B
  B
  BBBB
</code>```

Is it possible to use one query?

答:
Based on your sample data, you can use group by with group_concat to get comma separated value for each title:

```<code>select title,
    group_concat(description)
from your_table
group by title;
</code>```

Body:
I have a table like this:

title - description
 A          AA
 B          B
 A          AAA
 B          BBBBB

now I would like to have a json like this:

A
  AA
  AAA
B
  B
  BBBB

Is it possible to use one query?

Body:
Based on your sample data, you can use group by with group_concat to get comma separated value for each title:

select title,
    group_concat(description)
from your_table
group by title;


答:
Check whether the fragment class you have imported in this class is same as the Fragment class in EventFragment class

Android has a built in Fragment class in latest versions of sdk but support library is for older versions or for continuity so those are two different locations.

Title: Getting error Required android.support.v4.app.Fragment


问:
Advanced Method Call Hierarchy generation for Java?
I have some large corporate Spring project unknown for me and I need to perform this kind of task above it:

"I have method A and method B. During the execution of method A, can
  method B be called?"

Well I found there is function Method Call Hierarchy in IntelliJ Idea. I can perform this function on method B and generate call hierarchy, where I can perform serarch for method A. Unfortunatelly, IntelliJ freeze during computing of this hierarchy becouse its so large and crashed after 5 hours of working.

I need Method Call Hierarchy utility with better performance than IntelliJ Idea have but I failed to find it. Can you help me?

答: try alt + f7, or also use debugger to use call sequence. </p>


问:
How to install Search Guard 5 in cluster of nodes?
I want to secure Elasticsearch and Kibana using Search Guard 5 plugin. Search Guard SSL is bundled with Search Guard 5.

I have got three nodes cluster. One of them is master. My question is - do I have to install Search Guard 5 on every node or only on master node? And what about configuration files? Do I have to chnage config files on every node?

答:
You need to install the Search Guard plugin on every node regardless of the node type (master, data, ingest, loadbalancer, ...).

So you also need to add the Search Guard specific configuration in elasticsearch.yml on every node. But there are only a few entries for the SSL configuration.

The main parts of the configs reside in an index within elasticsearch itself an can be administered through "sgadmin" tool from any host which can connect to elasticsearch (on transport protocol level, typically port 9300)


问:
PHP read first item in object array
I have my code in PHP which is returning this Array of data:

```<code>GoCardlessPro\Core\ListResponse Object
(
    [records] => Array
        (
            [0] => GoCardlessPro\Resources\Mandate Object
                (
                    [model_name:protected] => Mandate
                    [created_at:protected] => 2017-04-01T16:49:09.642Z
                    [id:protected] => ID001
                    [links:protected] => stdClass Object
                        (
                            [customer_bank_account] => CB001
                            [creditor] => CR001
                            [customer] => CU001
                        )

                    [metadata:protected] => stdClass Object
                        (
                        )

                    [next_possible_charge_date:protected] => 2017-04-06
                    [payments_require_approval:protected] =>
                    [reference:protected] => RE001
                    [scheme:protected] => bacs
                    [status:protected] => active
                    [data:GoCardlessPro\Resources\BaseResource:private] => stdClass Object
                        (
                            [id] => 123
                            [created_at] => 2017-04-01T16:49:09.642Z
                            [reference] => RE001
                            [status] => active
                            [scheme] => bacs
                            [next_possible_charge_date] => 2017-04-06
                            [payments_require_approval] =>
                            [metadata] => stdClass Object
                                (
                                )

                            [links] => stdClass Object
                                (
                                    [customer_bank_account] => 001
                                    [creditor] => CR001
                                    [customer] => CU001
                                )

                        )

                    [api_response] =>
                )

        )
)
</code>```

I want to be able to read the ID of the first item in therecords array.

This data is contained inside a variable called $GC_Mandate;

I have tried these:

```<code>echo $GC_Mandate->records->{0}->id;

echo $GC_Mandate->records->0->id;

echo $GC_Mandate->records->[0]->id;

$GC_Mandate = $GC_Mandate->records;
echo $GC_Mandate->{0}->id;
</code>```

But none will return the data

答:
I can't comment so I guess I'll have to post.

You should try to print_r($GC_Mandate); and see what it gives out and then go from there.

Title: PHP read first item in object array

Body:
I have my code in PHP which is returning this Array of data:

GoCardlessPro\Core\ListResponse Object
(
    [records] => Array
        (
            [0] => GoCardlessPro\Resources\Mandate Object
                (
                    [model_name:protected] => Mandate
                    [created_at:protected] => 2017-04-01T16:49:09.642Z
                    [id:protected] => ID001
                    [links:protected] => stdClass Object
                        (
                            [customer_bank_account] => CB001
                            [creditor] => CR001
                            [customer] => CU001
                        )

                    [metadata:protected] => stdClass Object
                        (
                        )

                    [next_possible_charge_date:protected] => 2017-04-06
                    [payments_require_approval:protected] =>
                    [reference:protected] => RE001
                    [scheme:protected] => bacs
                    [status:protected] => active
                    [data:GoCardlessPro\Resources\BaseResource:private] => stdClass Object
                        (
                            [id] => 123
                            [created_at] => 2017-04-01T16:49:09.642Z
                            [reference] => RE001
                            [status] => active
                            [scheme] => bacs
                            [next_possible_charge_date] => 2017-04-06
                            [payments_require_approval] =>
                            [metadata] => stdClass Object
                                (
                                )

                            [links] => stdClass Object
                                (
                                    [customer_bank_account] => 001
                                    [creditor] => CR001
                                    [customer] => CU001
                                )

                        )

                    [api_response] =>
                )

        )
)

I want to be able to read the ID of the first item in therecords array.

This data is contained inside a variable called $GC_Mandate;

I have tried these:

echo $GC_Mandate->records->{0}->id;

echo $GC_Mandate->records->0->id;

echo $GC_Mandate->records->[0]->id;

$GC_Mandate = $GC_Mandate->records;
echo $GC_Mandate->{0}->id;

But none will return the data


问:
Looping assets and entries together
I have managed to loop out all content from a specific ContentType and everything works well except that the entries are not followed by their specific assets.

In this specific case it renders as:
Entry 1
Entry 2
Entry 3
Asset 1
Asset 2
Asset 3

I want it to render as: Entry 1 Asset 1, Entry 2 Asset 2 etc...

Putting the asset array loop inside the fields loop didn't help :)

Javascript

```<code>client.getEntries({
    include: 1,
    'content_type': 'posts'
})
.then((response) => {

    var template = $('#myEntries').html();
    var html = Mustache.to_html(template, response.toPlainObject());
    $('.result').html(html);

})
.catch((error) => {
    console.log('Error occured')
    console.log(error)
})
</code>```

HTML

```<code><script id="myEntries" type="text/template">
    {{#items}}
        <h1>{{fields.header}}</h1>
        <p>{{fields.description}}</p>
    {{/items}}

    {{#includes.Asset}}
        <p>File: <img src="https:{{fields.file.url}}?fit=thumb&f=top_left&h=200&w=200" width="100"/></p>
    {{/includes.Asset}}
</script>

<div class="result"></div>
</code>```

JSON
https://jsfiddle.net/pcgn73zf/

Would love your help!

答:
You are flattering JSON with response.toPlainObject(). Try reading required properties in desired order.

Example:

var input = {
  entries: [
    {
      text: "Entry 1"
    },
    {
      text: "Entry 2"
    }
  ],
  assets: [
    {
      text: "Asset 1"
    },
    {
      text: "Asset 2"
    }
  ]
};

var i = 0;
while (i < Math.max(input.entries.length, input.assets.length)) {
  if (i < input.entries.length) {
    document.write(input.entries[i].text + ", ");
  }
  if (i < input.assets.length) {
    document.write(input.assets[i].text + ", ");
  }
  i++;
}```

Title: Looping assets and entries together

Body:
I have managed to loop out all content from a specific ContentType and everything works well except that the entries are not followed by their specific assets.

In this specific case it renders as:
Entry 1
Entry 2
Entry 3
Asset 1
Asset 2
Asset 3

I want it to render as: Entry 1 Asset 1, Entry 2 Asset 2 etc...

Putting the asset array loop inside the fields loop didn't help :)

Javascript

client.getEntries({
    include: 1,
    'content_type': 'posts'
})
.then((response) => {

    var template = $('#myEntries').html();
    var html = Mustache.to_html(template, response.toPlainObject());
    $('.result').html(html);

})
.catch((error) => {
    console.log('Error occured')
    console.log(error)
})

HTML

JSON
https://jsfiddle.net/pcgn73zf/

Would love your help!


问:
Spring MVC 415 error when posting form
Getting 415 error when doing POST request.
This is my form:

```<code><c:url value="/createOrUpdate" var="actionUrl"/>
  <form  action="${actionUrl}" method="post" enctype="application/x-www-form-urlencoded">
    <table class="editor silver">
      <tr>
        <th colspan="2">Edit advert details</th>
        <input type="number" hidden value="${advert.id}" name="id"/>
      </tr>
      <tr>
        <td>Owner:</td>
        <td>
          <input type="text" disabled value="${advert.owner}" name="owner"/>
        </td>
      </tr>
      <tr>
        <td>Publication date:</td>
        <td>
          <input type="datetime" disabled value="${advert.publicationDate}" name="publicationDate"/>
        </td>
      </tr>
      <tr>
        <td>Select rubric</td>
        <td>
          <select name="rubric">
            <option value="sale" selected>Sale</option>
            <option value="buy">Buy</option>
            <option value="lease">Lease</option>
            <option value="services">Services</option>
            <option value="dating">Dating</option>
          </select>
        </td>
      </tr>
      <tr>
        <td>Enter header:</td>
        <td>
          <input type="text" value="${advert.header}" name="header"/>
        </td>
      </tr>
      <tr>
        <td>Enter text:</td>
        <td>
          <input type="text" value="${advert.text}" name="text"/>
        </td>
      </tr>
</code>```

And this is controller where i'm doing request

```<code>@RequestMapping(value = "/createOrUpdate", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ModelAndView editAdvert(@RequestBody Advert advert) {//some actions
</code>```

Advert is a simple POJO with getters and setters:

```<code>private long id;

private String owner;

private Date publicationDate;

private String rubric;

private String header;

private String text;
</code>```

What i'm doing wrong?
p.s. As i understand spring should map that 'name-fields' into fields of POJO. Right?
Added Ok, i found that some values didn't send in form. I checked console in browser and now it's ok, but still i get 415 error.

答:
The problem was in date conversion.
Change @RequestBody to @MadelAttribute and put @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
    private Date publicationDate;
to a model

Title: Spring MVC 415 error when posting form

Body:
Getting 415 error when doing POST request.
This is my form:

<c:url value="/createOrUpdate" var="actionUrl"/>
  <form  action="${actionUrl}" method="post" enctype="application/x-www-form-urlencoded">

        Edit advert details
        <input type="number" hidden value="${advert.id}" name="id"/>

        Owner:

          <input type="text" disabled value="${advert.owner}" name="owner"/>

        Publication date:

          <input type="datetime" disabled value="${advert.publicationDate}" name="publicationDate"/>

        Select rubric

          <select name="rubric">
            <option value="sale" selected>Sale</option>
            <option value="buy">Buy</option>
            <option value="lease">Lease</option>
            <option value="services">Services</option>
            <option value="dating">Dating</option>
          </select>

        Enter header:

          <input type="text" value="${advert.header}" name="header"/>

        Enter text:

          <input type="text" value="${advert.text}" name="text"/>

And this is controller where i'm doing request

@RequestMapping(value = "/createOrUpdate", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ModelAndView editAdvert(@RequestBody Advert advert) {//some actions

Advert is a simple POJO with getters and setters:

private long id;

private String owner;

private Date publicationDate;

private String rubric;

private String header;

private String text;

What i'm doing wrong?
p.s. As i understand spring should map that 'name-fields' into fields of POJO. Right?
Added Ok, i found that some values didn't send in form. I checked console in browser and now it's ok, but still i get 415 error.


问:
Cloud Functions for Firebase monitor node leaf if deleted check if parent exists
I am monitoring for changes in node leaf jobs/{jobid}/proposals. Whenever I remove the proposals the function gets executed and reinsert proposals (this is the expected behavior).
The problem is When I remove its parent {job}, proposals gets reinserted in a new object with same parent ID. Is there a way to do a check if the parent exists? If so, reinsert proposal otherwise not.

```<code>exports.RecountProposals = functions.database.ref("/jobs/{jobid}/proposals").onWrite(event => {
    const jobid = event.params.jobid;
    if (!event.data.exists() && event.data.ref.parent.exists()) {
        const propRef = admin.database().ref(`proposals/${jobid}`);
        const counterRef = event.data.ref;
        const collectionRef = counterRef.parent.child('proposals');
        // Return the promise from counterRef.set() so our function
        // waits for this async event to complete before it exits.
        return propRef.once('value')
            .then(messagesData => collectionRef.set(messagesData.numChildren()));
    }
});
</code>```

I am checking if parent exists but it is showing an error:

event.data.ref.parent.exists()

TypeError: event.data.ref.parent.exists is not a function

答:
event.data.ref.parent is a Reference type object.  As you can see from the linked doc, there is no exists() method on Reference.  In Realtime Database, if you want to know if there is any data at a node, simply fetch the snapshot there and call val() on it to check to see if it's null.  Reference objects are just paths, they don't contain any knowledge of data.

To put it another way, there is no such concept as a node that "exists" but contains no data, like an empty folder in a filesystem. For any given path that you can construct, the snapshot of the data there is either available (non-null) or not (null).

Body:
I am monitoring for changes in node leaf jobs/{jobid}/proposals. Whenever I remove the proposals the function gets executed and reinsert proposals (this is the expected behavior).
The problem is When I remove its parent {job}, proposals gets reinserted in a new object with same parent ID. Is there a way to do a check if the parent exists? If so, reinsert proposal otherwise not.

exports.RecountProposals = functions.database.ref("/jobs/{jobid}/proposals").onWrite(event => {
    const jobid = event.params.jobid;
    if (!event.data.exists() && event.data.ref.parent.exists()) {
        const propRef = admin.database().ref(`proposals/${jobid}`);
        const counterRef = event.data.ref;
        const collectionRef = counterRef.parent.child('proposals');
        // Return the promise from counterRef.set() so our function
        // waits for this async event to complete before it exits.
        return propRef.once('value')
            .then(messagesData => collectionRef.set(messagesData.numChildren()));
    }
});

I am checking if parent exists but it is showing an error:

event.data.ref.parent.exists()

TypeError: event.data.ref.parent.exists is not a function


问:
How to authenticate to the server over a secure connection to send mail from a script?
My current script uses this simple command:

```<code>mail -s "$my_msg" username\@mycompany.com </dev/null
</code>```

When changing it to use a mailing list rather than the hardcoded username:

```<code>mail -s "$my_msg" mailing_list_1\@groups.mycompany.com </dev/null
</code>```

It produces:

550 Unrouteable address

I need to be able to authenticate to the server over a secure connection.
How do I do this?

Linux version 2.6.26

答:
msmtp is an SMTP client:

TLS/SSL both in SMTP-over-SSL mode and
  in STARTTLS mode. Full certificate
  trust checks can be performed. A
  client certificate can be sent.

ContentLicense: CC BY-SA 2.5

Body:
My current script uses this simple command:

mail -s "$my_msg" username\@mycompany.com </dev/null

When changing it to use a mailing list rather than the hardcoded username:

mail -s "$my_msg" mailing_list_1\@groups.mycompany.com </dev/null

It produces:

550 Unrouteable address

I need to be able to authenticate to the server over a secure connection.
How do I do this?

Linux version 2.6.26


问:
SQL/PHP - find average for sum of specific items
Well, SQL is not my native language and I can't handle with my problem.
I have one table.

```<code>+------------+--------+-----------+
| Item name: | Price: | Quantity: |
+------------+--------+-----------+
| Cherry     |     20 |        11 |
| Cherry     |     19 |         9 |
| Apple      |     20 |         2 |
| Apple      |     19 |         1 |
| Cherry     |     16 |         2 |
| Apple      |     15 |         1 |
| Apple      |     21 |         1 |
| Apple      |     14 |         4 |
| Cherry     |     11 |         1 |
+------------+--------+-----------+
</code>```

I need to find average price for 5 cheapest Apples. Thanks for any help.

答:
If I understand correctly, you want to get first 5 apples with least price and find weighted average of price. You can use user variables here.

```<code>select
    sum(price * quantity) / sum(quantity) as average_price
from (
    select
        price,
        case when diff >= 0 then quantity else quantity + diff end as quantity
    from (
        select t.*,
            @required := @required - quantity as diff
        from your_table t
        cross join (select @required := 5) x
        where item_name = 'Apple'
        order by price
    ) t where quantity + diff > 0
) t;
</code>```

See this demo - http://rextester.com/XZQ74947

You can run the subqueries independently to see how it's actually working.

Body:
Well, SQL is not my native language and I can't handle with my problem.
I have one table.

+------------+--------+-----------+
| Item name: | Price: | Quantity: |
+------------+--------+-----------+
| Cherry     |     20 |        11 |
| Cherry     |     19 |         9 |
| Apple      |     20 |         2 |
| Apple      |     19 |         1 |
| Cherry     |     16 |         2 |
| Apple      |     15 |         1 |
| Apple      |     21 |         1 |
| Apple      |     14 |         4 |
| Cherry     |     11 |         1 |
+------------+--------+-----------+

I need to find average price for 5 cheapest Apples. Thanks for any help.

Body:
If I understand correctly, you want to get first 5 apples with least price and find weighted average of price. You can use user variables here.

select
    sum(price * quantity) / sum(quantity) as average_price
from (
    select
        price,
        case when diff >= 0 then quantity else quantity + diff end as quantity
    from (
        select t.*,
            @required := @required - quantity as diff
        from your_table t
        cross join (select @required := 5) x
        where item_name = 'Apple'
        order by price
    ) t where quantity + diff > 0
) t;

See this demo - http://rextester.com/XZQ74947

You can run the subqueries independently to see how it's actually working.


问:
How to use MoveFile function of windows.h The function is prepending the path in filename
```<code>path[ ]="folder" ;

strcat(path,fname) ;

MoveFile(fname,path) ;
</code>```

how to use MoveFile function of windows.h The function is prepending the path in filename

答:
The way you are initializing path, it only has room to hold "folder", you can't append anything more to it without overflowing memory. You need to allocate more space for it, eg:

```<code>char path[MAX_PATH] = {};
strcpy(path, "folder");
strcat(path, "\\");
strcat(path, fname);
</code>```

However, using the Win32 API PathCombine() (or related) function (or a 3rd party solution like boost::filesystem) would be safer:

```<code>char path[MAX_PATH] = {};
PathCombine(path, "folder", fname);
</code>```

Now, with that said, you are passing fname as the first argument to MoveFile(). Assuming fname contains just a filename and no path, MoveFile() will look for the file in a path that is relative to the calling process's current working directory, which is a dynamic value that can (and usually does) change during the process's lifetime. NEVER rely on relative paths, ALWAYS use absolute paths instead.

```<code>char src[MAX_PATH] = {};
strcpy(src, "source folder");
strcat(src, "\\");
strcat(src, fname);
// or: PathCombine(src, "source folder", fname);

char dst[MAX_PATH] = {};
strcpy(dst, "destination folder");
strcat(dst, "\\");
strcat(dst, fname);
// or: PathCombine(dst, "destination folder", fname);

MoveFile(src, dst);
</code>```

Body:
path[ ]="folder" ;

strcat(path,fname) ;

MoveFile(fname,path) ;

how to use MoveFile function of windows.h The function is prepending the path in filename

Body:
The way you are initializing path, it only has room to hold "folder", you can't append anything more to it without overflowing memory. You need to allocate more space for it, eg:

char path[MAX_PATH] = {};
strcpy(path, "folder");
strcat(path, "\\");
strcat(path, fname);

However, using the Win32 API PathCombine() (or related) function (or a 3rd party solution like boost::filesystem) would be safer:

char path[MAX_PATH] = {};
PathCombine(path, "folder", fname);

Now, with that said, you are passing fname as the first argument to MoveFile(). Assuming fname contains just a filename and no path, MoveFile() will look for the file in a path that is relative to the calling process's current working directory, which is a dynamic value that can (and usually does) change during the process's lifetime. NEVER rely on relative paths, ALWAYS use absolute paths instead.

char src[MAX_PATH] = {};
strcpy(src, "source folder");
strcat(src, "\\");
strcat(src, fname);
// or: PathCombine(src, "source folder", fname);

char dst[MAX_PATH] = {};
strcpy(dst, "destination folder");
strcat(dst, "\\");
strcat(dst, fname);
// or: PathCombine(dst, "destination folder", fname);

MoveFile(src, dst);


问:
Processing large csv files in Python
I have large CSV files containing more than 315 million rows and a single column. I have to process more than 50 such files at a time to get the results.

As I read more than 10 using a csv reader, it takes more than 12GB of RAM and is painfully slow. I can read only a chunk of the file to save memory but would spend more time in reading the file as it will read the whole file every time.

I have thought about loading them into a database and querying the data from there. However, I am not sure if this approach would help in any way. Can anyone please tell which is the most efficient way of handling such scenarios in Python?

答:
Check out ETLyte, a tool I've just open sourced.  It's .NET, but you could call out to the EXE from Python.  It's still a work in progress but I think it'll work for your situation.

With ETLyte, here would be the steps:

Place files in Flatfiles folder, or whichever folder you specify in the config.json.

Describe them with a JSON schema and place them in the Schemas folder, or whichever you specify (Note:  If they all have the same schema [you said it's all a single column], then just change flatfile field in the schema to a regex that matches your files)

When it comes to performing the addition/multiplication, you could create derived columns that perform that calculation.

Run ETLyteExe.exe and allow the data to flow in

ETLyte is just getting started but it has a lot of features and a lot more on the roadmap.  It also comes with an interactive REPL with word completion which wraps the SQLite DLL so you can interrogate the data without installing sqlite3.  For an overview of the tool, look here.

Title: Processing large csv files in Python


问:
Set StringFormat in xaml Style returns binding error
I want to create a style for textboxes containing numeric values, like this:

```<code><Style x:Key="MoneyTextbox" TargetType="{x:Type TextBox}">
    <Setter Property="Height" Value="20"/>
    <Setter Property="Margin" Value="10,5,10,5" />
    <Setter Property="VerticalAlignment" Value="Center" />
    <Setter Property="HorizontalContentAlignment" Value="Right"/>
    <Setter Property="VerticalContentAlignment" Value="Center" />
    <Setter Property="Text" Value="{Binding Path=., StringFormat='#,##0.00;-#,##0.00'}" />
</Style>
</code>```

I use the style like this:

```<code><TextBox x:Name="tbNumerical" Text="{Binding Receipt.Amount}" Style="{StaticResource MoneyTextbox}" Grid.Column="0"/>
</code>```

But the returns the following error:

System.Windows.Data Error: 1 : Cannot create default converter to
  perform 'two-way' conversions between types
  'ViewModel.UserControl.vmReceipt' and 'System.String'. Consider using
  Converter property of Binding. BindingExpression:Path=.;
  DataItem=vmReceipt' (HashCode=48860040); target element is 'TextBox'
  (Name=tbNumerical); target property is 'Text' (type 'String')

How can I fix this?

答:
The style defines the default value of 'Text'. But through

```<code>Text="{Binding Receipt.Amount}"
</code>```

you override the value of 'Text' defined by your style.

You have to redefine the whole value of 'Text'

```<code>Text="{Binding Path=Receipt.Amount, StringFormat='#,##0.00;-#,##0.00'}"
</code>```

The problem is that 'StringFormat' is a property of the binding and not of the 'Text' attribute.

Body:
I want to create a style for textboxes containing numeric values, like this:

I use the style like this:

<TextBox x:Name="tbNumerical" Text="{Binding Receipt.Amount}" Style="{StaticResource MoneyTextbox}" Grid.Column="0"/>

But the returns the following error:

System.Windows.Data Error: 1 : Cannot create default converter to
  perform 'two-way' conversions between types
  'ViewModel.UserControl.vmReceipt' and 'System.String'. Consider using
  Converter property of Binding. BindingExpression:Path=.;
  DataItem=vmReceipt' (HashCode=48860040); target element is 'TextBox'
  (Name=tbNumerical); target property is 'Text' (type 'String')

How can I fix this?

Body:
The style defines the default value of 'Text'. But through

Text="{Binding Receipt.Amount}"

you override the value of 'Text' defined by your style.

You have to redefine the whole value of 'Text'

Text="{Binding Path=Receipt.Amount, StringFormat='#,##0.00;-#,##0.00'}"

The problem is that 'StringFormat' is a property of the binding and not of the 'Text' attribute.


问:
Can't get GD image to display
my code:
save this file as captcha.php

```<code>    <?php
ob_start();
session_start();
if(!isset($_POST['submit'])){
    echo "<form method=\"post\" action=\"captcha.php\">\n";
    echo "<table border=\"0\" cellspacing=\"3\" cellpadding=\"3\">\n";
    echo "<tr><td>Type The Letters You See Below Into the Box</td></tr>\n";
    echo "<tr><td align=\"center\"><img src=\"image.php\"></td></tr>\n";
    echo "<tr><td align=\"center\"><input type=\"text\" name=\"image\"></td></tr>\n";
    echo "<tr><td align=\"center\"><input type=\"submit\" name=\"submit\" value=\"Check CAPTCHA\"></td></tr>\n";
    echo "</table></form>\n";
}else {
    $image = $_POST['image'];
    if ($image == $_SESSION['string'])
    {
        echo "<b>Great success!</b>\n";
    }
    else
    {
        echo "<em>Failure!</em>\n";
    }
}
ob_end_flush();
?>
</code>```

save this file as image.php

```<code><?php

session_start();
$img = imagecreatetruecolor(118,80);

$white = imagecolorallocate($img, 255, 255, 255);
$black = imagecolorallocate($img, 0, 0, 0);
$red = imagecolorallocate($img, 255, 0, 0);
$grey = imagecolorallocate($img,150, 150, 150);
$pink = imagecolorallocate($img, 200, 0, 150);
$yellow = imagecolorallocate($img, 255, 246, 0);

function randomString($length){
    $chars = "abcdefghijkmnopqrstuvwxyz023456789";
    srand((double)microtime()*1000000);
    $str = "";
    $i = 0;

        while($i <= $length){
            $num = rand() % 33;
            $tmp = substr($chars, $num, 1);
            $str = $str . $tmp;
            $i++;
        }
    return $str;
}

for($i=1;$i<=rand(1,5);$i++){
    $color = (rand(1,2) == 1) ? $pink : $red;
    imageline($img,rand(6,90),rand(6,40), rand(6,90)+6,rand(6,40)+6, $color);
}

imagefill($img, 0, 0, $yellow);

$string = randomString(rand(4,6));
$_SESSION['string'] = $string;

imagettftext($img, 20, 10, 10, 52, $black, "calibri.ttf", $string);
imagettftext($img, 20, 10, 12, 53, $grey, "calibri.ttf", $string);

header("Content-type: image/png");
imagepng($img);
imagedestroy($img);

?>
</code>```

go to this address http://www.cufonfonts.com/en/font/12048/calibri and download the font and save it in the same root folder as the to .php files we just created.

NOTE!! THIS WILL WORK ON LOCALHOST BUT IM HAVING A PROBLEM WITH THE image.php file SHOWING UP LIKE THIS -> ����JFIF��>CREATOR: gd-jpeg v1.0 (using IJG JPEG v90), default quality ��C    $.' ",#(7),01444'9=82<.342��C  2!!22222222222222222222222222222222222222222222222222��x"�����}!1AQa"q2���#B��R��$3br� .

THIS ONLY HAPPENS WHEN I TRY AND ADD IT TO THE CMS I CREATED. ALL I NEED TO KNOW IS WHY THIS IS HAPPENING I HAVE A FEELING ITS GOT SOMETHING TO DO WITH "header("Content-type: image/png");" although i could be way wrong. please help me. by the way im am trying to add a email form and have the captcha evaluate it

this is the form i am trying to insert the code into:
you can save it as form.php

```<code><?php
$query = mysql_query("SELECT * FROM forms where id = '$formid'");

echo '<h2>'.mysql_result($query, 0, "title").'</h2>';

if(mysql_result($query, 0, "description") != "") {
    echo '<p>'.mysql_result($query, 0, "description").'</p>';
}
error_reporting(E_ERROR);

?>
<form action="plugins/form_send.php" method="post" enctype="multipart/form-data" class="ajax" name="formplugin" id="form_<?php echo $formid; ?>">
<input name="formid" id="formid" type="hidden" value="<?php echo $formid; ?>" />
  <p><span class="required">*</span> = required fields.</p>
  <table border="0" cellspacing="5" cellpadding="5">
    <?php
    $field_labels_col = mysql_result($query, 0, "field_label");
    $field_labels = array();
    $field_labels =(explode('|', $field_labels_col));

    $field_types_col = mysql_result($query, 0, "field_type");
    $field_types = array();
    $field_types =(explode('|', $field_types_col));

    $field_option1_col = mysql_result($query, 0, "field_option1");
    $field_option1 = array();
    $field_option1 =(explode('|', $field_option1_col));

    $field_option2_col = mysql_result($query, 0, "field_option2");
    $field_option2 = array();
    $field_option2 =(explode('|', $field_option2_col));

    $field_validtype_col = mysql_result($query, 0, "field_validtype");
    $field_validtype = array();
    $field_validtype =(explode('|', $field_validtype_col));

    $i = 0;
    while (array_key_exists($i, $field_labels))
    {
    if(!isset($title)) { $title = ''; }
    if($title != $field_labels[$i]) {

    if(isset($field_labels[$i])) { $title = $field_labels[$i]; }
    if(isset($title)) { $stripped = urlify($title); }
    if(isset($field_types[$i])) { $type = $field_types[$i]; }
    if(isset($field_option1[$i])) { $option1 = $field_option1[$i]; }
    if(isset($field_option2[$i])) { $option2 = $field_option2[$i]; }
    if(isset($field_validtype[$i])) { $valid = $field_validtype[$i]; }

    echo '<tr>';
      echo '<td align="left" valign="top">'.$title.'</td>';
      echo '<td align="left" valign="top">';

        // -- INPUT FIELDS --
        if($type == "input") {
            echo '<input name="'.$stripped.'" type="text" id="'.$stripped.'" size="'.$option1.'" maxlength="'.$option2.'" />';
            if($valid != '') { echo '<span class="required">*</span>'; }
        }

        // -- TEXT AREAS --
        if($type == "textarea") {
            echo '<textarea name="'.$stripped.'" cols="'.$option1.'" rows="size="'.$option2.'"" id="'.$stripped.'"></textarea>';
        }

        // -- DROP DOWNS --
        if($type == "dropdown") {
            echo '<select name="'.$stripped.'" id="'.$stripped.'">';
                $l = 0;
                while (array_key_exists($l, $field_labels))
                {
                $thisoption = $field_option1[$l];
                $thistitle = $field_labels[$l];
                if($thistitle == $title) {
                echo '<option value="'.$thisoption.'">'.$thisoption.'</option>';
                }
                $l++;
                }
            echo'</select>';
        }

        // -- RADIO BUTTONS --
        if($type == "radiobutton") {
            $l = 0;
            while (array_key_exists($l, $field_labels))
            {
            $thisoption = $field_option1[$l];
            $thistitle = $field_labels[$l];
            $thisstripped = urlify($field_labels[$l]);
            if($thistitle == $title) {
              echo '<label><input type="radio" name="'.$thistitle.'" id="'.$thisstripped.'" value="'.$option1.'">'.$thisoption.'</label><br />';
            }
            $l++;
            }
        }

        // -- SIMPLE YES / NO --
        if($type == "yesno") {
            echo '<label><input type="radio" name="'.$stripped.'" id="'.$stripped.'" value="Yes">Yes</label>';
            echo '<label><input type="radio" name="'.$stripped.'" id="'.$stripped.'" value="No">No</label>';
        }

        // -- FILE UPLOADS --
        if($type == "fileupload") {
            echo '<input type="file" name="'.$stripped.'" id="'.$stripped.'" size="10"> (2mb limit)';
        }

      echo '</td>';
    echo '</tr>';
    }
    $i++;
    }
?>
    <tr id="comment-div"><td colspan="2"><input name="user-comment" size="3" value="" /></td></tr>

    <tr>
        <td colspan="2">
            <?php if(mysql_result($query, 0, "submit_text") != "") { ?>
                <p><br /><?php echo mysql_result($query, 0, "submit_text"); ?></p>
            <?php } ?>
            <div id="result"><strong>Loading... please wait.</strong></div>
            <!-- <input type="submit" name="button" id="button" value="<?php echo mysql_result($query, 0, "submit_button"); ?>" /> -->

        </td>
    </tr>
  </table>
</form>
</code>```

答:
i was faced same problem . Remove  all html tag it will 100% work..

save as php file .. index.php

```<code><?php
/**
 * PHP GD
 * create a simple image with GD library
 *
 */
//setting the image header in order to proper display the image
header("Content-Type: image/png");
//try to create an image
$im = @imagecreate(800, 600)
    or die("Cannot Initialize new GD image stream");
//set the background color of the image
$background_color = imagecolorallocate($im, 0xFF, 0xCC, 0xDD);
//set the color for the text
$text_color = imagecolorallocate($im, 133, 14, 91);
//adf the string to the image
imagestring($im, 5, 300, 300,  "I'm a pretty picture:))", $text_color);
//outputs the image as png
imagepng($im);
//frees any memory associated with the image
imagedestroy($im);
?>
</code>```

instead of...

```<code><html>
<head>
</head>
<body>

<?php
/**
 * PHP GD
 * create a simple image with GD library
 *
 */
//setting the image header in order to proper display the image
header("Content-Type: image/png");
//try to create an image
$im = @imagecreate(800, 600)
    or die("Cannot Initialize new GD image stream");
//set the background color of the image
$background_color = imagecolorallocate($im, 0xFF, 0xCC, 0xDD);
//set the color for the text
$text_color = imagecolorallocate($im, 133, 14, 91);
//adf the string to the image
imagestring($im, 5, 300, 300,  "I'm a pretty picture:))", $text_color);
//outputs the image as png
imagepng($im);
//frees any memory associated with the image
imagedestroy($im);
?>
</body>
</html>
</code>```

Title: Can't get GD image to display

Body:
my code:
save this file as captcha.php

    <?php
ob_start();
session_start();
if(!isset($_POST['submit'])){
    echo "<form method=\"post\" action=\"captcha.php\">\n";
    echo "
\n";
    echo "
Type The Letters You See Below Into the Box
\n";
    echo "

\n";
    echo "
<input type=\"text\" name=\"image\">
\n";
    echo "
<input type=\"submit\" name=\"submit\" value=\"Check CAPTCHA\">
\n";
    echo "
</form>\n";
}else {
    $image = $_POST['image'];
    if ($image == $_SESSION['string'])
    {
        echo "Great success!\n";
    }
    else
    {
        echo "Failure!\n";
    }
}
ob_end_flush();
?>

save this file as image.php

<?php

session_start();
$img = imagecreatetruecolor(118,80);

$white = imagecolorallocate($img, 255, 255, 255);
$black = imagecolorallocate($img, 0, 0, 0);
$red = imagecolorallocate($img, 255, 0, 0);
$grey = imagecolorallocate($img,150, 150, 150);
$pink = imagecolorallocate($img, 200, 0, 150);
$yellow = imagecolorallocate($img, 255, 246, 0);

function randomString($length){
    $chars = "abcdefghijkmnopqrstuvwxyz023456789";
    srand((double)microtime()*1000000);
    $str = "";
    $i = 0;

        while($i <= $length){
            $num = rand() % 33;
            $tmp = substr($chars, $num, 1);
            $str = $str . $tmp;
            $i++;
        }
    return $str;
}

for($i=1;$i<=rand(1,5);$i++){
    $color = (rand(1,2) == 1) ? $pink : $red;
    imageline($img,rand(6,90),rand(6,40), rand(6,90)+6,rand(6,40)+6, $color);
}

imagefill($img, 0, 0, $yellow);

$string = randomString(rand(4,6));
$_SESSION['string'] = $string;

imagettftext($img, 20, 10, 10, 52, $black, "calibri.ttf", $string);
imagettftext($img, 20, 10, 12, 53, $grey, "calibri.ttf", $string);

header("Content-type: image/png");
imagepng($img);
imagedestroy($img);

?>

go to this address http://www.cufonfonts.com/en/font/12048/calibri and download the font and save it in the same root folder as the to .php files we just created.

NOTE!! THIS WILL WORK ON LOCALHOST BUT IM HAVING A PROBLEM WITH THE image.php file SHOWING UP LIKE THIS -> ����JFIF��>CREATOR: gd-jpeg v1.0 (using IJG JPEG v90), default quality ��C    $.' ",#(7),01444'9=82<.342��C  2!!22222222222222222222222222222222222222222222222222��x"�����}!1AQa"q2���#B��R��$3br� .

THIS ONLY HAPPENS WHEN I TRY AND ADD IT TO THE CMS I CREATED. ALL I NEED TO KNOW IS WHY THIS IS HAPPENING I HAVE A FEELING ITS GOT SOMETHING TO DO WITH "header("Content-type: image/png");" although i could be way wrong. please help me. by the way im am trying to add a email form and have the captcha evaluate it

this is the form i am trying to insert the code into:
you can save it as form.php

<?php
$query = mysql_query("SELECT * FROM forms where id = '$formid'");

echo '
'.mysql_result($query, 0, "title").'
';

if(mysql_result($query, 0, "description") != "") {
    echo '
'.mysql_result($query, 0, "description").'
';
}
error_reporting(E_ERROR);

?>
<form action="plugins/form_send.php" method="post" enctype="multipart/form-data" class="ajax" name="formplugin" id="form_<?php echo $formid; ?>">
<input name="formid" id="formid" type="hidden" value="<?php echo $formid; ?>" />

* = required fields.

    <?php
    $field_labels_col = mysql_result($query, 0, "field_label");
    $field_labels = array();
    $field_labels =(explode('|', $field_labels_col));

    $field_types_col = mysql_result($query, 0, "field_type");
    $field_types = array();
    $field_types =(explode('|', $field_types_col));

    $field_option1_col = mysql_result($query, 0, "field_option1");
    $field_option1 = array();
    $field_option1 =(explode('|', $field_option1_col));

    $field_option2_col = mysql_result($query, 0, "field_option2");
    $field_option2 = array();
    $field_option2 =(explode('|', $field_option2_col));

    $field_validtype_col = mysql_result($query, 0, "field_validtype");
    $field_validtype = array();
    $field_validtype =(explode('|', $field_validtype_col));

    $i = 0;
    while (array_key_exists($i, $field_labels))
    {
    if(!isset($title)) { $title = ''; }
    if($title != $field_labels[$i]) {

    if(isset($field_labels[$i])) { $title = $field_labels[$i]; }
    if(isset($title)) { $stripped = urlify($title); }
    if(isset($field_types[$i])) { $type = $field_types[$i]; }
    if(isset($field_option1[$i])) { $option1 = $field_option1[$i]; }
    if(isset($field_option2[$i])) { $option2 = $field_option2[$i]; }
    if(isset($field_validtype[$i])) { $valid = $field_validtype[$i]; }

    echo '
';
      echo ''.$title.'	';
      echo '';

        // -- INPUT FIELDS --
        if($type == "input") {
            echo '<input name="'.$stripped.'" type="text" id="'.$stripped.'" size="'.$option1.'" maxlength="'.$option2.'" />';
            if($valid != '') { echo '*'; }
        }

        // -- TEXT AREAS --
        if($type == "textarea") {
            echo '<textarea name="'.$stripped.'" cols="'.$option1.'" rows="size="'.$option2.'"" id="'.$stripped.'"></textarea>';
        }

        // -- DROP DOWNS --
        if($type == "dropdown") {
            echo '<select name="'.$stripped.'" id="'.$stripped.'">';
                $l = 0;
                while (array_key_exists($l, $field_labels))
                {
                $thisoption = $field_option1[$l];
                $thistitle = $field_labels[$l];
                if($thistitle == $title) {
                echo '<option value="'.$thisoption.'">'.$thisoption.'</option>';
                }
                $l++;
                }
            echo'</select>';
        }

        // -- RADIO BUTTONS --
        if($type == "radiobutton") {
            $l = 0;
            while (array_key_exists($l, $field_labels))
            {
            $thisoption = $field_option1[$l];
            $thistitle = $field_labels[$l];
            $thisstripped = urlify($field_labels[$l]);
            if($thistitle == $title) {
              echo '<input type="radio" name="'.$thistitle.'" id="'.$thisstripped.'" value="'.$option1.'">'.$thisoption.'
';
            }
            $l++;
            }
        }

        // -- SIMPLE YES / NO --
        if($type == "yesno") {
            echo '<input type="radio" name="'.$stripped.'" id="'.$stripped.'" value="Yes">Yes';
            echo '<input type="radio" name="'.$stripped.'" id="'.$stripped.'" value="No">No';
        }

        // -- FILE UPLOADS --
        if($type == "fileupload") {
            echo '<input type="file" name="'.$stripped.'" id="'.$stripped.'" size="10"> (2mb limit)';
        }

      echo '	';
    echo '
';
    }
    $i++;
    }
?>

<input name="user-comment" size="3" value="" />

            <?php if(mysql_result($query, 0, "submit_text") != "") { ?>

<?php echo mysql_result($query, 0, "submit_text"); ?>

            <?php } ?>

Loading... please wait.

</form>

Body:
i was faced same problem . Remove  all html tag it will 100% work..

save as php file .. index.php

<?php
/**
 * PHP GD
 * create a simple image with GD library
 *
 */
//setting the image header in order to proper display the image
header("Content-Type: image/png");
//try to create an image
$im = @imagecreate(800, 600)
    or die("Cannot Initialize new GD image stream");
//set the background color of the image
$background_color = imagecolorallocate($im, 0xFF, 0xCC, 0xDD);
//set the color for the text
$text_color = imagecolorallocate($im, 133, 14, 91);
//adf the string to the image
imagestring($im, 5, 300, 300,  "I'm a pretty picture:))", $text_color);
//outputs the image as png
imagepng($im);
//frees any memory associated with the image
imagedestroy($im);
?>

instead of...

<html>
<head>
</head>
<body>

<?php
/**
 * PHP GD
 * create a simple image with GD library
 *
 */
//setting the image header in order to proper display the image
header("Content-Type: image/png");
//try to create an image
$im = @imagecreate(800, 600)
    or die("Cannot Initialize new GD image stream");
//set the background color of the image
$background_color = imagecolorallocate($im, 0xFF, 0xCC, 0xDD);
//set the color for the text
$text_color = imagecolorallocate($im, 133, 14, 91);
//adf the string to the image
imagestring($im, 5, 300, 300,  "I'm a pretty picture:))", $text_color);
//outputs the image as png
imagepng($im);
//frees any memory associated with the image
imagedestroy($im);
?>
</body>
</html>


问:
Protractor Failed: browser.findElements(...).all is not a function
First time trying to e2e test my AngularJS application.

I have an ul with the class 'meta'. The ul has a couple of li's.
I want to grab the first li and compare that to a string.

```<code>var duration = browser.findElements(by.className('meta')).all(by.tagName('li')).get(1);
</code>```

But when running the test i keep getting the error:  Failed: browser.findElements(...).all is not a function.

I already tried findElement and findElements and keep getting the same error.

I stumbled upon this previous question: Selecting second anchor element within lists using protractor. But it didn't help me.

答:
It is better to use the "default" ElementFinder syntax of Protractor, that is for example element(by.css('ul')), see the docs

You will then get this

var duration = element(by.className('meta')).all(by.tagName('li')).get(1);

Or element.all(by.css('.meta li')).first();, see the docs

Or the shorthand $$('.meta li')).first();, see the docs

Body:
First time trying to e2e test my AngularJS application.

I have an ul with the class 'meta'. The ul has a couple of li's.
I want to grab the first li and compare that to a string.

var duration = browser.findElements(by.className('meta')).all(by.tagName('li')).get(1);

But when running the test i keep getting the error:  Failed: browser.findElements(...).all is not a function.

I already tried findElement and findElements and keep getting the same error.

I stumbled upon this previous question: Selecting second anchor element within lists using protractor. But it didn't help me.


答:
You can use @ModelAttribute instead of @RequestBody. RequestBody consume json,xml. Remove application/x-www-form-urlencoded because it is already default type.

If you want to use @Requestbody then you post your form data as json, using a JavaScript-library like JQuery, you would post a JSON data with Content-Type:application/json. And use jackson-lib convert json to java object easily.

400 - bad request

The problem might be date sending. Focus on how to send date spring mvc. You can use @DateTimeFormat like this or @InıtBinder

Title: Spring MVC 415 error when posting form


问:
How do I fix the margins on PDFs created by Sphinx easily?
I have a Django Project where I used Sphinx to create my documentation. I went through sphinx-apidoc and ran 'make latexpdf'. The resulting documentation has a quite a few lines that flow out of the margin. On top of margin issues, lines in the index start overflowing onto each other.

Overflowing Lines

Margin Issues :(

Is there an easy way to fix these issues (or an easier way to create PDF documentation)?

ELI5 if possible (I'm not well-versed in LaTeX)

答:
The overflowing lines situation in the index should improve from adding this to conf.py:

```<code>latex_elements = {
    'printindex': '\\footnotesize\\raggedright\\printindex',
}
</code>```

Or, you can switch to Japanese language which does something like that (even better) out-of-the box from its special document class ;-)

TeX does not always know how by itself how to insert linebreaks: after all it is good at hyphenation of natural language. But as pointed out in comments Sphinx coerces LaTeX into handling better long code lines since 1.4.2.

Since recent 1.5.3, user can customize page margins, check http://www.sphinx-doc.org/en/stable/latex.html#the-sphinx-latex-style-package-options for documentation of hmargin and vmargin which can be configured via 'sphinxsetup'.

Body:
The overflowing lines situation in the index should improve from adding this to conf.py:

latex_elements = {
    'printindex': '\\footnotesize\\raggedright\\printindex',
}

Or, you can switch to Japanese language which does something like that (even better) out-of-the box from its special document class ;-)

TeX does not always know how by itself how to insert linebreaks: after all it is good at hyphenation of natural language. But as pointed out in comments Sphinx coerces LaTeX into handling better long code lines since 1.4.2.

Since recent 1.5.3, user can customize page margins, check http://www.sphinx-doc.org/en/stable/latex.html#the-sphinx-latex-style-package-options for documentation of hmargin and vmargin which can be configured via 'sphinxsetup'.


问:
how to make role menu in laravel
I need to make role menu in laravel , i have make in User model this funcion

```<code>public function isTeacher() {
    return $this->where('role', '3')->exists();
}
</code>```

and at the app.blade making this :

```<code>@if(Auth::user()->isTeacher())

    <li class=" btn">
        <a class="menu"  href="/">الرئيسية</a>
    </li>
    <li class=" btn">
        <a class="menu"  href="/">تقييم الأطفال</a>
    </li>
    <li class=" btn">
        <a class="menu" href="/">تسجيل طفل جديد</a>
    </li>
    <li class=" btn">
        <a class="menu" href="/indexTable">إدخال جدول الانشطة</a>
    </li>
    <li class=" btn">
        <a class="menu" href="/">مراجعة جدول الانشطة</a>
    </li>
@endif
@if (Auth::guest())

    <li class=" btn">
        <a href="/register" class="log"> تسجيل ولي أمر جديد </a>
    </li>
@endif
</code>```

But it's giving me that error :

Call to a member function isTeacher() on a non-object

答:
I don't think you need the braces "()" after your isTeacher</p>

```<code>@if(Auth::user()->isTeacher){
    //
}
</code>```

Title: how to make role menu in laravel

Body:
I need to make role menu in laravel , i have make in User model this funcion

public function isTeacher() {
    return $this->where('role', '3')->exists();
}

and at the app.blade making this :

@if(Auth::user()->isTeacher())

        الرئيسية

        تقييم الأطفال

        تسجيل طفل جديد

        إدخال جدول الانشطة

        مراجعة جدول الانشطة

@endif
@if (Auth::guest())

         تسجيل ولي أمر جديد

@endif

But it's giving me that error :

Call to a member function isTeacher() on a non-object

Body:
I don't think you need the braces "()" after your isTeacher

@if(Auth::user()->isTeacher){
    //
}


问:
Efficient way to check if individual arrays inside a 2-d array have equal lengths
Let's say we have a 2D array

int[][] arr = new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7 }, { 8, 9 } };

Here, arr[1] has a length of 3.

Is there any efficient way to check if all the 1-d arrays present within the 2-d array have equal lengths?

Say, without looping through the array or may be through using any data structure which can be preferred instead of a int[][]?

答:
In comments you said that we can use a List. So, check the difference in length at the time of adding a new list. After that, getting an answer will cost O(1):

```<code>class DataWrapper {
    private List<List<Integer>> data = new ArrayList<>();
    private List<Integer> lastAdded;
    private boolean isDifferentLength;

    public void add(List<Integer> newList) {
        if (data.add(newList)) {
            if (!isDifferentLength && isDifferentLengthWith(newList)) {
                 isDifferentLength = true;
            }
            lastAdded = newList;
        }
    }

    private boolean isDifferentLengthWith(List<Integer> newList) {
        return lastAdded != null && lastAdded.size() != newList.size();
    }

    public boolean isDifferentLength() {
        return isDifferentLength;
    }
}
</code>```

Body:
In comments you said that we can use a List. So, check the difference in length at the time of adding a new list. After that, getting an answer will cost O(1):

class DataWrapper {
    private List<List<Integer>> data = new ArrayList<>();
    private List<Integer> lastAdded;
    private boolean isDifferentLength;

    public void add(List<Integer> newList) {
        if (data.add(newList)) {
            if (!isDifferentLength && isDifferentLengthWith(newList)) {
                 isDifferentLength = true;
            }
            lastAdded = newList;
        }
    }

    private boolean isDifferentLengthWith(List<Integer> newList) {
        return lastAdded != null && lastAdded.size() != newList.size();
    }

    public boolean isDifferentLength() {
        return isDifferentLength;
    }
}


问:
Dynamic String array dosent work
I'm trying to create a dynamic array of 1000 character long strings using calloc:

```<code>int i;
char** strarr =(char**)calloc(argc,sizeof(char)*1000);
if(strarr == NULL)
    return 0;
strarr[0][0] ='a';
printf("%c\n",strarr[0][0]);
</code>```

Every time i try to run this code i get segmentation fault on the printf line, i don't get why does this happen (you can assume that argc is bigger than 0)
Thanks

P.s. im sorry that the code is in text format but im using a mobile so i dont have the code feature

答:
Hello and Welcome to the world of undefined behaviour, one of the darkest territories of the C language. Your code has several problems, which cause undefined behaviour in several occasions, but they all get executed, until you reach the printf line, where you are accessing memory, you have not allocated, which is finally caught by your system and, thus, a segmentation fault is produced.

But I think, it would be better to walk ourselves through your code.

The variable i, which is declared in the int i; line is not used anywhere in the code you have posted, but I guess you need it later.

The first piece of code, that is not right, is in this second line, where you declare an array of strings or a char**. That means that you have a pointer to pointers to chars. So, what you really want to do there is allocate memory for those pointers and not for the chars they will point to. Note that a char consumes a different amount of memory than a char*. This line is, thus, the one to go with.

```<code>char** strarr = (char**) calloc(argc, sizeof(char*));
</code>```

This will allocate memory for argc blocks of memory, each of which is of size 4 or 8 bytes, which depends on whether your system is 32 or 64-bit.

You are doing a very good job of checking whether the calloc function returned NULL or not, which is a very good practice overall.

Next, you will want to allocate memory for the strings themselves, that are pointed to by the pointers, for which you allocated memory in the previous line. These lines will do it.

```<code>for (int i = 0; i < argc; i++) {
    strarr[i] = (char*) calloc(1000, sizeof(char));
}
</code>```

This will now allocate 1000-character lengthed strings for every element of our argc-sized string array.

After that, you can continue with your code as it is and I think that no errors will be produced. Please accept an additional piece of advice from me. Learn to love valgrind. It is a very helpful program, which you can run your code with, in order to analyse memory. It is my first step, whenever I get a segmentation fault.

Title: Dynamic String array dosent work

Body:
I'm trying to create a dynamic array of 1000 character long strings using calloc:

int i;
char** strarr =(char**)calloc(argc,sizeof(char)*1000);
if(strarr == NULL)
    return 0;
strarr[0][0] ='a';
printf("%c\n",strarr[0][0]);

Every time i try to run this code i get segmentation fault on the printf line, i don't get why does this happen (you can assume that argc is bigger than 0)
Thanks

P.s. im sorry that the code is in text format but im using a mobile so i dont have the code feature

Body:
Hello and Welcome to the world of undefined behaviour, one of the darkest territories of the C language. Your code has several problems, which cause undefined behaviour in several occasions, but they all get executed, until you reach the printf line, where you are accessing memory, you have not allocated, which is finally caught by your system and, thus, a segmentation fault is produced.

But I think, it would be better to walk ourselves through your code.

The variable i, which is declared in the int i; line is not used anywhere in the code you have posted, but I guess you need it later.

The first piece of code, that is not right, is in this second line, where you declare an array of strings or a char**. That means that you have a pointer to pointers to chars. So, what you really want to do there is allocate memory for those pointers and not for the chars they will point to. Note that a char consumes a different amount of memory than a char*. This line is, thus, the one to go with.

char** strarr = (char**) calloc(argc, sizeof(char*));

This will allocate memory for argc blocks of memory, each of which is of size 4 or 8 bytes, which depends on whether your system is 32 or 64-bit.

You are doing a very good job of checking whether the calloc function returned NULL or not, which is a very good practice overall.

Next, you will want to allocate memory for the strings themselves, that are pointed to by the pointers, for which you allocated memory in the previous line. These lines will do it.

for (int i = 0; i < argc; i++) {
    strarr[i] = (char*) calloc(1000, sizeof(char));
}

This will now allocate 1000-character lengthed strings for every element of our argc-sized string array.

After that, you can continue with your code as it is and I think that no errors will be produced. Please accept an additional piece of advice from me. Learn to love valgrind. It is a very helpful program, which you can run your code with, in order to analyse memory. It is my first step, whenever I get a segmentation fault.


问:
How to check if C++ abstract method is defined at runtime
How to check if C++ abstract method is defined at runtime

```<code>class ABase{
public:
 virtual void do1() = 0;
};

class BBase: public ABase{
public:
 virtual void do1(){}
};

class CBase: public ABase{
public:
};

ABase * base = rand() % 2 ? new BBase() : new CBase();
if(&(base->do1) != 0)
  base->do1();
</code>```

This gives error.

Thanks,
Max

答: As you can't instantiate an abstract class, any class you encounter at runtime will not have any pure virtual methods (unless you're in a constructor or destructor at the time), they'll all have been overriden with a non-pure overrider. There is nothing to check.</p>

Body:
How to check if C++ abstract method is defined at runtime

class ABase{
public:
 virtual void do1() = 0;
};

class BBase: public ABase{
public:
 virtual void do1(){}
};

class CBase: public ABase{
public:
};

ABase * base = rand() % 2 ? new BBase() : new CBase();
if(&(base->do1) != 0)
  base->do1();

This gives error.

Thanks,
Max


问:
why does getdate returns 1\1\1900
i have the following code which does backward scheduling if Saturday or Sunday to move the date to Friday but why it returns 1900-01-06 00:00:00.000 rather 2017-03-31 13:18:12.300 i tried it getdate()-1 works fine which is Friday works great. I wounder why i doesn't work if Saturday or Sunday?

```<code>set datefirst 7 --Sunday

declare @ACUTBY datetime = getdate()

select
case datepart(WEEKDAY, @ACUTBY)
    when 1 then 5
    when 7 then 5
    else  @ACUTBY
end as [A-CUT BY]
</code>```

the above code 1900-01-06 00:00:00.000

---- getdate()-1------

```<code>set datefirst 7 --Sunday

declare @ACUTBY datetime = getdate()-1

select
case datepart(WEEKDAY, @ACUTBY)
    when 1 then 2
    when 7 then 5
    else  @ACUTBY
end as [A-CUT BY]
</code>```

the above code return 2017-03-31 13:18:12.300

答:
You are trying to merge two different return values.</p>

```<code>select
case when datepart(WEEKDAY, @ACUTBY) = 1 then 2
     when datepart(WEEKDAY, @ACUTBY) = 7 then 5
     else datepart(WEEKDAY, @ACUTBY)
end as [A-CUT BY]
</code>```

Title: why does getdate returns 1\1\1900

Body:
i have the following code which does backward scheduling if Saturday or Sunday to move the date to Friday but why it returns 1900-01-06 00:00:00.000 rather 2017-03-31 13:18:12.300 i tried it getdate()-1 works fine which is Friday works great. I wounder why i doesn't work if Saturday or Sunday?

set datefirst 7 --Sunday

declare @ACUTBY datetime = getdate()

select
case datepart(WEEKDAY, @ACUTBY)
    when 1 then 5
    when 7 then 5
    else  @ACUTBY
end as [A-CUT BY]

the above code 1900-01-06 00:00:00.000

---- getdate()-1------

set datefirst 7 --Sunday

declare @ACUTBY datetime = getdate()-1

select
case datepart(WEEKDAY, @ACUTBY)
    when 1 then 2
    when 7 then 5
    else  @ACUTBY
end as [A-CUT BY]

the above code return 2017-03-31 13:18:12.300

Body:
You are trying to merge two different return values.

select
case when datepart(WEEKDAY, @ACUTBY) = 1 then 2
     when datepart(WEEKDAY, @ACUTBY) = 7 then 5
     else datepart(WEEKDAY, @ACUTBY)
end as [A-CUT BY]