问:
Update textbox control count of items inside a list<> when it's cleared using Custom Events C#
I have the MainForm that contain two read-only textboxes and two buttons that either opens up as many instances of PizzaCreatorForms the user wants shown and the other buttons displays one instance of a PizzaOrdersListViewForm. The two read-only textboxes keep track of how many instance of the PizzaCreatorForm are shown (this part works) and the other keeps track of how many items are being created (this works, too).

I should add in that every object created by PizzaCreatorForm is added in the List<>, as well, as in the PizzaOrdersListViewFrom listView.Items control. There is also a clear button inside the MainForm and in the PizzaOrderListViewForm that clears the List<>.

My code works, but I ran into two problems.

Whenever a new object is added inside the list<>, it starts at 0 when I want it to start at 1.

Whenever I clear the List<> using the clear button inside PizzaOrderListViewForm, the listview control items are cleared, but the textbox displays the same number

This is the custom event I tried to use for #2:

MainForm

```<code>    public partial class Form1 : Form
    {
       public static List<Pizza> pizzaList = new List<Pizza>();
       public List<Pizza> PizzaList
       {
           get { return pizzaList; }
           set { pizzaList = value; }
       }

       //Where PizzaOrdersListViewForm is instantiated
       private void displayOrdersToolStripMenuItem_Click(object sender, EventArgs e)
       {
           PizzaOrdersListViewForm orderListV = new PizzaOrdersListViewForm();

       }
       //Where PizzaCreatorForm is instantiated
       private void newPizzaOrder_Click(object sender, EventArgs e)
       {
           PizzaCreatorForm pizzaForms = new PizzaCreatorForm(this);
           pizzaForms.PizzaInList += PizzaInListHandler;
           pizzasCreatedCounterTextBox.TextChanged += PizzaInListHandler;
       }

       public void PizzaInListHandler(object sender, EventArgs e)
       {
           pizzasCreatedCounterTextBox.Text = pizzaList.Count.ToString();
       }
       public void ClearMainListChangeHandler(object sender, EventArgs e)
       {
           pizzaList.Clear();
       }
    }
</code>```

PizzaCreatorForm

```<code>    public partial class PizzaCreatorForm : Form
    {
       public EventHandler PizzaInList;

       public Pizza Order
       {
           //Code that assigns Pizza class member variables to control values
       }

       Form1 MainForm = null;

       public PizzaCreatorForm(Form1 mForm)
       {
            InitializeComponent();
            MainForm = mForm
       }

       private void orderNewPizaaToolStripButton_Click(object sender, EventArgs e)
       {
            if(PizzaInList != null)
            {
                PizzaInList(this, new EventArgs());
            }

            MainForm.PizzaList.Add(Order);

            Order = new Pizza();
       }
    }
</code>```

PizzaOrdersListViewForm

```<code>    public partial class PizzaOrdersListViewForm : Form
    {
       public EventHandler ClearMainList;

       Form1 mainForm = null;

       public PizzaOrdersListViewForm(Form1 TheMain)
       {
          InitializeComponent();
          mainForm = TheMain;
       }

       private void clearToolStripButton_Click(object sender, EventArgs e)
       {
          if(ClearMainList != null)
          {
              ClearMainList(this, new EventArgs());
          }
          ClearMainList += mainForm.ClearMainListChangeHandler;
          pizzaListView.Items.Clear();

       }

    }
</code>```

答:
All I had to do was subscribe the PizzaOrdersListViewForm ClearMainList EventHandler to the custom PizzaInListHandler method inside the displayOrdersToolStripMenuItem_Click method in the MainForm.

```<code>private void displayOrdersToolStripMenuItem_Click(object sender, EventArgs e)
{
     PizzaOrdersListViewForm orderListV = new PizzaOrdersListViewForm();
     orderListV.ClearMainList += ClearMainListChangeHandler;
     orderListV.ClearMainList += PizzaInListHandler;
}
</code>```

I figured out my mistake with the pizzaList.Count. I accidentally used the Count that counted the sequence of each item when I should have choosen the Count that brings back the total of elements inside the List<>.

Body:
I have the MainForm that contain two read-only textboxes and two buttons that either opens up as many instances of PizzaCreatorForms the user wants shown and the other buttons displays one instance of a PizzaOrdersListViewForm. The two read-only textboxes keep track of how many instance of the PizzaCreatorForm are shown (this part works) and the other keeps track of how many items are being created (this works, too).

I should add in that every object created by PizzaCreatorForm is added in the List<>, as well, as in the PizzaOrdersListViewFrom listView.Items control. There is also a clear button inside the MainForm and in the PizzaOrderListViewForm that clears the List<>.

My code works, but I ran into two problems.

Whenever a new object is added inside the list<>, it starts at 0 when I want it to start at 1.

Whenever I clear the List<> using the clear button inside PizzaOrderListViewForm, the listview control items are cleared, but the textbox displays the same number

This is the custom event I tried to use for #2:

MainForm

    public partial class Form1 : Form
    {
       public static List<Pizza> pizzaList = new List<Pizza>();
       public List<Pizza> PizzaList
       {
           get { return pizzaList; }
           set { pizzaList = value; }
       }

       //Where PizzaOrdersListViewForm is instantiated
       private void displayOrdersToolStripMenuItem_Click(object sender, EventArgs e)
       {
           PizzaOrdersListViewForm orderListV = new PizzaOrdersListViewForm();

       }
       //Where PizzaCreatorForm is instantiated
       private void newPizzaOrder_Click(object sender, EventArgs e)
       {
           PizzaCreatorForm pizzaForms = new PizzaCreatorForm(this);
           pizzaForms.PizzaInList += PizzaInListHandler;
           pizzasCreatedCounterTextBox.TextChanged += PizzaInListHandler;
       }

       public void PizzaInListHandler(object sender, EventArgs e)
       {
           pizzasCreatedCounterTextBox.Text = pizzaList.Count.ToString();
       }
       public void ClearMainListChangeHandler(object sender, EventArgs e)
       {
           pizzaList.Clear();
       }
    }

PizzaCreatorForm

    public partial class PizzaCreatorForm : Form
    {
       public EventHandler PizzaInList;

       public Pizza Order
       {
           //Code that assigns Pizza class member variables to control values
       }

       Form1 MainForm = null;

       public PizzaCreatorForm(Form1 mForm)
       {
            InitializeComponent();
            MainForm = mForm
       }

       private void orderNewPizaaToolStripButton_Click(object sender, EventArgs e)
       {
            if(PizzaInList != null)
            {
                PizzaInList(this, new EventArgs());
            }

            MainForm.PizzaList.Add(Order);

            Order = new Pizza();
       }
    }

PizzaOrdersListViewForm

    public partial class PizzaOrdersListViewForm : Form
    {
       public EventHandler ClearMainList;

       Form1 mainForm = null;

       public PizzaOrdersListViewForm(Form1 TheMain)
       {
          InitializeComponent();
          mainForm = TheMain;
       }

       private void clearToolStripButton_Click(object sender, EventArgs e)
       {
          if(ClearMainList != null)
          {
              ClearMainList(this, new EventArgs());
          }
          ClearMainList += mainForm.ClearMainListChangeHandler;
          pizzaListView.Items.Clear();

       }

    }

Body:
All I had to do was subscribe the PizzaOrdersListViewForm ClearMainList EventHandler to the custom PizzaInListHandler method inside the displayOrdersToolStripMenuItem_Click method in the MainForm.

private void displayOrdersToolStripMenuItem_Click(object sender, EventArgs e)
{
     PizzaOrdersListViewForm orderListV = new PizzaOrdersListViewForm();
     orderListV.ClearMainList += ClearMainListChangeHandler;
     orderListV.ClearMainList += PizzaInListHandler;
}

I figured out my mistake with the pizzaList.Count. I accidentally used the Count that counted the sequence of each item when I should have choosen the Count that brings back the total of elements inside the List<>.


来源: stackexchange

问:
Read wifi status with powershell
I want to read the state of a wifi adapter. For example I want to know if the wifi device connected to an access point.

Is it possible to do it with powershell?

答:
Something like this might do it</p>

```<code>Add-Type -TypeDefinition @"
   public enum NetConnectionStatus
   {
        Disconnected=0,
        Connecting=1,
        Connected=2,
        Disconnecting=3,
        Hardware_Not_present=4,
        Hardware_disabled=5,
        Hardware_malfunction=6,
        Media_disconnected=7,
        Authenticating=8,
        Authentication_succeeded=9,
        Authentication_failed=10,
        Invalid_address=11,
        Credentials_required=12
   }
"@

$Adaptors = Get-WmiObject -class win32_networkadapter -filter "Name like '%wireless%'" | select name, deviceID, NetConnectionStatus

foreach ($adaptor in $Adaptors){
    "$($adaptor.deviceID) : $($adaptor.name) : $([NetConnectionStatus]::GetName([NetConnectionStatus],$adaptor.NetConnectionStatus))"
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Read wifi status with powershell

Body:
Something like this might do it

Add-Type -TypeDefinition @"
   public enum NetConnectionStatus
   {
        Disconnected=0,
        Connecting=1,
        Connected=2,
        Disconnecting=3,
        Hardware_Not_present=4,
        Hardware_disabled=5,
        Hardware_malfunction=6,
        Media_disconnected=7,
        Authenticating=8,
        Authentication_succeeded=9,
        Authentication_failed=10,
        Invalid_address=11,
        Credentials_required=12
   }
"@

$Adaptors = Get-WmiObject -class win32_networkadapter -filter "Name like '%wireless%'" | select name, deviceID, NetConnectionStatus

foreach ($adaptor in $Adaptors){
    "$($adaptor.deviceID) : $($adaptor.name) : $([NetConnectionStatus]::GetName([NetConnectionStatus],$adaptor.NetConnectionStatus))"
}


问:
Prevent unstable code going into default line
Currently, I have 2 repository. One repository is named jstock, which contains all the stable source code.

Another repository named jstock-refactor-calendar-to-joda, which is cloned from jstock, and it contains all the unstable experimental feature code.

All the change-set in red rectangle is unstable experimental feature code. They are not finished yet. Hence, I do not have intent to make it merge with the change-set in green rectangle (Green rectangle indicates those are stable change-set)

After jstock-refactor-calendar-to-joda pulls from jstock, here is how it looks like.

Now, I would like to let the experimental code visible to jstock (But not going into default line, as they are unstable)

Hence, when I perform push from jstock-refactor-calendar-to-joda to jstock, here is what I get.

Now all unstable code are belongs to default line!

This not what I want. In jstock, I wish the stable code (in green rectangle) remains in default (left side), unstable code (in red rectangle) remains in right side. Note that, I do not want them to be merged yet, but I would like to have both development lines (stable and unstable) being visible.

Is there any step I had done wrong?

答:
In this case you probably should have waited with pushing, and make the whole repository available.

Or, when you started that branch, you should've given it a name. You can have multiple unnamed branches all belonging to the same named branch.

In other words, all of the changesets you're seeing there is part of the default branch, however the label is only shown for the tip of that branch. Since the new changesets are now the tip, that's where the label is shown in the UI.

If you had given it a name, default would've still been down on your tipmost changeset on the default branch.

To fix that, you would have to "replay" those changesets one by one. I don't know the best way to do that, but suffice to say they would get new hashes, so anyone that has pulled those changesets already risk pushing them back in as part of the default branch.

ContentLicense: CC BY-SA 2.5


问:
Accurately measuring rspec/capybara testing time?
I'm trying to speed up tests and so far have done things like remove unnecessary database writes (using new instead of create and not using factorygirl, less feature tests, combining tests) and when I run the files individually I get a reduction in time.

However, when I run the entire test suite I end up getting roughly the same times, and sometimes I end up even getting a slower run time on my improved tests.

Any way to accurately measure this?

答:
Swapping out new instead of create with FactoryGirl is throwing the baby out with the bathwater. If you don't need persisted objects you can use FactoryGirl's build or build_stubbed and you will get the performance savings while still maintaining the parameter defaulting, etc.  Beyond that all the performance tuning you're doing really is swamped by the actual time it takes to do things in a browser, and asset compilation (especially on smaller numbers of tests) so you really won't save that much.  If performance is what you care about your best bet is to test as much as possible as in unit tests and then limit most of your feature tests to the happy path through your app.

If you still want to find the slowest tests to make sure you aren't doing anything like waiting for "not elements to exist" rather  than "elements to  not exist" and optimize them, you can specify the --profile command line option to rspec or specify 'profile_examples' in your RSpec configuration https://relishapp.com/rspec/rspec-core/docs/configuration/profile-examples


问:
How to optimize code removing unwanted characters
This code is designed for a problem where the users computer has a bug where every time he/she hits the backspace button it displays a '<' symbol. The created program should fix this and output the intended string considering that '<' represents a backspace. The input string can be up to 10^6 characters long, and it only will include lowercase letters and '<'.

My code seems to be executing correctly but, when I submit it, the website says it exceeded the time limit for test 5/25. The amount of time given is 1 second. Also, if there are only '<' symbols it should produce no output.

For example,

```<code>"hellooo<< my name is matthe<<"
</code>```

would output

```<code>"hello my name is matt"
</code>```

and

```<code>"ssadfas<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
</code>```

would output nothing, etc.

Here is the code:

```<code>input = gets.chomp
while input[/[[:lower:]]</]
    input.gsub!(/[[:lower:]]</, "")
end
input.gsub!(/</, "")
puts"#{input}"
</code>```

In the code above I stay in the while loop if there are any instances where a lowercase letter is in front of a '<'. Anywhere a lowercase letter is followed by a '<' it is replaced with nothing. Once the while loop is exited if there are any '<' symbols left, they are replaced with nothing. Then the final string is displayed.

I created a test which I think is worst case scenario for my code:

```<code>input = ("a" + "<" + "a")*10000000

#input = gets.chomp
while input[/[[:lower:]]</]
    input.gsub!(/[[:lower:]]</, "")
end
input.gsub!(/</, "")
puts"#{input}"
</code>```

I made the program stop between the creation of the string and the execution of the while loop and then ran it completely to be able to eyeball if it was taking longer than a second. It seemed to take much longer than 1 second.

How can it be modified to be faster or is there a much better way to do this?

答:
Your approach is good but you get better performance if you adapt the regular expression.

Cary, I hope you don't mind I take your excellent solution also in the benchmark ?

Benchmark done on a MRI ruby 2.3.0p0 (2015-12-25 revision 53290) [x64-mingw32]
I use .dup on my sample string to make sure none of the methods changes the input sample.

```<code>require 'benchmark'
input = ""
10_000_000.times{input << ['a','<'].sample}

def original_method inp
  while inp[/[[:lower:]]</]
    inp.gsub!(/[[:lower:]]</, "")
  end
  inp.gsub(/</, "")
end

def better_method inp
  tuple = /[^<]</
  while inp[tuple]
    inp.gsub!(inp[tuple], "")
  end
  inp.gsub(/</, "")
end

def backspace str
  bs_count = 0
  str.reverse.each_char.with_object([]) do |s, arr|
    if s == '<'
      bs_count += 1
    else
      bs_count.zero? ? arr.unshift(s) : bs_count -= 1
    end
  end.join
end

puts original_method(input.dup).length
puts better_method(input.dup).length
puts backspace(input.dup).length

Benchmark.bm do |x|
  x.report("original_method")  { original_method(input.dup) }
  x.report("backspace      ")  { backspace(input.dup) }
  x.report("better_method  ")  { better_method(input.dup) }
end
</code>```

gives

```<code>3640
3640
3640
       user     system      total        real
original_method  3.494000   0.016000   3.510000 (  3.510709)
backspace        1.872000   0.000000   1.872000 (  1.862550)
better_method    1.155000   0.031000   1.186000 (  1.187495)
</code>```

Body:
This code is designed for a problem where the users computer has a bug where every time he/she hits the backspace button it displays a '<' symbol. The created program should fix this and output the intended string considering that '<' represents a backspace. The input string can be up to 10^6 characters long, and it only will include lowercase letters and '<'.

My code seems to be executing correctly but, when I submit it, the website says it exceeded the time limit for test 5/25. The amount of time given is 1 second. Also, if there are only '<' symbols it should produce no output.

For example,

"hellooo<< my name is matthe<<"

would output

"hello my name is matt"

and

"ssadfas<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"

would output nothing, etc.

Here is the code:

input = gets.chomp
while input[/[[:lower:]]</]
    input.gsub!(/[[:lower:]]</, "")
end
input.gsub!(/</, "")
puts"#{input}"

In the code above I stay in the while loop if there are any instances where a lowercase letter is in front of a '<'. Anywhere a lowercase letter is followed by a '<' it is replaced with nothing. Once the while loop is exited if there are any '<' symbols left, they are replaced with nothing. Then the final string is displayed.

I created a test which I think is worst case scenario for my code:

input = ("a" + "<" + "a")*10000000

#input = gets.chomp
while input[/[[:lower:]]</]
    input.gsub!(/[[:lower:]]</, "")
end
input.gsub!(/</, "")
puts"#{input}"

I made the program stop between the creation of the string and the execution of the while loop and then ran it completely to be able to eyeball if it was taking longer than a second. It seemed to take much longer than 1 second.

How can it be modified to be faster or is there a much better way to do this?

Body:
Your approach is good but you get better performance if you adapt the regular expression.

Cary, I hope you don't mind I take your excellent solution also in the benchmark ?

Benchmark done on a MRI ruby 2.3.0p0 (2015-12-25 revision 53290) [x64-mingw32]
I use .dup on my sample string to make sure none of the methods changes the input sample.

require 'benchmark'
input = ""
10_000_000.times{input << ['a','<'].sample}

def original_method inp
  while inp[/[[:lower:]]</]
    inp.gsub!(/[[:lower:]]</, "")
  end
  inp.gsub(/</, "")
end

def better_method inp
  tuple = /[^<]</
  while inp[tuple]
    inp.gsub!(inp[tuple], "")
  end
  inp.gsub(/</, "")
end

def backspace str
  bs_count = 0
  str.reverse.each_char.with_object([]) do |s, arr|
    if s == '<'
      bs_count += 1
    else
      bs_count.zero? ? arr.unshift(s) : bs_count -= 1
    end
  end.join
end

puts original_method(input.dup).length
puts better_method(input.dup).length
puts backspace(input.dup).length

Benchmark.bm do |x|
  x.report("original_method")  { original_method(input.dup) }
  x.report("backspace      ")  { backspace(input.dup) }
  x.report("better_method  ")  { better_method(input.dup) }
end

gives

3640
3640
3640
       user     system      total        real
original_method  3.494000   0.016000   3.510000 (  3.510709)
backspace        1.872000   0.000000   1.872000 (  1.862550)
better_method    1.155000   0.031000   1.186000 (  1.187495)


问:
How to return all unique number combinations with the sum of N
I've edited my question as I don't think I've explained it well.  The subset_sum function that is linked as a duplicate seems to be when the list of numbers is random but would also work in my situation.  However, it seems to be inefficient for large numbers like my function below.  My questions is for a list of number that is always known based on the value of N.

If N is 10 the list of numbers would be 1 through 9 or range(1, N).  The function should return all unique number combinations from 1 to 9 with a sum of 10.  In this case my function below will solve this and return 9 however for large numbers it takes a very long time.  It seems to me there should be a better way to solve this when the range of numbers is known than having to iterate through each possible combination.  Maybe I'm wrong though.

```<code>import itertools

def counter(n):
    count = 0
    l = range(1, n)
    for i in range(1, n):
        for c in itertools.combinations(l, i):
            if sum(c) == n:
                count += 1
    return count
</code>```

答:
What you search for is partition function p.
Check out https://en.m.wikipedia.org/wiki/Partition_(number_theory)
It contains recursive formula which is only linear in terms of input. </p>

Body:
I've edited my question as I don't think I've explained it well.  The subset_sum function that is linked as a duplicate seems to be when the list of numbers is random but would also work in my situation.  However, it seems to be inefficient for large numbers like my function below.  My questions is for a list of number that is always known based on the value of N.

If N is 10 the list of numbers would be 1 through 9 or range(1, N).  The function should return all unique number combinations from 1 to 9 with a sum of 10.  In this case my function below will solve this and return 9 however for large numbers it takes a very long time.  It seems to me there should be a better way to solve this when the range of numbers is known than having to iterate through each possible combination.  Maybe I'm wrong though.

import itertools

def counter(n):
    count = 0
    l = range(1, n)
    for i in range(1, n):
        for c in itertools.combinations(l, i):
            if sum(c) == n:
                count += 1
    return count


问:
How to obfuscate files without using any external libraries?
I am currently trying to obscure the contents of files or simply txt files without using any libraries. I know that this won't be very secure at all but what I basically want is a program that asks you what the password to "encrypt" it with is, then it asks what the files name is and then it finds that file and "encrypts" it. Then another program is used to "decrypt" it so it asks for the password and filename and then "decrypts" it. I don't care about actual security so if it can be easily opened it's fine I just need it so it doesn't just open if you click the file.

On top of that I don't want it to use ANY libraries so no pycrypto or anything like that.

I am on 64 bit windows.

I also am a complete beginner in tthe world of code and only know basic things such as how to get user input, print stuff, if loops and while loops.

Thanks in advance!

答: You can try using the password as a key to encrypt it. May be a logical operation on the file on a binary level such as or, and, or others will be able to encrypt it very simply -- but it won't be secure like you mentioned.


问:
Why does android images use bitmaps to display?
Aren't bitmaps incredibly large and inefficient? </p>

<p>How come Android image views uses them then? </p>

```<code>Uri new_picture_uri = data.getData();

try
{
    Bitmap new_picture_bmp = MediaStore.Images.Media.getBitmap(getContentResolver(), new_picture_uri);

    DISPLAY_VIEW.setImageBitmap(new_picture_bmp);
}
catch (IOException exception)
{
    exception.printStackTrace();
}
</code>```

答: Bitmaps are inefficient storage wise but perfect display wise. Android converts more space efficient formats (png, jpg, etc) into bitmap objects to manipulate and display. </p>

Body:
Aren't bitmaps incredibly large and inefficient?

How come Android image views uses them then?

Uri new_picture_uri = data.getData();

try
{
    Bitmap new_picture_bmp = MediaStore.Images.Media.getBitmap(getContentResolver(), new_picture_uri);

    DISPLAY_VIEW.setImageBitmap(new_picture_bmp);
}
catch (IOException exception)
{
    exception.printStackTrace();
}


问:
cmake not working, could not exec qmake
I am using Ubuntu 14.04. I'm trying to install a program which requires cmake. When I run cmake src/ I get:

```<code>qmake: could not exec '/usr/lib/x86_64-linux-gnu/qt4/bin/qmake': No such file or directory
</code>```

What am I doing wrong?

答:
For newer versions of Ubuntu, if you have only installed version 5 of the Qt Framework, you may get this error. If you want to use Qt version 5 by default, then you should run the following command to fix the error:</p>

```<code>sudo apt install qt5-default
</code>```

Title: cmake not working, could not exec qmake

Body:
I am using Ubuntu 14.04. I'm trying to install a program which requires cmake. When I run cmake src/ I get:

qmake: could not exec '/usr/lib/x86_64-linux-gnu/qt4/bin/qmake': No such file or directory

What am I doing wrong?

Body:
For newer versions of Ubuntu, if you have only installed version 5 of the Qt Framework, you may get this error. If you want to use Qt version 5 by default, then you should run the following command to fix the error:

sudo apt install qt5-default


问:
Typescript Error Cannot find name 'require'. IONIC 3
Typescript Error
Cannot find name 'require'.
C:/Users/me/project/src/pages/home/home.ts
            // require the Twilio module and create a REST client

const client = require('twilio')(accountSid, authToken);

Ionic Framework: 3.3.0

Ionic App Scripts: 1.3.7

Angular Core: 4.1.2

Angular Compiler CLI: 4.1.2

Node: 6.10.3

OS Platform: Windows 10

Navigator Platform: Win32

User Agent: Mozilla/5.0 (Windows NT 10.0; Win64;

ts code

CODE inside home.ts:

TOP

```<code>import { Component } from '@angular/core';
import { FirebaseProvider } from './../../providers/firebase/firebase';
import { FirebaseListObservable } from 'angularfire2/database';
import { NavController, NavParams } from 'ionic-angular';
import { BarcodeScanner ,BarcodeScannerOptions } from '@ionic-native/barcode-scanner';
import { Request } from '@angular/http';

@Component({
selector: 'home',
templateUrl: 'home.html',
})
</code>```

//ALERT FUNCTION

```<code>scanAlert(){
    this.options = {
      showFlipCameraButton : true,
      formats : "QR_CODE,PDF_417",
      prompt : "SCAN QR CODE "
    }
    this.barcodeScanner.scan(this.options).then((barcodeData) => {
        console.log(barcodeData);
        this.pinText = barcodeData.text;
        const uid = this.pinText;
        this.firebaseProvider.afd.database.ref('pins')
        .orderByChild('QRCODE')
        .equalTo(uid)
        .limitToFirst(1)
        .once('value', snap => {
            let key = Object.keys(snap.val())[0]; // KEY VALUE
            let user = snap.child(key).val(); // the whole user object
            this.message = 'Parameters to send to twilio' + user.phone +
                  'regarding'+user.message;

            const accountSid = 'myacctid';
            const authToken = 'mytoken';

            // require the Twilio module and create a REST client
            const client = require('twilio')(accountSid, authToken);

            client.messages
            .create({
                to: '+142mynumber  ',
                from: '+mysms trial#',
                body: 'TEST Alert Message !',
  })
  .then((message) => console.log(message.sid));
</code>```

I followed these steps

install require --save

and

npm install @types/node --save-dev

My issue is that the message does not get sent.

if i add

```<code>declare var require: any
</code>```

the error goes away, but twilio never gets the request to send the message.
enter image description here

I cannot find any tutorials for Ionic3 or Angular and twilio to send an sms
I have not even passed the parameters, I copied the

I also tried this

```<code>    var twilio = require('twilio');//Make sure to npm install @types/node
    var accountSid = 'myacctid'; // Your Account SID from www.twilio.com/console
    var authToken = 'myauthtoken';   // Your Auth Token from www.twilio.com/console

    var client = new twilio(accountSid, authToken);

    client.messages.create({
        body: 'ALERT! Someone has scanned the Alert Code for ',
        to: '+myphone'  ,// Text this number
        from: '+myTwilioTrial#' // From a valid Twilio number
    })
    .then((message) => console.log(message.sid));
</code>```

my tsconfig.json:

```<code>{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "dom",
      "es2015"
    ],
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "target": "es5"
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ],
  "compileOnSave": false,
  "atom": {
    "rewriteTsconfig": false
  }
}
</code>```

答:
@types/node

@types work best if you have module: node in your tsconfig.json.

More

Potential setup https://basarat.gitbooks.io/typescript/content/docs/quick/browser.html

Body:
Typescript Error
Cannot find name 'require'.
C:/Users/me/project/src/pages/home/home.ts
            // require the Twilio module and create a REST client

const client = require('twilio')(accountSid, authToken);

Ionic Framework: 3.3.0

Ionic App Scripts: 1.3.7

Angular Core: 4.1.2

Angular Compiler CLI: 4.1.2

Node: 6.10.3

OS Platform: Windows 10

Navigator Platform: Win32

User Agent: Mozilla/5.0 (Windows NT 10.0; Win64;

ts code

CODE inside home.ts:

TOP

import { Component } from '@angular/core';
import { FirebaseProvider } from './../../providers/firebase/firebase';
import { FirebaseListObservable } from 'angularfire2/database';
import { NavController, NavParams } from 'ionic-angular';
import { BarcodeScanner ,BarcodeScannerOptions } from '@ionic-native/barcode-scanner';
import { Request } from '@angular/http';

@Component({
selector: 'home',
templateUrl: 'home.html',
})

//ALERT FUNCTION

scanAlert(){
    this.options = {
      showFlipCameraButton : true,
      formats : "QR_CODE,PDF_417",
      prompt : "SCAN QR CODE "
    }
    this.barcodeScanner.scan(this.options).then((barcodeData) => {
        console.log(barcodeData);
        this.pinText = barcodeData.text;
        const uid = this.pinText;
        this.firebaseProvider.afd.database.ref('pins')
        .orderByChild('QRCODE')
        .equalTo(uid)
        .limitToFirst(1)
        .once('value', snap => {
            let key = Object.keys(snap.val())[0]; // KEY VALUE
            let user = snap.child(key).val(); // the whole user object
            this.message = 'Parameters to send to twilio' + user.phone +
                  'regarding'+user.message;

            const accountSid = 'myacctid';
            const authToken = 'mytoken';

            // require the Twilio module and create a REST client
            const client = require('twilio')(accountSid, authToken);

            client.messages
            .create({
                to: '+142mynumber  ',
                from: '+mysms trial#',
                body: 'TEST Alert Message !',
  })
  .then((message) => console.log(message.sid));

I followed these steps

install require --save

and

npm install @types/node --save-dev

My issue is that the message does not get sent.

if i add

declare var require: any

the error goes away, but twilio never gets the request to send the message.
enter image description here

I cannot find any tutorials for Ionic3 or Angular and twilio to send an sms
I have not even passed the parameters, I copied the

I also tried this

    var twilio = require('twilio');//Make sure to npm install @types/node
    var accountSid = 'myacctid'; // Your Account SID from www.twilio.com/console
    var authToken = 'myauthtoken';   // Your Auth Token from www.twilio.com/console

    var client = new twilio(accountSid, authToken);

    client.messages.create({
        body: 'ALERT! Someone has scanned the Alert Code for ',
        to: '+myphone'  ,// Text this number
        from: '+myTwilioTrial#' // From a valid Twilio number
    })
    .then((message) => console.log(message.sid));

my tsconfig.json:

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "dom",
      "es2015"
    ],
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "target": "es5"
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ],
  "compileOnSave": false,
  "atom": {
    "rewriteTsconfig": false
  }
}


问:
How to solve the following case?
Consider the following question:
We have 3 tables,

```<code>1. Theatre  ( theatre_Id, thatre_name )
2. ShowTime ( showTimeId,  theatre_Id, movie_id )
3. Movies   ( movie_id, movie_name )
</code>```

Now same movie name can also have different movieId's sort of dependent on the reel.

Eg: [1, HarryPotter], [2, HarryPotter], [3, Pirates of Carr]

Now we need to find movie name which has showtime on all theatre locations ?
Is it nested correlated query ?

答:
If you better phrase the question:

What are the names of movies whose theatre list is the same size as the number of theatres?

you get the query:

```<code>select distinct movie_name
from Movies m
where movie_id in (
    select movie_id
    from ShowTime
    group by movie_id
    having count(distinct theatre_Id) = (select count(*) from Theatre))
</code>```

Title: How to solve the following case?

Body:
Consider the following question:
We have 3 tables,

1. Theatre  ( theatre_Id, thatre_name )
2. ShowTime ( showTimeId,  theatre_Id, movie_id )
3. Movies   ( movie_id, movie_name )

Now same movie name can also have different movieId's sort of dependent on the reel.

Eg: [1, HarryPotter], [2, HarryPotter], [3, Pirates of Carr]

Now we need to find movie name which has showtime on all theatre locations ?
Is it nested correlated query ?

Body:
If you better phrase the question:

What are the names of movies whose theatre list is the same size as the number of theatres?

you get the query:

select distinct movie_name
from Movies m
where movie_id in (
    select movie_id
    from ShowTime
    group by movie_id
    having count(distinct theatre_Id) = (select count(*) from Theatre))


问:
What is the best practice to join tables during graphql query
If my graphql has a user which has posts that are followed which obviously have posted users is there a best practice to efficiently get the data but not over request from the database.

should not join posts table
{ users { first_name } }

should join posts but not back onto users
{ users { followedPosts { title } } }

should join posts and back onto users for poster
{ users {followedPosts { poster { first_name } } } }

I've thought about inspecting the context on the initial resolver to see if the appropriate fields are fetched but in the library i'm using it is pretty ugly.

I'd like to know if there are good practices that exist to solve this and add appropriate joins or does everyone just query the heck out of the database and try to do some caching.

Also, if joins aren't common, what about inspecting the posters that will be requested and fetch them all in one go rather than as graphql resolves down the chain.

答:
Stick to separate queries for separate tables and have a look at DataLoader for batching multiples calls to the same table, and eventually some per-request caching.

This is usually more than enough.


问:
Linq to Entities: usage of function causes multiple queries
I noticed very strange Linq to Entities behavior if user defined functions (which are properly declared and connected to Linq) are used in Linq query.
Suppose I execute statement

```<code>var list = (from ts in context.Tests select MyFunction(ts.TestId));
</code>```

Linq builds correct SQL Select query, which uses MyFunction properly. But the problem is: Linq generates and sends this statement for every row in the table instead of sending it once! I looked in SQL profiler and found that the number of times this Select statement is sent to server is exactly the number of records in Test table…

What is this? Is it another bug in Linq to Entities? Does anybody know any workaround? As behavior like this really makes database side functions not usable.

答:
But this is precisely what you have written in your LINQ query: select a result of MyFunction(ts.TestId) for every row in the Tests table.
If you have 25 rows in your table than your resultset will contain 25 records as well, each obtained by executing MyFunction.

What do you actually want to do? Do you want to execute MyFunction only once? If so, which TestId you want to pass if you have 25 records?

Body:
I noticed very strange Linq to Entities behavior if user defined functions (which are properly declared and connected to Linq) are used in Linq query.
Suppose I execute statement

var list = (from ts in context.Tests select MyFunction(ts.TestId));

Linq builds correct SQL Select query, which uses MyFunction properly. But the problem is: Linq generates and sends this statement for every row in the table instead of sending it once! I looked in SQL profiler and found that the number of times this Select statement is sent to server is exactly the number of records in Test table…

What is this? Is it another bug in Linq to Entities? Does anybody know any workaround? As behavior like this really makes database side functions not usable.


问:
Jquery function for retrieving input values of the active checkbox when the page loads. JFIDDLE
I need to display the values of the selected checkbox when the page loads. Currently, the values are displayed when I click on a checkbox, but I need the values from the default checkbox when page loads.

Here if the link to my code: JFIDDLE

Here is a link to my page: My Website

Here is my code copy & paste:

```<code><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>TEST LIST</title>
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script src="simpleCart.js"></script>
</head>
<body>
<fieldset id="" class="" style="margin-top: 0px;font-variant: small-caps;letter-spacing: 2px;" data-role="controlgroup">

    <input class="weight1" type="hidden" value="2.0" >
    <input class="price1" type="radio" name="radio-choice-v-2" id="radio-choice-v-2a" value="20.00" checked="checked">
    <label class="price_weight_lable1" style="display: flex;" for="radio-choice-v-2a">
        <div style="flex:2;">2.0 grams</div>
        <div style="flex:1;text-align: center;">$22.00</div>
    </label>

    <input class="weight2" type="hidden" value="3.5" >
    <input class="price2" type="radio" name="radio-choice-v-2" id="radio-choice-v-2b" value="45.00">
    <label class="price_weight_lable2" style="display: flex;" for="radio-choice-v-2b">
        <div style="flex:2;">3.5 grams</div>
        <div style="flex:1;text-align: center;">$45.00</div>
    </label>

   <input class="weight3" type="hidden" value="7.0" >
    <input class="price3" type="radio" name="radio-choice-v-2" id="radio-choice-v-2c" value="90.00">
    <label class="price_weight_lable3" style="display: flex;" for="radio-choice-v-2c">
        <div style="flex:2;">7.0 grams</div>
        <div style="flex:1;text-align: center;">$90.00</div>
  </label>
</fieldset>

    <script>

$('input[type=radio]').on( 'change', function(el){
  $( '.weight_results' ).text( $(this).parent().prev().val() );
  $( '.price_results' ).text( $(this).val() );
});
    </script>

<div class="simpleCart_shelfItem">

    <div class="item_price"> <!-- simplecart div -->
        <div class="price_results"></div> <!-- price function result? -->
    </div>

     <div class="item_weight"> <!-- simplecart div -->
        <div class="weight_results"></div>   <!-- weight function result? -->
    </div>

</div>

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

答:
Like in my above comment here is an example. Just put this in your  and then run the desired JS.

$( document ).ready(function() {
    alert($("#myInput").val());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<input id="myInput" type="text" value="SOME TEXT HERE"></code>```

Body:
I need to display the values of the selected checkbox when the page loads. Currently, the values are displayed when I click on a checkbox, but I need the values from the default checkbox when page loads.

Here if the link to my code: JFIDDLE

Here is a link to my page: My Website

Here is my code copy & paste:

<!doctype html>

<meta charset="utf-8">
<title>TEST LIST</title>
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">

<fieldset id="" class="" style="margin-top: 0px;font-variant: small-caps;letter-spacing: 2px;" data-role="controlgroup">

    <input class="weight1" type="hidden" value="2.0" >
    <input class="price1" type="radio" name="radio-choice-v-2" id="radio-choice-v-2a" value="20.00" checked="checked">

2.0 grams

$22.00

    <input class="weight2" type="hidden" value="3.5" >
    <input class="price2" type="radio" name="radio-choice-v-2" id="radio-choice-v-2b" value="45.00">

3.5 grams

$45.00

   <input class="weight3" type="hidden" value="7.0" >
    <input class="price3" type="radio" name="radio-choice-v-2" id="radio-choice-v-2c" value="90.00">

7.0 grams

$90.00

</fieldset>

Body:
Like in my above comment here is an example. Just put this in your  and then run the desired JS.

$( document ).ready(function() {
    alert($("#myInput").val());
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<input id="myInput" type="text" value="SOME TEXT HERE">


问:
Filtering a Pandas Dataframe with a boolean mask
How do I drop all dataframe rows  that don't match a pair of conditions.

I did this:

```<code>df = df[ ! ((df['FVID'] == 0) & (df['vstDelta'] == 0)) ]
</code>```

but that was a syntax error.  Hopefully it illustrates what I want to do, which is to drop all records containing these 2 conditions.

答:
You should use '~' instead of ! to get the negation of the condition.</p>

```<code>df = df[~((df['FVID'] == 0) & (df['vstDelta'] == 0))]
</code>```

Body:
How do I drop all dataframe rows  that don't match a pair of conditions.

I did this:

df = df[ ! ((df['FVID'] == 0) & (df['vstDelta'] == 0)) ]

but that was a syntax error.  Hopefully it illustrates what I want to do, which is to drop all records containing these 2 conditions.

Body:
You should use '~' instead of ! to get the negation of the condition.

df = df[~((df['FVID'] == 0) & (df['vstDelta'] == 0))]


问:
Extracting specific string from spreadsheet cell
I've got an LibreOffice Calc spreadsheet and need to extract a small string from a cell in each row.  The cells contain about a paragraph of text and look similar to the below but all with different words, lengths etc.  The one common thing is the actually the format of the text I need to extract, in this case 17/11/2016 09:00 but could be any date/time formatted like that in 24h format.

Lorem Ipsum is simply dummy text of the printing and typesetting
  industry. Lorem Ipsum has been the 17/11/2016 09:00 industry's
  standard dummy text ever since the 1500s, when an unknown printer took
  a galley of type and scrambled it to make a type specimen book.

I've searched the following site but can't join it together to work to even match let alone extract the actual string.

http://regexlib.com/DisplayPatterns.aspx?cattabindex=4&categoryId=5

Could someone point me in the right direction please?

答:
An alternative but similar approach that does not require a formula and returns a date/time index rather than text is to Find and Replace (Edit menu) using for Find:

```<code>(.*)([0-9]{2}/[0-9]{2}/[0-9]{4} [0-9]{2}:[0-9]{2})(.*)
</code>```

and checking Regular expressions under Other options.

There are three (groups): anything before what we want, what we want and anything after what we want and the the replacement is of only the second capture group, so for Replace using:

```<code>$2
</code>```

The patter to match is {2} of any numeric character ([0-9]) followed by /, another two numbers and forward slash, four numbers, space, another two numbers, :, and two numbers.

If data is in ColumnA the Find/Replace may be on a copy in ColumnB, to preserve the source data.

Body:
An alternative but similar approach that does not require a formula and returns a date/time index rather than text is to Find and Replace (Edit menu) using for Find:

(.*)([0-9]{2}/[0-9]{2}/[0-9]{4} [0-9]{2}:[0-9]{2})(.*)

and checking Regular expressions under Other options.

There are three (groups): anything before what we want, what we want and anything after what we want and the the replacement is of only the second capture group, so for Replace using:

$2

The patter to match is {2} of any numeric character ([0-9]) followed by /, another two numbers and forward slash, four numbers, space, another two numbers, :, and two numbers.

If data is in ColumnA the Find/Replace may be on a copy in ColumnB, to preserve the source data.


问:
How can I rotate log files monthly using Perl?
In Unix, I need to be able to archive log files into monthly folders, labelled accordingly. How do I do this in Perl?</p>

答:
When I have had this task, I use cronolog.

The package includes a Perl script called cronosplit that you can use to split an existing monolithic log file into %Y/%m/%d subdirectories.

Cronolog itself is a binary written in C that can be used as a piped target for logging.  For example, you can use it in an Apache httpd.conf:

```<code>CustomLog "|/usr/sbin/cronolog /web/logs/%Y/%m/%d/access.log"
</code>```

OwnerDisplayName: Alex Wong

LastEditorDisplayName: brian d foy

Body:
When I have had this task, I use cronolog.

The package includes a Perl script called cronosplit that you can use to split an existing monolithic log file into %Y/%m/%d subdirectories.

Cronolog itself is a binary written in C that can be used as a piped target for logging.  For example, you can use it in an Apache httpd.conf:

CustomLog "|/usr/sbin/cronolog /web/logs/%Y/%m/%d/access.log"

OwnerDisplayName: Bill Karwin


问:
Add data to Arraylist Object from fragment
I need a guide to add data from my add button of my fragment and show the list in another fragment..Everything in memory

This is my entity

```<code>public class Incidencia implements  Parcelable {

    private Integer id_incidencia;

    private String FechaRegistroIncidencia;

    private String NomRegistro;

    private  String FechaRegistro;;
    private String HoraRegistro;
    private int CodEstacion;
    private String NomEstacion;
    private int CodEquipo;
    private String NomEquipo;
    private String TipoFalla;
    private int AtoramientoMoneda;
    private int AtoramientoBillete;
    private String HoraLlegadaEstacion;
    private String Estado;
    private String Observaciones;
    private String FechaSolucion;
    private String HoraSolucion;

    public Integer getId_incidencia() {
        return id_incidencia;
    }

    public void setId_incidencia(Integer id_incidencia) {
        this.id_incidencia = id_incidencia;
    }

    public String getFechaRegistroIncidencia() {
        return FechaRegistroIncidencia;
    }

    public void setFechaRegistroIncidencia(String fechaRegistroIncidencia) {
        FechaRegistroIncidencia = fechaRegistroIncidencia;
    }

    public String getNomRegistro() {
        return NomRegistro;
    }

    public void setNomRegistro(String nomRegistro) {
        NomRegistro = nomRegistro;
    }

    public String getFechaRegistro() {
        return FechaRegistro;
    }

    public void setFechaRegistro(String fechaRegistro) {
        FechaRegistro = fechaRegistro;
    }

    public String getHoraRegistro() {
        return HoraRegistro;
    }

    public void setHoraRegistro(String horaRegistro) {
        HoraRegistro = horaRegistro;
    }

    public Integer getCodEstacion() {
        return CodEstacion;
    }

    public void setCodEstacion(Integer codEstacion) {
        CodEstacion = codEstacion;
    }

    public String getNomEstacion() {
        return NomEstacion;
    }

    public void setNomEstacion(String nomEstacion) {
        NomEstacion = nomEstacion;
    }

    public Integer getCodEquipo() {
        return CodEquipo;
    }

    public void setCodEquipo(Integer codEquipo) {
        CodEquipo = codEquipo;
    }

    public String getNomEquipo() {
        return NomEquipo;
    }

    public void setNomEquipo(String nomEquipo) {
        NomEquipo = nomEquipo;
    }

    public String getTipoFalla() {
        return TipoFalla;
    }

    public void setTipoFalla(String tipoFalla) {
        TipoFalla = tipoFalla;
    }

    public Integer getAtoramientoMoneda() {
        return AtoramientoMoneda;
    }

    public void setAtoramientoMoneda(Integer atoramientoMoneda) {
        AtoramientoMoneda = atoramientoMoneda;
    }

    public Integer getAtoramientoBillete() {
        return AtoramientoBillete;
    }

    public void setAtoramientoBillete(Integer atoramientoBillete) {
        AtoramientoBillete = atoramientoBillete;
    }

    public String getHoraLlegadaEstacion() {
        return HoraLlegadaEstacion;
    }

    public void setHoraLlegadaEstacion(String horaLlegadaEstacion) {
        HoraLlegadaEstacion = horaLlegadaEstacion;
    }

    public String getEstado() {
        return Estado;
    }

    public void setEstado(String estado) {
        Estado = estado;
    }

    public String getObservaciones() {
        return Observaciones;
    }

    public void setObservaciones(String observaciones) {
        Observaciones = observaciones;
    }

    public String getFechaSolucion() {
        return FechaSolucion;
    }

    public void setFechaSolucion(String fechaSolucion) {
        FechaSolucion = fechaSolucion;
    }

    public String getHoraSolucion() {
        return HoraSolucion;
    }

    public void setHoraSolucion(String horaSolucion) {
        HoraSolucion = horaSolucion;
    }

    public Incidencia(){}

    protected Incidencia(Parcel in){
        this.id_incidencia=in.readInt();;
        this.FechaRegistroIncidencia=in.readString();
        this.NomRegistro=in.readString();
        this.FechaRegistro=in.readString();
        this.HoraRegistro=in.readString();
        this.CodEstacion=in.readInt();
        this.NomEstacion=in.readString();
        this.CodEquipo=in.readInt();
        this.NomEquipo=in.readString();
        this.TipoFalla=in.readString();
        this.AtoramientoMoneda=in.readInt();
        this.AtoramientoBillete=in.readInt();
        this.HoraLlegadaEstacion=in.readString();
        this.Estado=in.readString();
        this.Observaciones=in.readString();
        this.FechaSolucion=in.readString();
        this.HoraSolucion=in.readString();
    }

    public static final Parcelable.Creator<Incidencia> CREATOR = new Parcelable.Creator<Incidencia>() {
        @Override
        public Incidencia createFromParcel(Parcel source) {
            return new Incidencia(source);
        }

        @Override
        public Incidencia[] newArray(int size) {
            return new Incidencia[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.FechaRegistro);
        dest.writeString(this.HoraRegistro);
        dest.writeString(this.TipoFalla);
        dest.writeString(this.FechaSolucion);
        dest.writeString(this.HoraSolucion);
        dest.writeString(this.NomEstacion);

    }

}
</code>```

This is my adapter

```<code>public class ListaIncidenciasTroncalAdapter extends RecyclerView.Adapter<ListaIncidenciasTroncalAdapter.ListaIncidenciasTroncalAdapterViewHolder>
         {

    private List<Incidencia> mLstIncidencia = new ArrayList<>();
    private OnItemClickListener listener;

    public void add(Incidencia incidencia){
        mLstIncidencia.add(incidencia);
        notifyItemInserted(mLstIncidencia.size()-1);
    }

    @Override
    public ListaIncidenciasTroncalAdapter.ListaIncidenciasTroncalAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listaincidencias_item,parent,false);
        ListaIncidenciasTroncalAdapterViewHolder  mlistaIncidenciasTroncalAdapterViewHolder = new ListaIncidenciasTroncalAdapterViewHolder(view);
        return mlistaIncidenciasTroncalAdapterViewHolder;
    }

    @Override
    public void onBindViewHolder(ListaIncidenciasTroncalAdapter.ListaIncidenciasTroncalAdapterViewHolder holder, final int position) {

        final Incidencia incidencia= mLstIncidencia.get(position);
        holder.tv_FechaRegistro.setText("Registro: "+incidencia.getFechaRegistro()+" - "+incidencia.getHoraRegistro());
        holder.tv_Falla.setText(incidencia.getTipoFalla());
        holder.tv_Estacion.setText(incidencia.getNomEstacion());
        holder.tv_FechaSolucion.setText("Solucion: "+incidencia.getFechaSolucion()+" - "+incidencia.getHoraSolucion());

    }

    @Override
    public int getItemCount() {
        return mLstIncidencia.size();
    }

    static class ListaIncidenciasTroncalAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        private OnItemClickListener listener;
        TextView tv_FechaRegistro, tv_Falla, tv_Estacion,tv_FechaSolucion;
        LinearLayout linearLayout;
        public DetalleIncidencia detalleincidencia;

        public ListaIncidenciasTroncalAdapterViewHolder(View itemView) {
            super(itemView);
            tv_FechaRegistro= (TextView) itemView.findViewById(R.id.tvRegistro);
            tv_Falla= (TextView) itemView.findViewById(R.id.tvFalla);
            tv_Estacion= (TextView) itemView.findViewById(R.id.tvEstacion);
            tv_FechaSolucion= (TextView) itemView.findViewById(R.id.tvSolucion);
            final Context context = itemView.getContext();
           // detalleincidencia=(DetalleIncidencia) itemView.findViewById(R.id.)

            linearLayout=(LinearLayout) itemView.findViewById(R.id.linearItem);

        }

        @Override
        public void onClick(View v) {
            int pos = getAdapterPosition();

            }

        }

    public void setOnItemClickListener(OnItemClickListener listener){
        this.listener = listener;
    }

    public interface OnItemClickListener{
        public void onItemClick(String textName, String textViewBrief);
    }

    }
</code>```

I want to add an Incidencia Object from this fragment

```<code>    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            /**
             *Inflate ingresoincidenciastroncal and setup Views.
             */
                final View x =  inflater.inflate(R.layout.ingresoincidenciastroncal,null);
            context = x.getContext();

            //BOTON DE AGREGAR INCIDENCIA
            botonAgregaIncidencia=(Button) x.findViewById(R.id.btnAgregarIncidencia);
            botonAgregaIncidencia.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Incidencia incidencia = new Incidencia();
                    incidencia.setFechaRegistro(mDateDisplay.getText().toString());
                    incidencia.setHoraSolucion(mTimeDisplay.getText().toString());

                    Toast toast = Toast.makeText(getContext(), "Registrado", Toast.LENGTH_SHORT);
                    toast.show();

                }
            });
return x;
}
</code>```

And I want to see the list in this fragment

```<code>public class ListaIncidenciasTroncalFragment extends Fragment {

    Context context;

    GestureDetector detector;

    private RecyclerView rvListaIncidencias;
    private ListaIncidenciasTroncalAdapter mlistaIncidenciasTroncalAdapter;

    public ListaIncidenciasTroncalFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        final View x =  inflater.inflate(R.layout.listaincidenciastroncalfragment,null);
        context = x.getContext();

        detector = new GestureDetector(getActivity(), new RecyclerViewOnGestureListener());

        rvListaIncidencias=(RecyclerView)x.findViewById(R.id.rv_listaIncidenciasTroncal);
        rvListaIncidencias.setLayoutManager(new LinearLayoutManager(getContext()));
        mlistaIncidenciasTroncalAdapter = new ListaIncidenciasTroncalAdapter();
        rvListaIncidencias.setAdapter(mlistaIncidenciasTroncalAdapter);

  //I ADD THIS ONE FOR TEST AND ITS SUCCESFULL BUT I DONT KNOW HOW TO ADD IT BY THE BUTTON IN ANOTHER FRAGMENT
  Incidencia incidencia = new Incidencia();
        incidencia.setFechaRegistro("06/06/2017");
        incidencia.setHoraRegistro("10:30");
        incidencia.setTipoFalla("Atasco Moneda");
        incidencia.setNomEstacion("Javier Prado");
        incidencia.setFechaSolucion("07/06/2017");
        incidencia.setHoraSolucion("9:20");
        mlistaIncidenciasTroncalAdapter.add(incidencia);

return x;
}
</code>```

答:
In your first fragment, define an interface which would pass your Incidencia object to the host activity. The interface method is called in your button's onClick():

```<code>public class YourFirstFragment extends Fragment {
    private OnButtonClickedListener mListener;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        ...
        botonAgregaIncidencia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ...
                mListener.onButtonClicked(incidencia);
            }
        });
    }

    public interface OnButtonClickedListener {
        void onButtonClicked(Incidencia incidencia);
    }
}
</code>```

Then, in your activity, implement this interface. The overridden method will also bundle the object and pass to your next fragment as the fragment argument:

```<code>public class YourActivity implements YourFirstFragment.OnButtonClicked {
    .
    .
    .
    @Override
    public void onButtonClicked(Incidencia incidencia){
        ListaIncidenciasTroncalFragment fragment = new ListaIncidenciasTroncalFragment();
        Bundle args = new Bundle();
        args.putParcelable("yourKey", incindencia);
        fragement.setArguments(args);
        getSupportFragmentManager().beginTransaction().replace(R.id.yourFragmentContainer, fragment).commit();
    }
}
</code>```

Finally, in your second fragment, extract the bundle or arguments like so and use it however you want:

```<code>Bundle args = getArguments();
Incidencia incidencia = args.getParcelable("yourKey");
</code>```

Body:
I need a guide to add data from my add button of my fragment and show the list in another fragment..Everything in memory

This is my entity

public class Incidencia implements  Parcelable {

    private Integer id_incidencia;

    private String FechaRegistroIncidencia;

    private String NomRegistro;

    private  String FechaRegistro;;
    private String HoraRegistro;
    private int CodEstacion;
    private String NomEstacion;
    private int CodEquipo;
    private String NomEquipo;
    private String TipoFalla;
    private int AtoramientoMoneda;
    private int AtoramientoBillete;
    private String HoraLlegadaEstacion;
    private String Estado;
    private String Observaciones;
    private String FechaSolucion;
    private String HoraSolucion;

    public Integer getId_incidencia() {
        return id_incidencia;
    }

    public void setId_incidencia(Integer id_incidencia) {
        this.id_incidencia = id_incidencia;
    }

    public String getFechaRegistroIncidencia() {
        return FechaRegistroIncidencia;
    }

    public void setFechaRegistroIncidencia(String fechaRegistroIncidencia) {
        FechaRegistroIncidencia = fechaRegistroIncidencia;
    }

    public String getNomRegistro() {
        return NomRegistro;
    }

    public void setNomRegistro(String nomRegistro) {
        NomRegistro = nomRegistro;
    }

    public String getFechaRegistro() {
        return FechaRegistro;
    }

    public void setFechaRegistro(String fechaRegistro) {
        FechaRegistro = fechaRegistro;
    }

    public String getHoraRegistro() {
        return HoraRegistro;
    }

    public void setHoraRegistro(String horaRegistro) {
        HoraRegistro = horaRegistro;
    }

    public Integer getCodEstacion() {
        return CodEstacion;
    }

    public void setCodEstacion(Integer codEstacion) {
        CodEstacion = codEstacion;
    }

    public String getNomEstacion() {
        return NomEstacion;
    }

    public void setNomEstacion(String nomEstacion) {
        NomEstacion = nomEstacion;
    }

    public Integer getCodEquipo() {
        return CodEquipo;
    }

    public void setCodEquipo(Integer codEquipo) {
        CodEquipo = codEquipo;
    }

    public String getNomEquipo() {
        return NomEquipo;
    }

    public void setNomEquipo(String nomEquipo) {
        NomEquipo = nomEquipo;
    }

    public String getTipoFalla() {
        return TipoFalla;
    }

    public void setTipoFalla(String tipoFalla) {
        TipoFalla = tipoFalla;
    }

    public Integer getAtoramientoMoneda() {
        return AtoramientoMoneda;
    }

    public void setAtoramientoMoneda(Integer atoramientoMoneda) {
        AtoramientoMoneda = atoramientoMoneda;
    }

    public Integer getAtoramientoBillete() {
        return AtoramientoBillete;
    }

    public void setAtoramientoBillete(Integer atoramientoBillete) {
        AtoramientoBillete = atoramientoBillete;
    }

    public String getHoraLlegadaEstacion() {
        return HoraLlegadaEstacion;
    }

    public void setHoraLlegadaEstacion(String horaLlegadaEstacion) {
        HoraLlegadaEstacion = horaLlegadaEstacion;
    }

    public String getEstado() {
        return Estado;
    }

    public void setEstado(String estado) {
        Estado = estado;
    }

    public String getObservaciones() {
        return Observaciones;
    }

    public void setObservaciones(String observaciones) {
        Observaciones = observaciones;
    }

    public String getFechaSolucion() {
        return FechaSolucion;
    }

    public void setFechaSolucion(String fechaSolucion) {
        FechaSolucion = fechaSolucion;
    }

    public String getHoraSolucion() {
        return HoraSolucion;
    }

    public void setHoraSolucion(String horaSolucion) {
        HoraSolucion = horaSolucion;
    }

    public Incidencia(){}

    protected Incidencia(Parcel in){
        this.id_incidencia=in.readInt();;
        this.FechaRegistroIncidencia=in.readString();
        this.NomRegistro=in.readString();
        this.FechaRegistro=in.readString();
        this.HoraRegistro=in.readString();
        this.CodEstacion=in.readInt();
        this.NomEstacion=in.readString();
        this.CodEquipo=in.readInt();
        this.NomEquipo=in.readString();
        this.TipoFalla=in.readString();
        this.AtoramientoMoneda=in.readInt();
        this.AtoramientoBillete=in.readInt();
        this.HoraLlegadaEstacion=in.readString();
        this.Estado=in.readString();
        this.Observaciones=in.readString();
        this.FechaSolucion=in.readString();
        this.HoraSolucion=in.readString();
    }

    public static final Parcelable.Creator<Incidencia> CREATOR = new Parcelable.Creator<Incidencia>() {
        @Override
        public Incidencia createFromParcel(Parcel source) {
            return new Incidencia(source);
        }

        @Override
        public Incidencia[] newArray(int size) {
            return new Incidencia[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.FechaRegistro);
        dest.writeString(this.HoraRegistro);
        dest.writeString(this.TipoFalla);
        dest.writeString(this.FechaSolucion);
        dest.writeString(this.HoraSolucion);
        dest.writeString(this.NomEstacion);

    }

}

This is my adapter

public class ListaIncidenciasTroncalAdapter extends RecyclerView.Adapter<ListaIncidenciasTroncalAdapter.ListaIncidenciasTroncalAdapterViewHolder>
         {

    private List<Incidencia> mLstIncidencia = new ArrayList<>();
    private OnItemClickListener listener;

    public void add(Incidencia incidencia){
        mLstIncidencia.add(incidencia);
        notifyItemInserted(mLstIncidencia.size()-1);
    }

    @Override
    public ListaIncidenciasTroncalAdapter.ListaIncidenciasTroncalAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listaincidencias_item,parent,false);
        ListaIncidenciasTroncalAdapterViewHolder  mlistaIncidenciasTroncalAdapterViewHolder = new ListaIncidenciasTroncalAdapterViewHolder(view);
        return mlistaIncidenciasTroncalAdapterViewHolder;
    }

    @Override
    public void onBindViewHolder(ListaIncidenciasTroncalAdapter.ListaIncidenciasTroncalAdapterViewHolder holder, final int position) {

        final Incidencia incidencia= mLstIncidencia.get(position);
        holder.tv_FechaRegistro.setText("Registro: "+incidencia.getFechaRegistro()+" - "+incidencia.getHoraRegistro());
        holder.tv_Falla.setText(incidencia.getTipoFalla());
        holder.tv_Estacion.setText(incidencia.getNomEstacion());
        holder.tv_FechaSolucion.setText("Solucion: "+incidencia.getFechaSolucion()+" - "+incidencia.getHoraSolucion());

    }

    @Override
    public int getItemCount() {
        return mLstIncidencia.size();
    }

    static class ListaIncidenciasTroncalAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        private OnItemClickListener listener;
        TextView tv_FechaRegistro, tv_Falla, tv_Estacion,tv_FechaSolucion;
        LinearLayout linearLayout;
        public DetalleIncidencia detalleincidencia;

        public ListaIncidenciasTroncalAdapterViewHolder(View itemView) {
            super(itemView);
            tv_FechaRegistro= (TextView) itemView.findViewById(R.id.tvRegistro);
            tv_Falla= (TextView) itemView.findViewById(R.id.tvFalla);
            tv_Estacion= (TextView) itemView.findViewById(R.id.tvEstacion);
            tv_FechaSolucion= (TextView) itemView.findViewById(R.id.tvSolucion);
            final Context context = itemView.getContext();
           // detalleincidencia=(DetalleIncidencia) itemView.findViewById(R.id.)

            linearLayout=(LinearLayout) itemView.findViewById(R.id.linearItem);

        }

        @Override
        public void onClick(View v) {
            int pos = getAdapterPosition();

            }

        }

    public void setOnItemClickListener(OnItemClickListener listener){
        this.listener = listener;
    }

    public interface OnItemClickListener{
        public void onItemClick(String textName, String textViewBrief);
    }

    }

I want to add an Incidencia Object from this fragment

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            /**
             *Inflate ingresoincidenciastroncal and setup Views.
             */
                final View x =  inflater.inflate(R.layout.ingresoincidenciastroncal,null);
            context = x.getContext();

            //BOTON DE AGREGAR INCIDENCIA
            botonAgregaIncidencia=(Button) x.findViewById(R.id.btnAgregarIncidencia);
            botonAgregaIncidencia.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Incidencia incidencia = new Incidencia();
                    incidencia.setFechaRegistro(mDateDisplay.getText().toString());
                    incidencia.setHoraSolucion(mTimeDisplay.getText().toString());

                    Toast toast = Toast.makeText(getContext(), "Registrado", Toast.LENGTH_SHORT);
                    toast.show();

                }
            });
return x;
}

And I want to see the list in this fragment

public class ListaIncidenciasTroncalFragment extends Fragment {

    Context context;

    GestureDetector detector;

    private RecyclerView rvListaIncidencias;
    private ListaIncidenciasTroncalAdapter mlistaIncidenciasTroncalAdapter;

    public ListaIncidenciasTroncalFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        final View x =  inflater.inflate(R.layout.listaincidenciastroncalfragment,null);
        context = x.getContext();

        detector = new GestureDetector(getActivity(), new RecyclerViewOnGestureListener());

        rvListaIncidencias=(RecyclerView)x.findViewById(R.id.rv_listaIncidenciasTroncal);
        rvListaIncidencias.setLayoutManager(new LinearLayoutManager(getContext()));
        mlistaIncidenciasTroncalAdapter = new ListaIncidenciasTroncalAdapter();
        rvListaIncidencias.setAdapter(mlistaIncidenciasTroncalAdapter);

  //I ADD THIS ONE FOR TEST AND ITS SUCCESFULL BUT I DONT KNOW HOW TO ADD IT BY THE BUTTON IN ANOTHER FRAGMENT
  Incidencia incidencia = new Incidencia();
        incidencia.setFechaRegistro("06/06/2017");
        incidencia.setHoraRegistro("10:30");
        incidencia.setTipoFalla("Atasco Moneda");
        incidencia.setNomEstacion("Javier Prado");
        incidencia.setFechaSolucion("07/06/2017");
        incidencia.setHoraSolucion("9:20");
        mlistaIncidenciasTroncalAdapter.add(incidencia);

return x;
}

Body:
In your first fragment, define an interface which would pass your Incidencia object to the host activity. The interface method is called in your button's onClick():

public class YourFirstFragment extends Fragment {
    private OnButtonClickedListener mListener;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        ...
        botonAgregaIncidencia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ...
                mListener.onButtonClicked(incidencia);
            }
        });
    }

    public interface OnButtonClickedListener {
        void onButtonClicked(Incidencia incidencia);
    }
}

Then, in your activity, implement this interface. The overridden method will also bundle the object and pass to your next fragment as the fragment argument:

public class YourActivity implements YourFirstFragment.OnButtonClicked {
    .
    .
    .
    @Override
    public void onButtonClicked(Incidencia incidencia){
        ListaIncidenciasTroncalFragment fragment = new ListaIncidenciasTroncalFragment();
        Bundle args = new Bundle();
        args.putParcelable("yourKey", incindencia);
        fragement.setArguments(args);
        getSupportFragmentManager().beginTransaction().replace(R.id.yourFragmentContainer, fragment).commit();
    }
}

Finally, in your second fragment, extract the bundle or arguments like so and use it however you want:

Bundle args = getArguments();
Incidencia incidencia = args.getParcelable("yourKey");


问:
How to do timestamp regex given start time and end time?
I was working on extracting the log lines of interest from a huge log file.
Note that I'm not familiar with python at all.

The log line all starts from a timestamp, like

09:00:00.648711172 [Info  ] [....]
```

<p>And I want to match it with a specific period of time, say from 09:00 to 09:30, I came up with the following solution:</p>

```r'^(09:[012][0-9]|30)
```

The problem is this cannot apply to a generic case, say we're given a start_time and an end_time, how can I do the match?

答: Only regex won't help you much in this case. Rather you can try to pick up the values of hour, minute and second using a regex, then do some calculation  (something like hour * 3600 + minute * 60 + second) to determine if it's in the range or not.

Body:
I was working on extracting the log lines of interest from a huge log file.
Note that I'm not familiar with python at all.

The log line all starts from a timestamp, like

09:00:00.648711172 [Info  ] [....]

And I want to match it with a specific period of time, say from 09:00 to 09:30, I came up with the following solution:

r'^(09:[012][0-9]|30)

The problem is this cannot apply to a generic case, say we're given a start_time and an end_time, how can I do the match?


问:
How to make requestbody controller works?
So actually everything is working well, except the fact that i can't get access to "inscrit" which is supposed to be the one which is sent to have the information user

This is my function in javascript and it does go into success for ajax.

```<code>function fbLogin() {
            FB.login(function (response) {
                if (response.authResponse) {
                    var inscrit = {
                        "prenom": response.first_name,
                        "nom": response.last_name,
                        "email": response.email
                    }
                    $.ajax({
                        method: 'post',
                        url: '/hello/facebookconnection',
                        contentType : 'application/json; charset=utf-8',
                        data: JSON.stringify(inscrit),
                        datatype: "json",
                        success: function() {
                        window.alert('User data sent');}
                        ,
                        error: function(){
                            window.alert('Error in sending ajax data');}
                    });
                } else {
                    document.getElementById('status').innerHTML = 'User cancelled login or did not fully authorize.';
                }
            }, {scope: 'email'});
        }
</code>```

And this is my java controller (whatever i do, the "inscrit.getEmail()" is always null)

```<code>@RequestMapping(value = "/facebookconnection", method = RequestMethod.POST)
@ResponseBody public void createUser(@RequestBody inscrit inscrit, ModelMap model) throws Exception {
    //System.out.println(inscrit.getNom());
    //System.out.println(inscrit.getPrenom());
    System.out.println(inscrit.getEmail());
    try {
        user.adduser(inscrit);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

This is my inscrit class with all the getter and setter correctly set (i know that there's no problem with it)

```<code>@Entity
@Table(name="inscrit")
public class inscrit implements Serializable {
  @Id
  @Column(name="email")
  private String email;

  @Column(name="nom")
  private String nom;

  @Column(name="prenom")
  private String prenom;
}
</code>```

So i would like to know if someone could help me understand why it's not working in my controller (how to do so the data is sent properly from the ajax to the controller) :(
Thx !

EDIT : i did write the answer of that question below. The problem was the fact that response.first_name was really blank... and had to pass through the function userdata() which had the real informations. So that means i don't have any real error in my code, all the informations between the controller and my jsp page works correctly. Be free to use it as an example of how this works

答:
This is my controller class.This just logs the post request send to the server:(You may modify this if you need something more like adding a Response Body)

```<code>@RestController
public class EmailController {
    @RequestMapping(value = "/facebookconnection", method = RequestMethod.POST)
     public void createUser(@RequestBody inscrit inscrit) throws Exception {
        System.out.println(inscrit.getNom());
        System.out.println(inscrit.getPrenom());
        System.out.println(inscrit.getEmail());

    }
</code>```

This is my inscrit.java class(I  personally think naming the class would not affect but better follow standard naming Practices like Inscrit.java)

```<code>import java.io.Serializable;

public class inscrit implements Serializable {
    private static final long serialVersionUID = -8445943548965154778L;

       private String email;

       private String prenom;

       private String nom;

       public inscrit() {
            super();
        }

        public inscrit(String email,String prenom,String nom) {
            this.setEmail(email);
            this.setPrenom(prenom);
            this.setNom(nom);

        }
       public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getNom() {
        return nom;
    }

    public void setNom(String nom) {
        this.nom = nom;
    }

    public String getPrenom() {
        return prenom;
    }

    public void setPrenom(String prenom) {
        this.prenom = prenom;
    }

    }
</code>```

I did a post request from Advanced Rest Client and set the payload as

```<code>{
 "email":"agdfae@gmail.com",
 "prenom":"qewrwe",
 "nom":"qwer"

}
</code>```

the results were

```<code>qwer
qewrwe
agdfae@gmail.com
</code>```

You can modify this to suit your own needs.Hope this helps

EDIT:

You will need more two classes in spring boot as below:

ServletInitializer.java

```<code>public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(PostDataApplication.class);
    }

}
</code>```

PostDataApplication .java

```<code>import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class PostDataApplication {

    public static void main(String[] args) {
        SpringApplication.run(PostDataApplication.class, args);
    }
}
</code>```

PostDataApplication is the name of the application.

These four classes will do the trick (with pom.xml only no other xml configuration needed since this is springboot).Let me know if you have any problem.

Body:
So actually everything is working well, except the fact that i can't get access to "inscrit" which is supposed to be the one which is sent to have the information user

This is my function in javascript and it does go into success for ajax.

function fbLogin() {
            FB.login(function (response) {
                if (response.authResponse) {
                    var inscrit = {
                        "prenom": response.first_name,
                        "nom": response.last_name,
                        "email": response.email
                    }
                    $.ajax({
                        method: 'post',
                        url: '/hello/facebookconnection',
                        contentType : 'application/json; charset=utf-8',
                        data: JSON.stringify(inscrit),
                        datatype: "json",
                        success: function() {
                        window.alert('User data sent');}
                        ,
                        error: function(){
                            window.alert('Error in sending ajax data');}
                    });
                } else {
                    document.getElementById('status').innerHTML = 'User cancelled login or did not fully authorize.';
                }
            }, {scope: 'email'});
        }

And this is my java controller (whatever i do, the "inscrit.getEmail()" is always null)

@RequestMapping(value = "/facebookconnection", method = RequestMethod.POST)
@ResponseBody public void createUser(@RequestBody inscrit inscrit, ModelMap model) throws Exception {
    //System.out.println(inscrit.getNom());
    //System.out.println(inscrit.getPrenom());
    System.out.println(inscrit.getEmail());
    try {
        user.adduser(inscrit);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

This is my inscrit class with all the getter and setter correctly set (i know that there's no problem with it)

@Entity
@Table(name="inscrit")
public class inscrit implements Serializable {
  @Id
  @Column(name="email")
  private String email;

  @Column(name="nom")
  private String nom;

  @Column(name="prenom")
  private String prenom;
}

So i would like to know if someone could help me understand why it's not working in my controller (how to do so the data is sent properly from the ajax to the controller) :(
Thx !

EDIT : i did write the answer of that question below. The problem was the fact that response.first_name was really blank... and had to pass through the function userdata() which had the real informations. So that means i don't have any real error in my code, all the informations between the controller and my jsp page works correctly. Be free to use it as an example of how this works

Body:
This is my controller class.This just logs the post request send to the server:(You may modify this if you need something more like adding a Response Body)

@RestController
public class EmailController {
    @RequestMapping(value = "/facebookconnection", method = RequestMethod.POST)
     public void createUser(@RequestBody inscrit inscrit) throws Exception {
        System.out.println(inscrit.getNom());
        System.out.println(inscrit.getPrenom());
        System.out.println(inscrit.getEmail());

    }

This is my inscrit.java class(I  personally think naming the class would not affect but better follow standard naming Practices like Inscrit.java)

import java.io.Serializable;

public class inscrit implements Serializable {
    private static final long serialVersionUID = -8445943548965154778L;

       private String email;

       private String prenom;

       private String nom;

       public inscrit() {
            super();
        }

        public inscrit(String email,String prenom,String nom) {
            this.setEmail(email);
            this.setPrenom(prenom);
            this.setNom(nom);

        }
       public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getNom() {
        return nom;
    }

    public void setNom(String nom) {
        this.nom = nom;
    }

    public String getPrenom() {
        return prenom;
    }

    public void setPrenom(String prenom) {
        this.prenom = prenom;
    }

    }

I did a post request from Advanced Rest Client and set the payload as

{
 "email":"agdfae@gmail.com",
 "prenom":"qewrwe",
 "nom":"qwer"

}

the results were

qwer
qewrwe
agdfae@gmail.com

You can modify this to suit your own needs.Hope this helps

EDIT:

You will need more two classes in spring boot as below:

ServletInitializer.java

public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(PostDataApplication.class);
    }

}

PostDataApplication .java

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class PostDataApplication {

    public static void main(String[] args) {
        SpringApplication.run(PostDataApplication.class, args);
    }
}

PostDataApplication is the name of the application.

These four classes will do the trick (with pom.xml only no other xml configuration needed since this is springboot).Let me know if you have any problem.


问:
Room - Schema export directory is not provided to the annotation processor so we cannot export the schema
I am using Android Database Component Room

I've configured everything, but when I compile, Android Studio gives me this warning:

Schema export directory is not provided to the annotation processor so
  we cannot export the schema. You can either provide
  room.schemaLocation annotation processor argument OR set
  exportSchema to false.

As I understand it is the location where DB file will be located

How can it affect my app? What is the best practice here? Should I use the default location (false value)?

答:
In the build.gradle file for your app module, add this to the defaultConfig section (under the android section). This will write out the schema to a schemas subfolder of your project folder.

```<code>javaCompileOptions {
    annotationProcessorOptions {
        arguments += ["room.schemaLocation": "$projectDir/schemas".toString()]
    }
}
</code>```

Like this:

```<code>// ...

android {

    // ... (compileSdkVersion, buildToolsVersion, etc)

    defaultConfig {

        // ... (applicationId, miSdkVersion, etc)

        javaCompileOptions {
            annotationProcessorOptions {
                arguments += ["room.schemaLocation": "$projectDir/schemas".toString()]
            }
        }
    }

    // ... (buildTypes, compileOptions, etc)

}

// ...
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In the build.gradle file for your app module, add this to the defaultConfig section (under the android section). This will write out the schema to a schemas subfolder of your project folder.

javaCompileOptions {
    annotationProcessorOptions {
        arguments += ["room.schemaLocation": "$projectDir/schemas".toString()]
    }
}

Like this:

// ...

android {

    // ... (compileSdkVersion, buildToolsVersion, etc)

    defaultConfig {

        // ... (applicationId, miSdkVersion, etc)

        javaCompileOptions {
            annotationProcessorOptions {
                arguments += ["room.schemaLocation": "$projectDir/schemas".toString()]
            }
        }
    }

    // ... (buildTypes, compileOptions, etc)

}

// ...


问:
Adding a textfile with a name to each directory
I'm having some trouble with trying to add a text file to each directory in this directory having a certain name. I have a directory called Daily Notes where I save my notes for the day and I have this further organized by week. So I have a bunch of directories in here such as 6.5.17-6.10.17 and in each of these I need a text file with the name format such as 6.7.17DailyNotes.txt. I know I can easily do this by hand each day, but I have some free time and am trying to learn how to program with cmd. I tried to just make a test text file with a for loop but it saved it to the directory containing the batch file. Here is my code right now:

```<code>@echo off
setlocal disabledelayedexpansion

set "folder=%~1"
if not defined folder set "folder=%cd%"

for /D %%a in ("%folder%\*") do (
    echo test > test.txt
)

endlocal
</code>```

So, I want to go into each directory and make 5 text files, one for each day with the format month.day.yearDailyNotes.txt. I was thinking I could just make a variable from reading the directory name and count up in days from that for the text files. Any advice?

答:
```<code>@echo off
setlocal disabledelayedexpansion

set "folder=%~1"
if not defined folder set "folder=%cd%"

for /D %%q in ("%folder%\*") do (
    echo test "%%q\%%~nxqDailyNotes.txt"
)

ENDLOCAL
</code>```

Interesting exercise with a couple of twists.

my posted code will simply show 'test "fullfilename" '. Naturally, you could use copy nul "*fullfilename*"' to create an empty file (with>nulto suppress the creation-report) orecho.>"fullfilename"` to create a file containing just an empty line - or whatever.

The main magic is with the gymnastics in creating the filename. Since you are using for/d, the directoryname will appear in %%q. so the required filename is the name+extension part of that directoryname (you and I know it's actually not a filename but the outermost leafname of a directory tree - just don't tell cmd) so we use %%~nxq meaning the name and extension part of the "filename" in %%q (see for /?|more from the prompt for documentation). We then just tack the remainder of the required name on as a literal.

So - why the change to %%q?

Suppose we leave it as %%a. The filename would then be "%%~nxaDailyNotes.txt" and be interpreted as name,extension,attribute,drive of %%a since i is neither a modifier nor a participating metavariable. Changing the metavariable from %%a to %%q removes the misinterpretation.

Body:
I'm having some trouble with trying to add a text file to each directory in this directory having a certain name. I have a directory called Daily Notes where I save my notes for the day and I have this further organized by week. So I have a bunch of directories in here such as 6.5.17-6.10.17 and in each of these I need a text file with the name format such as 6.7.17DailyNotes.txt. I know I can easily do this by hand each day, but I have some free time and am trying to learn how to program with cmd. I tried to just make a test text file with a for loop but it saved it to the directory containing the batch file. Here is my code right now:

@echo off
setlocal disabledelayedexpansion

set "folder=%~1"
if not defined folder set "folder=%cd%"

for /D %%a in ("%folder%\*") do (
    echo test > test.txt
)

endlocal

So, I want to go into each directory and make 5 text files, one for each day with the format month.day.yearDailyNotes.txt. I was thinking I could just make a variable from reading the directory name and count up in days from that for the text files. Any advice?

Body:
@echo off
setlocal disabledelayedexpansion

set "folder=%~1"
if not defined folder set "folder=%cd%"

for /D %%q in ("%folder%\*") do (
    echo test "%%q\%%~nxqDailyNotes.txt"
)

ENDLOCAL

Interesting exercise with a couple of twists.

my posted code will simply show 'test "fullfilename" '. Naturally, you could use copy nul "*fullfilename*"' to create an empty file (with>nulto suppress the creation-report) orecho.>"fullfilename"` to create a file containing just an empty line - or whatever.

The main magic is with the gymnastics in creating the filename. Since you are using for/d, the directoryname will appear in %%q. so the required filename is the name+extension part of that directoryname (you and I know it's actually not a filename but the outermost leafname of a directory tree - just don't tell cmd) so we use %%~nxq meaning the name and extension part of the "filename" in %%q (see for /?|more from the prompt for documentation). We then just tack the remainder of the required name on as a literal.

So - why the change to %%q?

Suppose we leave it as %%a. The filename would then be "%%~nxaDailyNotes.txt" and be interpreted as name,extension,attribute,drive of %%a since i is neither a modifier nor a participating metavariable. Changing the metavariable from %%a to %%q removes the misinterpretation.


问:
Remove ith item from a C++ std::vector
How do I remove the ith item from a std::vector?

I know I want to delete the ith element. I have int i; and std::vector<process> pList; where process is a struct. I want to do something equivalent to the following:

```<code>pList.remove(i);
</code>```

答:
```<code>pList.erase(pList.begin()+i);
</code>```

<p>To remove element with index i. </p>

Title: Remove ith item from a C++ std::vector

Body:
How do I remove the ith item from a std::vector?

I know I want to delete the ith element. I have int i; and std::vector<process> pList; where process is a struct. I want to do something equivalent to the following:

pList.remove(i);

Body:
pList.erase(pList.begin()+i);

To remove element with index i.


问:
Build this node project using only gulp or webpack
My project has this folder structure:

```<code>node
|   .gitignore
|   gulpfile.js
|   package.json
|   tsconfig.json
|   webpack.config.js
|
+---build
|   |   debug.js
|   |   main.js
|   |
|   +---client
|   |   +---scripts
|   |   |       bundle.js
|   |   |
|   |   \---views
|   |           index.html
|   |
|   |
|   \---server
|       |   constants.js
|       |   server.js
|       |
|       \---router
|           |   constants.js
|           |   router.js
|           |
|           \---routes
|                   base.js
|                   index.js
|
+---gulp
|   |   constants.js
|   |
|   \---tasks
|           default.js
|           html.js
|           typescript.js
|
\---src
    |   main.ts
    |
    +---client
    |   +---app
    |   |   |   app.tsx
    |   |   |
    |   |   \---components
    |   |           hello.tsx
    |   |
    |   \---views
    |           index.html
    |
    \---server
        |   constants.ts
        |   server.ts
        |
        \---router
            |   constants.ts
            |   router.ts
            |
            \---routes
                    base.ts
                    index.ts
</code>```

Gulp is used to copy HTML and compile TypeScript in build folder maintaining folder structure. But I didn't found how to also bundle front-end code and node dependencies in order to make these avaiable in build/client. After some suggestion and research I used Webpack to create bundle.js.

Now I've the expected result but I wonder if there is a way to only Gulp or Webpack, in order to simplify the build process.

答:
I wonder if there is a way to only Gulp or Webpack

These are different tools.

Gulp: Task runners. Runs code segments

Webpack: Module bundler. Bundles code in a manner that can be used in the browser.

If you want a bundler (which you do) gulp will not suffice.

Body:
My project has this folder structure:

node
|   .gitignore
|   gulpfile.js
|   package.json
|   tsconfig.json
|   webpack.config.js
|
+---build
|   |   debug.js
|   |   main.js
|   |
|   +---client
|   |   +---scripts
|   |   |       bundle.js
|   |   |
|   |   \---views
|   |           index.html
|   |
|   |
|   \---server
|       |   constants.js
|       |   server.js
|       |
|       \---router
|           |   constants.js
|           |   router.js
|           |
|           \---routes
|                   base.js
|                   index.js
|
+---gulp
|   |   constants.js
|   |
|   \---tasks
|           default.js
|           html.js
|           typescript.js
|
\---src
    |   main.ts
    |
    +---client
    |   +---app
    |   |   |   app.tsx
    |   |   |
    |   |   \---components
    |   |           hello.tsx
    |   |
    |   \---views
    |           index.html
    |
    \---server
        |   constants.ts
        |   server.ts
        |
        \---router
            |   constants.ts
            |   router.ts
            |
            \---routes
                    base.ts
                    index.ts

Gulp is used to copy HTML and compile TypeScript in build folder maintaining folder structure. But I didn't found how to also bundle front-end code and node dependencies in order to make these avaiable in build/client. After some suggestion and research I used Webpack to create bundle.js.

Now I've the expected result but I wonder if there is a way to only Gulp or Webpack, in order to simplify the build process.


问:
Multidimensional array in jquery
My Jquery code

```<code>      var attrid        = [];
      var attrvalue     = [];

      $.each($(".attname1"), function(index){

       if($('.getval'+index+'').val() != undefined){

          attrid.push($('.getval'+index+'').attr("id"));
          attrvalue.push($('.getval'+index+'').val());
        }

     });

    //outcome data
    ["5931", "5950", "5951", "5952"]  //id

    ["cas", "bsd", "Canvas", "Grey"] //name
</code>```

The result format that I actually want:

```<code>$ary = array (
              [0] => array(
                      Id => 5931,
                      value=> cas,
                     ),
              [1] => array(
                      Id => 5950,
                      value=> bsd,
                     ),
              [2] => array(
                      Id => 5951,
                      value=> Canvas,
                     ),
              [3] => array(
                      Id => 5952,
                      value=> Grey,
                     )
       );
</code>```

Question:

Above code are using Jquery to loop the data and store into array, I'm trying to create loop to create the result format the I want, but I failed to do that,anyone can provide me some sample code or idea which is can using Jquery to create the results format that I provided.Thank you.

答:
Make one array and push objects onto it:</p>

```<code>var ary = [];
$('.attname1').each(function(index) {
    var getval = $('.getval' + index);
    if (getval.val()) {
        ary.push({
            id: getval.attr('id'),
            value: getval.val()
        });
    }
});
</code>```

Title: Multidimensional array in jquery

Body:
My Jquery code

      var attrid        = [];
      var attrvalue     = [];

      $.each($(".attname1"), function(index){

       if($('.getval'+index+'').val() != undefined){

          attrid.push($('.getval'+index+'').attr("id"));
          attrvalue.push($('.getval'+index+'').val());
        }

     });

    //outcome data
    ["5931", "5950", "5951", "5952"]  //id

    ["cas", "bsd", "Canvas", "Grey"] //name

The result format that I actually want:

$ary = array (
              [0] => array(
                      Id => 5931,
                      value=> cas,
                     ),
              [1] => array(
                      Id => 5950,
                      value=> bsd,
                     ),
              [2] => array(
                      Id => 5951,
                      value=> Canvas,
                     ),
              [3] => array(
                      Id => 5952,
                      value=> Grey,
                     )
       );

Question:

Above code are using Jquery to loop the data and store into array, I'm trying to create loop to create the result format the I want, but I failed to do that,anyone can provide me some sample code or idea which is can using Jquery to create the results format that I provided.Thank you.

Body:
Make one array and push objects onto it:

var ary = [];
$('.attname1').each(function(index) {
    var getval = $('.getval' + index);
    if (getval.val()) {
        ary.push({
            id: getval.attr('id'),
            value: getval.val()
        });
    }
});