问:
Newbie stuck on a jQuery question...conditional statement
So I'm a complete newbie and stuck on a conditional statement.  Here's my code:

```<code><script type="text/javascript">
$(document).ready(function(){
 if($('span.fc_cart_item_price_total') == 0) {
  $(span.fc_info).addClass('foo');
 };
});
</script>
</code>```

So I'm attempting to see if span with a class of "fc_cart_item_price_total" has a value of "0", to then add a class of "foo" to the span with a class of ".fc_info".  This code above is not working.  Here's the HTML:

```<code><span class="fc_info">Info 1</span><br />
<span class="fc_cart_item_price_total">$0.00</span><br />
<span class="fc_info">Info 2</span>
</code>```

Here's the other challenge I have.  I'm trying to select the span with the value of "fc_info" before the span with the class of "fc_cart_item_price_total" but have no idea of how to just select this one span.

答:
To make the above code working

```<code><script type="text/javascript">
$(document).ready(function(){
 if($('span.fc_cart_item_price_total').html() == 0) {
  $(span.fc_info:first).addClass('foo');
 };
});
</script>
</code>```

And to select the first class fc_info

Use $(".fc_info:first") as your selector

Body:
So I'm a complete newbie and stuck on a conditional statement.  Here's my code:

So I'm attempting to see if span with a class of "fc_cart_item_price_total" has a value of "0", to then add a class of "foo" to the span with a class of ".fc_info".  This code above is not working.  Here's the HTML:

Info 1

$0.00

Info 2

Here's the other challenge I have.  I'm trying to select the span with the value of "fc_info" before the span with the class of "fc_cart_item_price_total" but have no idea of how to just select this one span.

Body:
To make the above code working

<script type="text/javascript">
$(document).ready(function(){
 if($('span.fc_cart_item_price_total').html() == 0) {
  $(span.fc_info:first).addClass('foo');
 };
});
</script>

And to select the first class fc_info

Use $(".fc_info:first") as your selector


来源: stackexchange

问:
Create new column in Spark DataFrame with diff of previous values from another column
I have a data frame which has a column with epoch seconds.

In addition to this I would like to add a column which contains the difference between current and previous time value - in other words time diff since last row in the data frame based on the timestamp column.

How would I add such a column based on earlier values?

I am using the Scala API.

答: I do not know Scala. But how about generating a lagged column with lag and then subtracting one column from the other?</p>

ContentLicense: CC BY-SA 3.0


问:
ContextMenu Hyperlink in RadRichTextBox WPF
When i add a Physical path in a Hyperlink from ContextMenu of RadRichTextBox i see http:// getting added extra but in only in one scenario.

I tried adding the link like below(The folder name has no spaces at the last),

the above gives me correct URL.

When i add the link with a folder which as spaces at the last like,

I get the output like below when i edit the Hyperlink and see,

//XAML

```<code>     <telerik:RadRichTextBox x:Name="ss" Grid.Column="0" Grid.Row="1" telerik:StyleManager.Theme="Windows8" AcceptsReturn="True" VerticalScrollBarVisibility="Auto" FontWeight="Normal" AcceptsTab="True" telerik:HtmlDataProvider.Source="{Binding Notes, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" IsSpellCheckingEnabled="True"  HyperlinkClicked="ritFnBNotes_HyperlinkClicked"   DocumentInheritsDefaultStyleSettings="True" Height="150" CommandExecuting="ritNotes_CommandExecuting" IsReadOnly="{Binding EnableForEdit, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource InverseBool}}" DocumentContentChanged="Notes_DocumentContentChanged">
     <telerik:RadRichTextBox.SelectionMiniToolBar >                                                     <telerik:SelectionMiniToolBar telerik:StyleManager.Theme="Windows8" />
     </telerik:RadRichTextBox.SelectionMiniToolBar>                                                <telerik:RadRichTextBox.Document>
         <telerik:RadDocument>
      <telerik:Section>
      <telerik:Paragraph FontSize="8" LineSpacing="0" LineSpacingType="Exact"></telerik:Paragraph>
     </telerik:Section>
      </telerik:RadDocument>
 </telerik:RadRichTextBox.Document>
     <i:Interaction.Triggers>
     <i:EventTrigger EventName="DocumentContentChanged">
     <i:InvokeCommandAction Command="{Binding FnBNoteChangeCommand, Mode=OneWay}"/>
      </i:EventTrigger>
     </i:Interaction.Triggers>
     </telerik:RadRichTextBox>
</code>```

I'm not sure how does the http:// append into the URL where i upload a physical path. Now i need to get rid of the http://.

Someone help me with this.

答:
I am afraid this is a known issue with RadInsertHyperlinkDialog. When the URL doesn't match a regular expression, an "http://" is added to the string.

As suggested by the official Telerik support, you could create a custom dialog to work around this behaviour. Please refer to the following link for more information: http://www.telerik.com/forums/radrichtextbox-hyperlink-dialog-issue

Body:
When i add a Physical path in a Hyperlink from ContextMenu of RadRichTextBox i see http:// getting added extra but in only in one scenario.

I tried adding the link like below(The folder name has no spaces at the last),

the above gives me correct URL.

When i add the link with a folder which as spaces at the last like,

I get the output like below when i edit the Hyperlink and see,

//XAML

     <telerik:RadRichTextBox x:Name="ss" Grid.Column="0" Grid.Row="1" telerik:StyleManager.Theme="Windows8" AcceptsReturn="True" VerticalScrollBarVisibility="Auto" FontWeight="Normal" AcceptsTab="True" telerik:HtmlDataProvider.Source="{Binding Notes, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" IsSpellCheckingEnabled="True"  HyperlinkClicked="ritFnBNotes_HyperlinkClicked"   DocumentInheritsDefaultStyleSettings="True" Height="150" CommandExecuting="ritNotes_CommandExecuting" IsReadOnly="{Binding EnableForEdit, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource InverseBool}}" DocumentContentChanged="Notes_DocumentContentChanged">
     <telerik:RadRichTextBox.SelectionMiniToolBar >                                                     <telerik:SelectionMiniToolBar telerik:StyleManager.Theme="Windows8" />
     </telerik:RadRichTextBox.SelectionMiniToolBar>                                                <telerik:RadRichTextBox.Document>
         <telerik:RadDocument>
      <telerik:Section>
      <telerik:Paragraph FontSize="8" LineSpacing="0" LineSpacingType="Exact"></telerik:Paragraph>
     </telerik:Section>
      </telerik:RadDocument>
 </telerik:RadRichTextBox.Document>

     </telerik:RadRichTextBox>

I'm not sure how does the http:// append into the URL where i upload a physical path. Now i need to get rid of the http://.

Someone help me with this.


问:
How to make subprocess be called after another command in Python?
I want to write Python script. I am somekind new to it. In that script I want to run another C program, which gives many numbers in output. Smth like:

```<code>1   1   0.000000    0.000172    0.075010    0.937330    33.743876
</code>```

I want to run this program multiple times with other parameters and to collect all outputs in one file. After that I plan to use pandas to sort data and make some plots, but it is not important now. I wrote the following code:

```<code>import subprocess

f = open("ax-rrff.dat", "w")
f.write("seed\tN\tT\tDRA\tD\tActive\tAvF\n")

p = subprocess.call(['gcc', 'ax-rrff.c', '-lm','-lgsl','-lgslcblas'])

for seed in range(1,2+1):
    for N in range(1,2+1):
        p = subprocess.call(['a.exe',str(seed),'1',str(N),'1000','0','0'], stdout=f)

f.close()
</code>```

(small numbers just to show you). I expect my ax-rrff.dat to be

```<code>seed    N   T   DRA D   Active  AvF
1   1   0.000000    0.000172    0.075010    0.937330    33.743876
1   2   0.000000    0.003598    0.021690    1.564677    14.032332
2   1   0.000000    0.000172    0.062262    0.925817    33.329404
2   2   0.000000    0.002790    0.014749    1.423670    16.689964
</code>```

However, scheduler of compiler thinks that it would be cool to make output in this way:

```<code>1   1   0.000000    0.000172    0.075010    0.937330    33.743876
1   2   0.000000    0.003598    0.021690    1.564677    14.032332
2   1   0.000000    0.000172    0.062262    0.925817    33.329404
2   2   0.000000    0.002790    0.014749    1.423670    16.689964
seed    N   T   DRA D   Active  AvF
</code>```

The question. How can I force sub-processes to run after  f.write("seed\tN\tT\tDRA\tD\tActive\tAvF\n")?

答: The issue is that write() places output in a buffer and only periodically flushes the buffer to disk. Since you have multiple processes writing to the file, they can potentially each flush their own buffer before the parent process does. To force the output, just call f.flsuh() before starting any subprocesses.

Body:
I want to write Python script. I am somekind new to it. In that script I want to run another C program, which gives many numbers in output. Smth like:

1   1   0.000000    0.000172    0.075010    0.937330    33.743876

I want to run this program multiple times with other parameters and to collect all outputs in one file. After that I plan to use pandas to sort data and make some plots, but it is not important now. I wrote the following code:

import subprocess

f = open("ax-rrff.dat", "w")
f.write("seed\tN\tT\tDRA\tD\tActive\tAvF\n")

p = subprocess.call(['gcc', 'ax-rrff.c', '-lm','-lgsl','-lgslcblas'])

for seed in range(1,2+1):
    for N in range(1,2+1):
        p = subprocess.call(['a.exe',str(seed),'1',str(N),'1000','0','0'], stdout=f)

f.close()

(small numbers just to show you). I expect my ax-rrff.dat to be

seed    N   T   DRA D   Active  AvF
1   1   0.000000    0.000172    0.075010    0.937330    33.743876
1   2   0.000000    0.003598    0.021690    1.564677    14.032332
2   1   0.000000    0.000172    0.062262    0.925817    33.329404
2   2   0.000000    0.002790    0.014749    1.423670    16.689964

However, scheduler of compiler thinks that it would be cool to make output in this way:

1   1   0.000000    0.000172    0.075010    0.937330    33.743876
1   2   0.000000    0.003598    0.021690    1.564677    14.032332
2   1   0.000000    0.000172    0.062262    0.925817    33.329404
2   2   0.000000    0.002790    0.014749    1.423670    16.689964
seed    N   T   DRA D   Active  AvF

The question. How can I force sub-processes to run after  f.write("seed\tN\tT\tDRA\tD\tActive\tAvF\n")?


问:
How to change UIButton image in Swift
I am trying to change the image of a UIButton using Swift...
What should I do

This is OBJ-C code.but I don't know with Swift:

```<code>[playButton setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
</code>```

答:
Yes, even we can change image of UIButton, by using flag.

```<code>class ViewController: UIViewController
{
    @IBOutlet var btnImage: UIButton!
    var flag = false

    override func viewDidLoad()
    {
        super.viewDidLoad()

        //setting default image for button
        setButtonImage()

    }

    @IBAction func btnClick(_ sender: Any)
    {
        flag = !flag
        setButtonImage()
    }

    func setButtonImage(){
        let imgName = flag ? "share" : "image"
        let image1 = UIImage(named: "\(imgName).png")!
        self.btnImage.setImage(image1, for: .normal)
    }

}
</code>```

Here, after every click your button image will change alternatively.

Title: How to change UIButton image in Swift

Body:
I am trying to change the image of a UIButton using Swift...
What should I do

This is OBJ-C code.but I don't know with Swift:

[playButton setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];

Body:
Yes, even we can change image of UIButton, by using flag.

class ViewController: UIViewController
{
    @IBOutlet var btnImage: UIButton!
    var flag = false

    override func viewDidLoad()
    {
        super.viewDidLoad()

        //setting default image for button
        setButtonImage()

    }

    @IBAction func btnClick(_ sender: Any)
    {
        flag = !flag
        setButtonImage()
    }

    func setButtonImage(){
        let imgName = flag ? "share" : "image"
        let image1 = UIImage(named: "\(imgName).png")!
        self.btnImage.setImage(image1, for: .normal)
    }

}

Here, after every click your button image will change alternatively.


问:
Firebase Structuring Complex List Data Without Creating Multiple Nodes
I have following 2 ways to construct data. Want to know which is correct way as in each of the case I'm coming across different limitations.

Case 1 : Nested Objects - Here single object is pushed maintaining all records related to recipient. All data related to recipient can be fetched in single "Query" can be passed to Firebase-Ui (FirebaseRecyclerAdapter)

Problem: Adding data to "servicesArrayList". Because it's index based (0,1,2,...). New push would add pushId (-KgJoRXVUP_-Z0gLhIWy). Breaks structure(refer code below). Now crashes while retrieving data. (Problem while deserializing data as structure is expecting ArrayList)

```<code>@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
    Recipient recipient = dataSnapshot.getValue(Recipient.class);
}
</code>```

Question: Is there way to maintain index on new push  or while first push itself it can be structured in some different way ?

```<code>FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String uid = user.getUid();

Query query = FirebaseDatabase.getInstance()
            .getReference(RECIPIENT_NODE)
            .child(uid)
            .orderByChild("billNo")
            .equalTo(135);

recipient // parent Node

   2R1Q8qKEPHXFU1OiMq5TyxHBaZa2 // uId

     -KgJhMAWADwownv5tck6  // push Ids
     -KgJhMAWADwownv5tck6
     -KgJoD77HQK-yACD_EuB
     -KgJoRXVUP_-Z0gLhIWy
     -KgJob82t47PvTjfTtig
     -KgK-N_Av_2kmmQS0Ulx

     -KgNu-fVWwFDLnRENj_b // Recipient Data
          billNo: 135
          billingMonth: "July 2017"
          childName: "xyz"
          date: "29/03/2017"
          fineAmount: 0
          paymentStatus: "UNPAID"
          pushId: "-KgNu-fVWwFDLnRENj_b"
          recipientEmail: "abc@gmail.com"
          recipientName: "Abc C."
          servicesArrayList
                       -0                 //added when recipient object was pushed
                          -amount: 1000
                          -charges: "1000"
                          -noOfSessions: 1
                          -serviceType: "Speech And Language Assessment"
                      -1                  //added when recipient object was pushed
                          -amount: 1200
                          -charges: "600"
                          -noOfSessions: 2
                          -serviceType: "Group Sessions"

                      -KgJoRXVUP_-Z0gLhIWy // added as an update to exsiting list (errrr ! now structure is breaking.)
                          -amount: 1200
                          -charges: "600"
                          -noOfSessions: 2
                          -serviceType: "Group Sessions"

          vat: 0
</code>```

Case 2: Maintain 2 different structures for Recipient and Services.

Problem: Have to fire 2 different "Queries". Merge 2 datas separately and then pass it to normal adapter (can't use Firebase-ui). Monitor using ChildListener / ValueeventListener.
Mapping using FOREIGN KEY and more tedious.

Question: Is there a way to use a single query to get data from both nodes ?

So I need an answer to Question 1 and Question 2 and need to understand which is the correct way ?

答:
Firebase recommends avoiding nesting data (Case 1) and instead flatten the data structure (Case 2). You can read more in Structuring your Firebase data

Quoting Firebase itself 'This is a necessary redundancy for two-way relationships. It allows you to quickly and efficiently fetch memberships, even when the list of users or groups scales into the millions or when Realtime Database security rules prevent access to some of the records.

This approach, inverting the data by listing the IDs as keys and setting the value to true, makes checking for a key as simple as reading /users/$uid/groups/$group_id and checking if it is null. The index is faster and a good deal more efficient than querying or scanning the data'.

So, I guess Case 2 is the way to go.

ContentLicense: CC BY-SA 4.0

Body:
I have following 2 ways to construct data. Want to know which is correct way as in each of the case I'm coming across different limitations.

Case 1 : Nested Objects - Here single object is pushed maintaining all records related to recipient. All data related to recipient can be fetched in single "Query" can be passed to Firebase-Ui (FirebaseRecyclerAdapter)

Problem: Adding data to "servicesArrayList". Because it's index based (0,1,2,...). New push would add pushId (-KgJoRXVUP_-Z0gLhIWy). Breaks structure(refer code below). Now crashes while retrieving data. (Problem while deserializing data as structure is expecting ArrayList)

@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
    Recipient recipient = dataSnapshot.getValue(Recipient.class);
}

Question: Is there way to maintain index on new push  or while first push itself it can be structured in some different way ?

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String uid = user.getUid();

Query query = FirebaseDatabase.getInstance()
            .getReference(RECIPIENT_NODE)
            .child(uid)
            .orderByChild("billNo")
            .equalTo(135);

recipient // parent Node

   2R1Q8qKEPHXFU1OiMq5TyxHBaZa2 // uId

     -KgJhMAWADwownv5tck6  // push Ids
     -KgJhMAWADwownv5tck6
     -KgJoD77HQK-yACD_EuB
     -KgJoRXVUP_-Z0gLhIWy
     -KgJob82t47PvTjfTtig
     -KgK-N_Av_2kmmQS0Ulx

     -KgNu-fVWwFDLnRENj_b // Recipient Data
          billNo: 135
          billingMonth: "July 2017"
          childName: "xyz"
          date: "29/03/2017"
          fineAmount: 0
          paymentStatus: "UNPAID"
          pushId: "-KgNu-fVWwFDLnRENj_b"
          recipientEmail: "abc@gmail.com"
          recipientName: "Abc C."
          servicesArrayList
                       -0                 //added when recipient object was pushed
                          -amount: 1000
                          -charges: "1000"
                          -noOfSessions: 1
                          -serviceType: "Speech And Language Assessment"
                      -1                  //added when recipient object was pushed
                          -amount: 1200
                          -charges: "600"
                          -noOfSessions: 2
                          -serviceType: "Group Sessions"

                      -KgJoRXVUP_-Z0gLhIWy // added as an update to exsiting list (errrr ! now structure is breaking.)
                          -amount: 1200
                          -charges: "600"
                          -noOfSessions: 2
                          -serviceType: "Group Sessions"

          vat: 0

Case 2: Maintain 2 different structures for Recipient and Services.

Problem: Have to fire 2 different "Queries". Merge 2 datas separately and then pass it to normal adapter (can't use Firebase-ui). Monitor using ChildListener / ValueeventListener.
Mapping using FOREIGN KEY and more tedious.

Question: Is there a way to use a single query to get data from both nodes ?

So I need an answer to Question 1 and Question 2 and need to understand which is the correct way ?


问:
importing google.cloud.datastore not working
I am working in pycharm(in windows) environment.

I am building a website to send query to datastore and display values. I also have data under kind="SpecialTest" that is automatically saved through Node.js. Now I wanted to Query the data from Python.

I installed google-cloud-datastore from command line.

But I can't establish connection to datastore.

My code:

```<code>from google.cloud import datastore
cli=datastore.Client(project="My_project_I")
query4= cli.query(kind="SpecialTest").order('Published_at')
print query4
</code>```

My result:

```<code>Internal Server Error

The server has either erred or is incapable of performing the requested operation.

Traceback (most recent call last):
  File "C:\Program Files\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1535, in __call__
    rv = self.handle_exception(request, response, e)
  File "C:\Program Files\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1529, in __call__
    rv = self.router.dispatch(request, response)
  File "C:\Program Files\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1272, in default_dispatcher
    self.handlers[handler] = handler = import_string(handler)
  File "C:\Program Files\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1850, in import_string
    return getattr(__import__(module, None, None, [obj]), obj)
  File "C:\Users\Harry\workspace\www\app\account.py", line 11, in <module>
    from google.cloud import datastore
  File "C:\Python27\lib\site-packages\google\cloud\datastore\__init__.py", line 60, in <module>
    from google.cloud.datastore.batch import Batch
  File "C:\Python27\lib\site-packages\google\cloud\datastore\batch.py", line 24, in <module>
    from google.cloud.datastore import helpers
  File "C:\Python27\lib\site-packages\google\cloud\datastore\helpers.py", line 23, in <module>
    from google.protobuf import struct_pb2
ImportStringError: import_string() failed for 'app.account.UserAccount'. Possible reasons are:

- missing __init__.py in a package;
- package or module path not included in sys.path;
- duplicated package or module name taking precedence in sys.path;
- missing module, class, function or variable;

Original exception:

ImportError: No module named protobuf

Debugged import:

- 'app' found in 'C:\\Users\\Harry\\workspace\\www\\app\\__init__.pyc'.
- 'app.account' not found.
</code>```

答:
The datastore client library is not supplied by GAE, you need to install/vendor it into your application (different method than for a standalone script).

Alternatively you can use the GAE-specific datastore library - it's actually recommended as it offers some advantages over the general purpose one. From Google App Engine Standard Environment Client Libraries:

Integrate Cloud Datastore with your App Engine Standard Environment
  applications by using the App Engine client libraries.

...

Python    Google Datastore NDB Client Library

Note: For App Engine applications that are written in Python, the Google Datastore DB Client Library is no longer recommended; use the
  Google Datastore NDB Client Library instead.

Body:
I am working in pycharm(in windows) environment.

I am building a website to send query to datastore and display values. I also have data under kind="SpecialTest" that is automatically saved through Node.js. Now I wanted to Query the data from Python.

I installed google-cloud-datastore from command line.

But I can't establish connection to datastore.

My code:

from google.cloud import datastore
cli=datastore.Client(project="My_project_I")
query4= cli.query(kind="SpecialTest").order('Published_at')
print query4

My result:

Internal Server Error

The server has either erred or is incapable of performing the requested operation.

Traceback (most recent call last):
  File "C:\Program Files\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1535, in __call__
    rv = self.handle_exception(request, response, e)
  File "C:\Program Files\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1529, in __call__
    rv = self.router.dispatch(request, response)
  File "C:\Program Files\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1272, in default_dispatcher
    self.handlers[handler] = handler = import_string(handler)
  File "C:\Program Files\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1850, in import_string
    return getattr(__import__(module, None, None, [obj]), obj)
  File "C:\Users\Harry\workspace\www\app\account.py", line 11, in <module>
    from google.cloud import datastore
  File "C:\Python27\lib\site-packages\google\cloud\datastore\__init__.py", line 60, in <module>
    from google.cloud.datastore.batch import Batch
  File "C:\Python27\lib\site-packages\google\cloud\datastore\batch.py", line 24, in <module>
    from google.cloud.datastore import helpers
  File "C:\Python27\lib\site-packages\google\cloud\datastore\helpers.py", line 23, in <module>
    from google.protobuf import struct_pb2
ImportStringError: import_string() failed for 'app.account.UserAccount'. Possible reasons are:

- missing __init__.py in a package;
- package or module path not included in sys.path;
- duplicated package or module name taking precedence in sys.path;
- missing module, class, function or variable;

Original exception:

ImportError: No module named protobuf

Debugged import:

- 'app' found in 'C:\\Users\\Harry\\workspace\\www\\app\\__init__.pyc'.
- 'app.account' not found.


问:
Java concurrent access of ArrayList
After the following code

```<code>ArrayList<String> foo, bar, test;
foo = new ArrayList<String>(Arrays.asList("foo"));
bar = new ArrayList<String>(Arrays.asList("bar"));
test = new ArrayList<String>(Arrays.asList("test"));
</code>```

Thread 1 runs:

```<code>foo = new ArrayList<String>(bar);
</code>```

Thread 2 runs:

```<code>bar = new ArrayList<String>(test);
</code>```

Can this cause an exception if Thread 2 changes value of bar while it is being used by Thread 1?

答:
It is not a problem at all. To understand what happens you need to know how java handles such structures as ArrayList (and other collections).

When you create a new ArrayList variable, the variable contains only the link to the segment of RAM where the real data is kept. When you pass the variable to a constructor or another method, java copies  the value of the variable, and the parameter is initialized with this value. So when you assign a new list to the parameter, you don't change the value of the original variable:

```<code>public class Main {

    public static void main(String [] args) throws IOException {
        List<String> foo, bar, test;
        foo = new ArrayList<String>(Arrays.asList("foo"));
        bar = new ArrayList<String>(Arrays.asList("bar"));
        test = new ArrayList<String>(Arrays.asList("test"));

        CountDownLatch cdl = new CountDownLatch(1);

        Thread r1 = new Thread(new MyThread("foo = new ArrayList(bar)", bar, foo, cdl));
        Thread r2 = new Thread(new MyThread("bar = new ArrayList(test)", test, bar, cdl));
        r1.start();
        r2.start();

        cdl.countDown();
        System.out.println("Size of foo is " + foo.size());
        System.out.println("Size of bar is " + foo.size());
    }
}

class MyThread implements Runnable {

    private List<String> src;
    private List<String> dst;
    private CountDownLatch cdl;
    private String msg;

    public MyThread(String msg, List<String> src, List<String> dst, CountDownLatch cdl) {
        this.msg = msg;
        this.src = src;
        this.dst = dst;
        this.cdl = cdl;
    }

    @Override
    public void run() {
        try {
            cdl.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        dst = new ArrayList<String>(src);
        dst.add("test");
        System.out.println(msg + " and my size is " + dst.size());
    }

}
</code>```

Output:

```<code>bar = new ArrayList(test) and my size is 2
foo = new ArrayList(bar) and my size is 2
Size of foo is 1
Size of bar is 1
</code>```

Title: Java concurrent access of ArrayList

Body:
After the following code

ArrayList<String> foo, bar, test;
foo = new ArrayList<String>(Arrays.asList("foo"));
bar = new ArrayList<String>(Arrays.asList("bar"));
test = new ArrayList<String>(Arrays.asList("test"));

Thread 1 runs:

foo = new ArrayList<String>(bar);

Thread 2 runs:

bar = new ArrayList<String>(test);

Can this cause an exception if Thread 2 changes value of bar while it is being used by Thread 1?

Body:
It is not a problem at all. To understand what happens you need to know how java handles such structures as ArrayList (and other collections).

When you create a new ArrayList variable, the variable contains only the link to the segment of RAM where the real data is kept. When you pass the variable to a constructor or another method, java copies  the value of the variable, and the parameter is initialized with this value. So when you assign a new list to the parameter, you don't change the value of the original variable:

public class Main {

    public static void main(String [] args) throws IOException {
        List<String> foo, bar, test;
        foo = new ArrayList<String>(Arrays.asList("foo"));
        bar = new ArrayList<String>(Arrays.asList("bar"));
        test = new ArrayList<String>(Arrays.asList("test"));

        CountDownLatch cdl = new CountDownLatch(1);

        Thread r1 = new Thread(new MyThread("foo = new ArrayList(bar)", bar, foo, cdl));
        Thread r2 = new Thread(new MyThread("bar = new ArrayList(test)", test, bar, cdl));
        r1.start();
        r2.start();

        cdl.countDown();
        System.out.println("Size of foo is " + foo.size());
        System.out.println("Size of bar is " + foo.size());
    }
}

class MyThread implements Runnable {

    private List<String> src;
    private List<String> dst;
    private CountDownLatch cdl;
    private String msg;

    public MyThread(String msg, List<String> src, List<String> dst, CountDownLatch cdl) {
        this.msg = msg;
        this.src = src;
        this.dst = dst;
        this.cdl = cdl;
    }

    @Override
    public void run() {
        try {
            cdl.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        dst = new ArrayList<String>(src);
        dst.add("test");
        System.out.println(msg + " and my size is " + dst.size());
    }

}

Output:

bar = new ArrayList(test) and my size is 2
foo = new ArrayList(bar) and my size is 2
Size of foo is 1
Size of bar is 1


问:
C# How to convert specific lower-case letters to uppercase and uppercase letters to lowercase at the same time
I want to exchange all occurences of a character in a string with their case-counterpart.

For example:

"%Y %m %d | %H:%M:%S"

should become

"%Y %M %d | %H:%m:%S"

for the character 'm' or 'M'.

How can I best do this in C# ?

答:
For ASCII letters, the 6ᵗʰ bit can be used to switch between upper and lower case:</p>

```<code>var s = "%Y %m %d | %H:%M:%S";
s = string.Concat(s.Select(c => (c | 32) == 'm' ? (char)(c ^ 32) : c));
</code>```

Body:
For ASCII letters, the 6ᵗʰ bit can be used to switch between upper and lower case:

var s = "%Y %m %d | %H:%M:%S";
s = string.Concat(s.Select(c => (c | 32) == 'm' ? (char)(c ^ 32) : c));


问:
DB2 rownum equivalent
I have the below query in Oracle which I want to replicate in DB2 which uses the random function and the rownum.

Oracle Query :

```<code>SELECT *
FROM  (
   SELECT *
   FROM db2admin.QUESTION_BANK
   WHERE type='PROCESS'
   ORDER BY dbms_random.value
) WHERE rownum <=?
</code>```

I got alternate for random function but nothing for rownum. Below is query in DB2,

```<code>SELECT *
FROM  (
  SELECT *
  FROM db2admin.QUESTION_BANK
  WHERE type='PROCESS' ORDER BY RAND
) WHERE rownum <= ?
</code>```

The value for rownum is passed via PreparedStatement.

答:
DB2 has ROWNUM when you work in the Oracle compatibility mode. To enable just this feature, use this:

```<code>db2set DB2_COMPATIBILITY_VECTOR=01
db2stop
db2start
</code>```

To get all the Oracle features, enable it like this:

```<code>db2set DB2_COMPATIBILITY_VECTOR=ORA
db2stop
db2start
</code>```

The doc on the DB2_COMPATIBILITY_VECTOR has details on alternatives like
ROW_NUMBER() OVER().

Title: DB2 rownum equivalent

Body:
I have the below query in Oracle which I want to replicate in DB2 which uses the random function and the rownum.

Oracle Query :

SELECT *
FROM  (
   SELECT *
   FROM db2admin.QUESTION_BANK
   WHERE type='PROCESS'
   ORDER BY dbms_random.value
) WHERE rownum <=?

I got alternate for random function but nothing for rownum. Below is query in DB2,

SELECT *
FROM  (
  SELECT *
  FROM db2admin.QUESTION_BANK
  WHERE type='PROCESS' ORDER BY RAND
) WHERE rownum <= ?

The value for rownum is passed via PreparedStatement.

Body:
DB2 has ROWNUM when you work in the Oracle compatibility mode. To enable just this feature, use this:

db2set DB2_COMPATIBILITY_VECTOR=01
db2stop
db2start

To get all the Oracle features, enable it like this:

db2set DB2_COMPATIBILITY_VECTOR=ORA
db2stop
db2start

The doc on the DB2_COMPATIBILITY_VECTOR has details on alternatives like
ROW_NUMBER() OVER().


问:
How to delete images in Media Library without deleting the file in server in wordpress
I have used  a plugin https://wordpress.org/plugins/best-import/ in oder to import all images from server into my wordpress media lirabry. Unfortunately, I had mistakenly uploaded many necessary files.

Now, want to delete these files from MEDIA without deleting those in server.

答:
In your admin panel go to media, you will render all your files. Then click bulk select, select all the files you wish to delete, then click delete selected. This will just delete it off your site.
A good plugin for this is Product CSV importer (You can download just products or all files)</p>


问:
Using multiple Leaves in Lucene Classifiers
I am trying to use the KNearestNeighbour classifier in lucene. The document classifier accepts a leafReader in its constructor, for training the classifier.
The problem is that, the Index I am using to train the classifier has multiple leaves. But the constructor for the class only accepts one leaf, and I could not find a process to add the remaining LeafReaders to the Class. I might be missing out on something. Could anyone help please me out with this?

Here is the code I am using currently :

```<code>    FSDirectory index = FSDirectory.open(Paths.get(indexLoc));
    IndexReader reader = DirectoryReader.open(index);
    LeafReaderContext leaf = leaves.get(0);
    LeafReader atomicReader = leaf.reader();
    KNearestNeighborDocumentClassifier knn = new KNearestNeighborDocumentClassifier(atomicReader, BM25, null, 10, 0, 0, "Topics", field2analyzer, "Text");
</code>```

答:
Leaves represent each segment of you index. In terms of performance and resource usage, you should iterate over the leaves, run the classification for each segment and accumulate your results.

```<code>for (LeafReaderContext context : indexReader.getContext().leaves()) {
  LeafReader reader = context.reader();
  // run for each leaf
}
</code>```

If that is not possible, you can use the SlowCompositeReaderWrapper which, as the name suggests, might be very slow as it aggregates all the leaves on the fly.

```<code>LeafReader singleLeaf = SlowCompositeReaderWrapper.wrap(indexReader);
// run classifier on singleLeaf
</code>```

Depending on your Lucene version, this sits in lucene-core or lucene-misc (since Lucene 6.0, I think). Also, this class is deprecated and scheduled for removal in Lucene 7.0.

The third option might be to run forceMerge(1) until you only have one segment and you can use the single leaf for this. However, forcing a merge down to a single segment has other issues and might not work for your use case. If you data is write-once and then only used for reading, you could use a forceMerge. If you have regular updates, you'll have to end up using the first option and aggregate the classification result yourself.

Body:
I am trying to use the KNearestNeighbour classifier in lucene. The document classifier accepts a leafReader in its constructor, for training the classifier.
The problem is that, the Index I am using to train the classifier has multiple leaves. But the constructor for the class only accepts one leaf, and I could not find a process to add the remaining LeafReaders to the Class. I might be missing out on something. Could anyone help please me out with this?

Here is the code I am using currently :

    FSDirectory index = FSDirectory.open(Paths.get(indexLoc));
    IndexReader reader = DirectoryReader.open(index);
    LeafReaderContext leaf = leaves.get(0);
    LeafReader atomicReader = leaf.reader();
    KNearestNeighborDocumentClassifier knn = new KNearestNeighborDocumentClassifier(atomicReader, BM25, null, 10, 0, 0, "Topics", field2analyzer, "Text");

Body:
Leaves represent each segment of you index. In terms of performance and resource usage, you should iterate over the leaves, run the classification for each segment and accumulate your results.

for (LeafReaderContext context : indexReader.getContext().leaves()) {
  LeafReader reader = context.reader();
  // run for each leaf
}

If that is not possible, you can use the SlowCompositeReaderWrapper which, as the name suggests, might be very slow as it aggregates all the leaves on the fly.

LeafReader singleLeaf = SlowCompositeReaderWrapper.wrap(indexReader);
// run classifier on singleLeaf

Depending on your Lucene version, this sits in lucene-core or lucene-misc (since Lucene 6.0, I think). Also, this class is deprecated and scheduled for removal in Lucene 7.0.

The third option might be to run forceMerge(1) until you only have one segment and you can use the single leaf for this. However, forcing a merge down to a single segment has other issues and might not work for your use case. If you data is write-once and then only used for reading, you could use a forceMerge. If you have regular updates, you'll have to end up using the first option and aggregate the classification result yourself.


问:
what is the bootstrapped data in data mining?
recently I came across this term,but really have no idea what it refers to.I've searched online,but with little gain.
Thanks.</p>

答:
Take a sample of the time of day that you wake up on Saturdays. Some Friday nights you have a few too many drinks, so you wake up early (but go back to bed). Other days you wake up at a normal time. Other days you sleep in.

Here are the results:

[3.1, 4.8, 6.3, 6.4, 6.6, 7.3, 7.5, 7.7, 7.9, 10.1]

What is the mean time that you wake up?

Well it's 6.8 (o'clock, or 6:48). A touch early for me.

How good a prediction is this of when you'll wake up next Saturday? Can you quantify how wrong you are likely to be?

It's a pretty small sample, and we're not sure of the distribution of the underlying process, so it might not be a good idea to use standard parametric statistical techniques†.

Why don't we take a random sample of our sample, and calculate the mean and repeat this? This will give us an estimate of how bad our estimate is.

I did this several times, and the mean was between 5.98 and 7.8

This is called the bootstrap, and it was first mentioned by Bradley Efron in 1979.

A variant is called the jackknife, where you sample all but one of your dataset, take the mean, and repeat. The jackknife mean is 6.8 (same as the arithmetic mean) and ranges from 6.4 to 7.2.

Another variant is called k-fold cross-validation, where you (at random) split your data set into k equally-sized sections, calculate the mean of all but one section, and repeat k times. The 5-fold cross-validation mean is 6.8 and ranges from 4 to 9.

† This distribution does happen to be Normal. The 95% confidence interval of the mean is 5.43 to 8.11, reasonably close but bigger than the bootstrap mean.

ContentLicense: CC BY-SA 2.5


问:
How to update across two tables using a function SQL
I am trying to run an update query which is based across two tables. So i am trying to update my stock level which is a table called workshop. The value i am trying to update it is the stock level from table workshop minus the quantity ordered from an orders table. I am not even sure if this is possible. Any help on this query would be greatly appreciated. </p>

```<code> UPDATE WORKSHOP SET STOCK_LEVEL =
(WORKSHOP.STOCK_LEVEL - ORDERS.QUANTITY_ORDERED)
 FROM ORDERS WHERE WORKSHOP.STOCK_ID = ORDERS.STOCK_ID
</code>```

答:
You could use an update with join </p>

```<code> UPDATE WORKSHOP
 INNER JOIN ORDERS ON WORKSHOP.STOCK_ID = ORDERS.STOCK_ID
 SET STOCK_LEVEL =STOCK_LEVEL - ORDERS.QUANTITY_ORDERED
</code>```

Body:
I am trying to run an update query which is based across two tables. So i am trying to update my stock level which is a table called workshop. The value i am trying to update it is the stock level from table workshop minus the quantity ordered from an orders table. I am not even sure if this is possible. Any help on this query would be greatly appreciated.

 UPDATE WORKSHOP SET STOCK_LEVEL =
(WORKSHOP.STOCK_LEVEL - ORDERS.QUANTITY_ORDERED)
 FROM ORDERS WHERE WORKSHOP.STOCK_ID = ORDERS.STOCK_ID

Body:
You could use an update with join

 UPDATE WORKSHOP
 INNER JOIN ORDERS ON WORKSHOP.STOCK_ID = ORDERS.STOCK_ID
 SET STOCK_LEVEL =STOCK_LEVEL - ORDERS.QUANTITY_ORDERED


问:
Uncaught Error: Expected to find a document already present for removed
When I try to log into app, the error I get in client console (chrome dev tools) is this:

```<code>Uncaught Error: Expected to find a document already present for removed mongo.js?69942a86515ec397dfd8cbb0a151a0eefdd9560d:253
</code>```

and the login is halted: the loading gif from the accounts-google package shows and the loading never ends.

I however get no errors in server console. Unfortunately, the error gives me little understanding as to where to even start debugging my app from.

I have gone through the portion where the error is thrown in the mongo.js file, but I don't get what's going on there from it either.

Since I do not have any idea where I am going wrong, this is the link to the project repository.

答:
Maybe you was use fast-render package and doing 2 subscriptions for the same publication as explined here

Hope this help someone.

Body:
When I try to log into app, the error I get in client console (chrome dev tools) is this:

Uncaught Error: Expected to find a document already present for removed mongo.js?69942a86515ec397dfd8cbb0a151a0eefdd9560d:253

and the login is halted: the loading gif from the accounts-google package shows and the loading never ends.

I however get no errors in server console. Unfortunately, the error gives me little understanding as to where to even start debugging my app from.

I have gone through the portion where the error is thrown in the mongo.js file, but I don't get what's going on there from it either.

Since I do not have any idea where I am going wrong, this is the link to the project repository.


问:
Java program on "friendly numbers "
I am working on a assignment about so called "friendly-numbers" with the following definition: An integer is said to be friendly if the leftmost digit is divisible by 1, the leftmost two digits are divisible by 2, and the leftmost three digits are divisible by 3, and so on. The n-digit itself is divisible by n.

Also it was given we need to call a method (as I did or at least tried to do in the code below). It should print whether a number is friendly or not. However, my program prints "The integer is not friendly." in both cases. From what I have tried, I know the counter does work. I just cannot find what I am missing or doing wrong. Help would be appreciated, and preferably with an adaptation of the code below, since that is what I came up with myself.

```<code>import java.util.Scanner;
public class A5E4 {

    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Please enter an integer: ");
        int friendlyNumber = in.nextInt();
        boolean result = isFriendly(friendlyNumber);
        if (result)
        {
            System.out.println("The integer is friendly");
        }
        else
        {
            System.out.println("The integer is not friendly");
        }
    }
    public static boolean isFriendly(int number)
    {
        int counter = 1;

        while (number / 10 >= 1)
        {
            counter ++;
            number = number / 10;
        }

        boolean check = true;

        for (int i = 1; i <= counter; i++)
        {

            if (number / Math.pow(10, (counter - i)) % i == 0 && check)
            {
                check = true;
            }
            else
            {
                check = false;
            }

        }
        return check;

    }
}
</code>```

答:
```<code>while (number / 10 >= 1){
    counter ++;
    number = number / 10;
}
</code>```

In this bit, you are reducing number to something smaller than 10. That is probably not what you want. You should make a copy of number here.
Also, proper software design would recommend that you extract this to a dedicated method.

```<code>private int countDigits(int number){
    if(number < 1) throw new IllegalArgumentException();
    int n = number;
    int counter = 1;
    while (n / 10 >= 1){
        counter ++;
        n = n / 10;
    }
    return counter;

}
</code>```

Title: Java program on "friendly numbers "

Body:
I am working on a assignment about so called "friendly-numbers" with the following definition: An integer is said to be friendly if the leftmost digit is divisible by 1, the leftmost two digits are divisible by 2, and the leftmost three digits are divisible by 3, and so on. The n-digit itself is divisible by n.

Also it was given we need to call a method (as I did or at least tried to do in the code below). It should print whether a number is friendly or not. However, my program prints "The integer is not friendly." in both cases. From what I have tried, I know the counter does work. I just cannot find what I am missing or doing wrong. Help would be appreciated, and preferably with an adaptation of the code below, since that is what I came up with myself.

import java.util.Scanner;
public class A5E4 {

    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Please enter an integer: ");
        int friendlyNumber = in.nextInt();
        boolean result = isFriendly(friendlyNumber);
        if (result)
        {
            System.out.println("The integer is friendly");
        }
        else
        {
            System.out.println("The integer is not friendly");
        }
    }
    public static boolean isFriendly(int number)
    {
        int counter = 1;

        while (number / 10 >= 1)
        {
            counter ++;
            number = number / 10;
        }

        boolean check = true;

        for (int i = 1; i <= counter; i++)
        {

            if (number / Math.pow(10, (counter - i)) % i == 0 && check)
            {
                check = true;
            }
            else
            {
                check = false;
            }

        }
        return check;

    }
}

Body:
while (number / 10 >= 1){
    counter ++;
    number = number / 10;
}

In this bit, you are reducing number to something smaller than 10. That is probably not what you want. You should make a copy of number here.
Also, proper software design would recommend that you extract this to a dedicated method.

private int countDigits(int number){
    if(number < 1) throw new IllegalArgumentException();
    int n = number;
    int counter = 1;
    while (n / 10 >= 1){
        counter ++;
        n = n / 10;
    }
    return counter;

}


问:
Django REST overrride destroy method to make user inactive
I'm trying to first access the users table via the user foreign key present in userinformations models and later override the RetriveUpdateDestroy API view's destroy method to change the status of the user to inactive instead of deleting them. I can't seem to access the is-active field of the in built User database.

views.py

```<code>class UserUpdateApiView(RetrieveUpdateDestroyAPIView):
queryset = UserInformation.objects.all()
serializer_class = UserInformationUpdateSerializer
lookup_field = 'pk'
lookup_url_kwarg = 'id'

def destroy(self, request, *args, **kwargs):
    try:
        user = User.objects.get(pk=self.kwargs["id"])
        deleteStatusVal = False
        user.is_active = deleteStatusVal
        user.save()
        return Response(UserSerializer(user).data)
    except:
        return Response("Nope")
</code>```

serializers.py

```<code>class UserSerializer(ModelSerializer):
password = serializers.CharField(style={'input_type': 'password'}, write_only=True)
email = serializers.EmailField(validators=[required])

class Meta:
    model = User
    fields = ['username', 'email', 'password', 'is_active']
    extra_kwargs = {'password': {'write_only': True},
                    'is_active': {'read_only': True}}

def validate(self, data):
    email = data.get('email', None)
    user = User.objects.filter(email=email).distinct()
    if user.exists():
        raise ValidationError("That email is already registered!")
    return data

class UserInformationUpdateSerializer(ModelSerializer):
user = UserSerializer(read_only=True)
class Meta:
    model = UserInformation
    fields = ['user', 'first_name', 'middle_name', 'last_name', 'phone', 'date_of_birth']
</code>```

models.py

```<code>class UserInformation(BaseModel):
user = models.OneToOneField(User, related_name='user_id')
first_name = models.CharField(max_length=45)
middle_name = models.CharField(max_length=45, null=True)
last_name = models.CharField(max_length=45)
vendor = models.BooleanField(default=False)
phone = models.CharField(max_length=100, validators=[
RegexValidator(regex=r'^\+?8801?\d{9}$', message="Phone number must be entered in the format: '+8801*********'")
], blank=False, unique=True)
date_of_birth = models.DateField()
confirmation_token = models.CharField(max_length=45, null=True)
confirmation_exp = models.DateTimeField(null=True)
pw_reminder_token = models.CharField(max_length=45, null=True)
pw_reminder_exp = models.DateTimeField(null=True)
profile_pic = models.ImageField(blank=True, null=True, upload_to='profile_images/', default='Images/none/no_images.jpg')
cover_photo = models.ImageField(blank=True, null=True, upload_to='cover_images/', default='Images/none/no_images.jpg')
thumbnail_pic = models.ImageField(blank=True, null=True, upload_to='thumbnail_images/', default='Images/none/no_images.jpg')
phone_verified = models.BooleanField(default=False)
email_verified = models.BooleanField(default=False)
reward_points = models.IntegerField(null=False)
ref_code = models.CharField(null=True, max_length=10)

def __str__(self):
    return self.user.username

def delete(self, *args, **kwargs):
    self.user.delete()
    super(UserInformation, self).delete(*args, **kwargs)
</code>```

答:
You have 'is_active': {'read_only': True}}.

Also,

```<code># this seems redundant
def delete(self, *args, **kwargs):
    self.user.delete()
    super(UserInformation, self).delete(*args, **kwargs)
</code>```

Body:
I'm trying to first access the users table via the user foreign key present in userinformations models and later override the RetriveUpdateDestroy API view's destroy method to change the status of the user to inactive instead of deleting them. I can't seem to access the is-active field of the in built User database.

views.py

class UserUpdateApiView(RetrieveUpdateDestroyAPIView):
queryset = UserInformation.objects.all()
serializer_class = UserInformationUpdateSerializer
lookup_field = 'pk'
lookup_url_kwarg = 'id'

def destroy(self, request, *args, **kwargs):
    try:
        user = User.objects.get(pk=self.kwargs["id"])
        deleteStatusVal = False
        user.is_active = deleteStatusVal
        user.save()
        return Response(UserSerializer(user).data)
    except:
        return Response("Nope")

serializers.py

class UserSerializer(ModelSerializer):
password = serializers.CharField(style={'input_type': 'password'}, write_only=True)
email = serializers.EmailField(validators=[required])

class Meta:
    model = User
    fields = ['username', 'email', 'password', 'is_active']
    extra_kwargs = {'password': {'write_only': True},
                    'is_active': {'read_only': True}}

def validate(self, data):
    email = data.get('email', None)
    user = User.objects.filter(email=email).distinct()
    if user.exists():
        raise ValidationError("That email is already registered!")
    return data

class UserInformationUpdateSerializer(ModelSerializer):
user = UserSerializer(read_only=True)
class Meta:
    model = UserInformation
    fields = ['user', 'first_name', 'middle_name', 'last_name', 'phone', 'date_of_birth']

models.py

class UserInformation(BaseModel):
user = models.OneToOneField(User, related_name='user_id')
first_name = models.CharField(max_length=45)
middle_name = models.CharField(max_length=45, null=True)
last_name = models.CharField(max_length=45)
vendor = models.BooleanField(default=False)
phone = models.CharField(max_length=100, validators=[
RegexValidator(regex=r'^\+?8801?\d{9}$', message="Phone number must be entered in the format: '+8801*********'")
], blank=False, unique=True)
date_of_birth = models.DateField()
confirmation_token = models.CharField(max_length=45, null=True)
confirmation_exp = models.DateTimeField(null=True)
pw_reminder_token = models.CharField(max_length=45, null=True)
pw_reminder_exp = models.DateTimeField(null=True)
profile_pic = models.ImageField(blank=True, null=True, upload_to='profile_images/', default='Images/none/no_images.jpg')
cover_photo = models.ImageField(blank=True, null=True, upload_to='cover_images/', default='Images/none/no_images.jpg')
thumbnail_pic = models.ImageField(blank=True, null=True, upload_to='thumbnail_images/', default='Images/none/no_images.jpg')
phone_verified = models.BooleanField(default=False)
email_verified = models.BooleanField(default=False)
reward_points = models.IntegerField(null=False)
ref_code = models.CharField(null=True, max_length=10)

def __str__(self):
    return self.user.username

def delete(self, *args, **kwargs):
    self.user.delete()
    super(UserInformation, self).delete(*args, **kwargs)

Body:
You have 'is_active': {'read_only': True}}.

Also,

# this seems redundant
def delete(self, *args, **kwargs):
    self.user.delete()
    super(UserInformation, self).delete(*args, **kwargs)


答:
The correct syntax in MySQL is:

```<code>UPDATE WORKSHOP w JOIN
       ORDERS o
       ON w.STOCK_ID = o.STOCK_ID
    SET STOCK_LEVEL = (w.STOCK_LEVEL - o.QUANTITY_ORDERED);
</code>```

Presumably, ORDERS could have multiple rows for a given STOCK_ID.  If so, you need to pre-aggregate to reduce the quantity for all of them:

```<code>UPDATE WORKSHOP w JOIN
       (SELECT STOCK_ID, SUM(QUANTITY_ORDERED) as QUANTITY_ORDERED
        FROM ORDERS o
        GROUP BY STOCK_ID
       ) o
       ON w.STOCK_ID = o.STOCK_ID
    SET STOCK_LEVEL = (w.STOCK_LEVEL - o.QUANTITY_ORDERED);
</code>```

Title: How to update across two tables using a function SQL

Body:
The correct syntax in MySQL is:

UPDATE WORKSHOP w JOIN
       ORDERS o
       ON w.STOCK_ID = o.STOCK_ID
    SET STOCK_LEVEL = (w.STOCK_LEVEL - o.QUANTITY_ORDERED);

Presumably, ORDERS could have multiple rows for a given STOCK_ID.  If so, you need to pre-aggregate to reduce the quantity for all of them:

UPDATE WORKSHOP w JOIN
       (SELECT STOCK_ID, SUM(QUANTITY_ORDERED) as QUANTITY_ORDERED
        FROM ORDERS o
        GROUP BY STOCK_ID
       ) o
       ON w.STOCK_ID = o.STOCK_ID
    SET STOCK_LEVEL = (w.STOCK_LEVEL - o.QUANTITY_ORDERED);


问:
xcode jumps a method and finish
im new at coding with Xcode but strangely it jumps some instructions and finish the program without printing the results. the find_track method is not printing the position of the song and skips to end. the code can be build and has "apparently"no error (it comes from a C coding book). Anyone familiar with Xcode who can help ?

```<code>char tracks[][80] = {"my spirit","code songs"};
void find_track(char search_for[]) {
int i;
for (i = 0; i < 2; i++){
    if (strstr(tracks[i],search_for)){
        printf("Track %i: '%s'\n", i, tracks[i]);
    }
  }
}
int main()
{
char search_for[80];
printf("Search for: \n");
fgets(search_for, 80, stdin);
find_track(search_for);
return 0;
}
** Program ended with exit code: 0 // exit message from Xcode
</code>```

答:
fgets leave newline (enter key) in the buffer. You can easily test it

```<code>int main(void)
{
    char search_for[80];
    printf("Search for: \n");
    fgets(search_for, 80, stdin);
    printf("%s", search_for);

    for (size_t i=0; i<strlen(search_for); i++)
    {
        printf ("%X - %c\n", search_for[i], search_for[i]);
    }

    return 0;
}
</code>```

Input my spirit from terminal output will be

```<code>0x6D - m
0x79 - y
0x20 -
0x73 - s
0x70 - p
0x69 - i
0x72 - r
0x69 - i
0x74 - t
0x0A -
</code>```

Final 0x0A is '\n' char: newline.

Passing directly it to find_track function strstr will try to match that char too.
So simple solution is to remove that char:

```<code>#include <stdio.h>
#include <string.h>

char tracks[][80] = { "my spirit", "code songs" };

void find_track(char search_for[])
{
    int i;
    for (i = 0; i < 2; i++)
    {
        if (strstr(tracks[i], search_for) != NULL)
        {
            printf("Track %i: %s\n", i, tracks[i]);
        }
    }
}
int main(void)
{
    char search_for[80];
    printf("Search for: \n");
    fgets(search_for, 80, stdin);
    printf("%s", search_for);

    // Remove newline
    search_for[strlen(search_for)-1] = '\0';

    find_track(search_for);

    return 0;
}
</code>```

Title: xcode jumps a method and finish

Body:
im new at coding with Xcode but strangely it jumps some instructions and finish the program without printing the results. the find_track method is not printing the position of the song and skips to end. the code can be build and has "apparently"no error (it comes from a C coding book). Anyone familiar with Xcode who can help ?

char tracks[][80] = {"my spirit","code songs"};
void find_track(char search_for[]) {
int i;
for (i = 0; i < 2; i++){
    if (strstr(tracks[i],search_for)){
        printf("Track %i: '%s'\n", i, tracks[i]);
    }
  }
}
int main()
{
char search_for[80];
printf("Search for: \n");
fgets(search_for, 80, stdin);
find_track(search_for);
return 0;
}
** Program ended with exit code: 0 // exit message from Xcode

Body:
fgets leave newline (enter key) in the buffer. You can easily test it

int main(void)
{
    char search_for[80];
    printf("Search for: \n");
    fgets(search_for, 80, stdin);
    printf("%s", search_for);

    for (size_t i=0; i<strlen(search_for); i++)
    {
        printf ("%X - %c\n", search_for[i], search_for[i]);
    }

    return 0;
}

Input my spirit from terminal output will be

0x6D - m
0x79 - y
0x20 -
0x73 - s
0x70 - p
0x69 - i
0x72 - r
0x69 - i
0x74 - t
0x0A -

Final 0x0A is '\n' char: newline.

Passing directly it to find_track function strstr will try to match that char too.
So simple solution is to remove that char:

#include <stdio.h>
#include <string.h>

char tracks[][80] = { "my spirit", "code songs" };

void find_track(char search_for[])
{
    int i;
    for (i = 0; i < 2; i++)
    {
        if (strstr(tracks[i], search_for) != NULL)
        {
            printf("Track %i: %s\n", i, tracks[i]);
        }
    }
}
int main(void)
{
    char search_for[80];
    printf("Search for: \n");
    fgets(search_for, 80, stdin);
    printf("%s", search_for);

    // Remove newline
    search_for[strlen(search_for)-1] = '\0';

    find_track(search_for);

    return 0;
}


问:
Why PostgreSQL does not like UPPERCASE table names?
I have recently tried to create some tables in PostgreSQL all in uppercase names. However in order to query them I need to put the table name inside the quotation  "TABLE_NAME". Is there any way to avoid this and tell the postgres to work with uppercase name as normal ?

UPDATE

this query create a table with lowercase table_name

```<code>create table TABLE_NAME
(
id integer,
name varchar(255)
)
</code>```

However, this query creates a table with uppercase name "TABLE_NAME"

```<code>create table "TABLE_NAME"
(
id integer,
name varchar(255)
)
</code>```

the problem is the quotations are part of the name now!!
in my case I do not create the tables manually, another Application creates the table and the names are in capital letters. this cause problems when I want to use CQL filters via Geoserver.

答:
The question implies that double quotes, when used to force PostgreSQL to recognize casing for an identifier name, actually become part of the identifier name. That's not correct. What does happen is that if you use double quotes to force casing, then you must always use double quotes to reference that identifier.

Background:

In PostgreSQL, names of identifiers are always folded to lowercase unless you surround the identifier name with double quotes. This can lead to confusion.

Consider what happens if you run these two statements in sequence:

```<code>CREATE TABLE my_table (
    t_id serial,
    some_value text
);
</code>```

That creates a table named my_table.

Now, try to run this:

```<code>CREATE TABLE My_Table (
    t_id serial,
    some_value text
);
</code>```

PostgreSQL ignores the uppercasing (because the table name is not surrounded by quotes) and tries to make another table called my_table. When that happens, it throws an error:

```<code>ERROR:  relation "my_table" already exists
</code>```

To make a table with uppercase letters, you'd have to run:

```<code>CREATE TABLE "My_Table" (
    t_id serial,
    some_value text
);
</code>```

Now you have two tables in your database:

```<code> Schema |           Name            | Type  |  Owner
--------+---------------------------+-------+----------
 public | My_Table                  | table | postgres
 public | my_table                  | table | postgres
</code>```

The only way to ever access My_Table is to then surround the identifier name with double quotes, as in:

```<code>SELECT * FROM "My_Table"
</code>```

If you leave the identifier unquoted, then PostgreSQL would fold it to lowercase and query my_table.

Body:
I have recently tried to create some tables in PostgreSQL all in uppercase names. However in order to query them I need to put the table name inside the quotation  "TABLE_NAME". Is there any way to avoid this and tell the postgres to work with uppercase name as normal ?

UPDATE

this query create a table with lowercase table_name

create table TABLE_NAME
(
id integer,
name varchar(255)
)

However, this query creates a table with uppercase name "TABLE_NAME"

create table "TABLE_NAME"
(
id integer,
name varchar(255)
)

the problem is the quotations are part of the name now!!
in my case I do not create the tables manually, another Application creates the table and the names are in capital letters. this cause problems when I want to use CQL filters via Geoserver.

Body:
The question implies that double quotes, when used to force PostgreSQL to recognize casing for an identifier name, actually become part of the identifier name. That's not correct. What does happen is that if you use double quotes to force casing, then you must always use double quotes to reference that identifier.

Background:

In PostgreSQL, names of identifiers are always folded to lowercase unless you surround the identifier name with double quotes. This can lead to confusion.

Consider what happens if you run these two statements in sequence:

CREATE TABLE my_table (
    t_id serial,
    some_value text
);

That creates a table named my_table.

Now, try to run this:

CREATE TABLE My_Table (
    t_id serial,
    some_value text
);

PostgreSQL ignores the uppercasing (because the table name is not surrounded by quotes) and tries to make another table called my_table. When that happens, it throws an error:

ERROR:  relation "my_table" already exists

To make a table with uppercase letters, you'd have to run:

CREATE TABLE "My_Table" (
    t_id serial,
    some_value text
);

Now you have two tables in your database:

 Schema |           Name            | Type  |  Owner
--------+---------------------------+-------+----------
 public | My_Table                  | table | postgres
 public | my_table                  | table | postgres

The only way to ever access My_Table is to then surround the identifier name with double quotes, as in:

SELECT * FROM "My_Table"

If you leave the identifier unquoted, then PostgreSQL would fold it to lowercase and query my_table.


问:
Web Deploy to Azure Web App in App Service Environment
I am experiencing a problem deploying to a Azure Web App hosted inside an App Service Environment (ASE) with an Internal Load Balancer (ILB) using the web deploy step in Team City.  It also fails when trying to deploy directly from my machine using Visual Studio.

Here's the error: "could not connect to the remote computer using the specified process ("Web Management Service") because the server did not respond. Make sure that the process is started on the remote computer."

This error is a bit misleading because, upon further investigation, the web app is returning (401) unauthorized error even though I am able to connect to SCM/Kudo using the credentials in the publishing profile.

The only way I have been able to deploy is via FTP after establishing a VPN connection.

After a lot of research, I found some other folks who were told to stop/start the site, etc., but that has not worked in this case. Do web apps act differently when hosted in an ASE? I have not run into this problem deploying to any other web app.

Any ideas on what could be causing this would be greatly appreciated.

Thanks in advance!

答:
Looks like msdeploy requires by default TLS 1.0 to be available. I bet your ASE have its TLS 1.0 deactivated. So you have two choices:

re-activate TLS 1.0 in your ASE (potential security breach)

configure your build agent (if you have access to it) to use TLS 1.1 and higher following the instructions here

Related answer here

Official Microsoft support here


问:
Linked server reference "Invalid Column Name"
In SSMS 2012, I have created a linked server in SERVERA to SERVERB from which I have successfully written queries to multiple tables within the DBB database using a four part reference.

When I try to reference the 'Charge' table in the 'DBB' database with a simple select statement:

```<code>SELECT * FROM [SERVERB].[DBB].dbo.Charge
</code>```

I get the following message:

Msg 207, Level 16, State 1, Line 1 Invalid column name 'charge_type'.

This column exists in the DBB database as 'Charge_Type', however, the collation of SERVERB is case insensitive, whereas the collation of SERVERA is case sensitive (which is where, I believe, my problem lies).

Does anyone have experience with this issue?

答:
(For the people who might end up here)

You can change the collation on the fly. In this case, you have to write the name of the column names in the select query. What I mean is,
rather than writing query like this:

SELECT * FROM [SERVERB].[DBB].dbo.Charge

write the query like this:

SELECT Charge_Col1, Charge_Col2, Charge_Type COLLATE Latin1_General_CI_AS FROM [SERVERB].[DBB].dbo.Charge

There is another post similar to this: how we can select two columns having different collation

Body:
In SSMS 2012, I have created a linked server in SERVERA to SERVERB from which I have successfully written queries to multiple tables within the DBB database using a four part reference.

When I try to reference the 'Charge' table in the 'DBB' database with a simple select statement:

SELECT * FROM [SERVERB].[DBB].dbo.Charge

I get the following message:

Msg 207, Level 16, State 1, Line 1 Invalid column name 'charge_type'.

This column exists in the DBB database as 'Charge_Type', however, the collation of SERVERB is case insensitive, whereas the collation of SERVERA is case sensitive (which is where, I believe, my problem lies).

Does anyone have experience with this issue?


问:
Convert value number key to string php?
Here is my code :

```<code> foreach($urlImages as $key => $u){

        $nameImg = $id_product.'_'.$key.'_'.md5(uniqid(rand(), true)).'.png';

    }
</code>```

The key value is incremented, I want to change the key number to a string like:

```<code>if $key=1 i want $key=white
if $key=2 i want $key=black
</code>```

答:
@psppro26 simple try the concept like below:</p>

```<code><?php
$color = array(1 => "white", 2 =>"black", 3 => "grey");
foreach($urlImages as $key => $u){

        $nameImg = $id_product.'_'.$color[$key].'_'.md5(uniqid(rand(), true)).'.png';

}
</code>```

Title: Convert value number key to string php?

Body:
Here is my code :

 foreach($urlImages as $key => $u){

        $nameImg = $id_product.'_'.$key.'_'.md5(uniqid(rand(), true)).'.png';

    }

The key value is incremented, I want to change the key number to a string like:

if $key=1 i want $key=white
if $key=2 i want $key=black

Body:
@psppro26 simple try the concept like below:

<?php
$color = array(1 => "white", 2 =>"black", 3 => "grey");
foreach($urlImages as $key => $u){

        $nameImg = $id_product.'_'.$color[$key].'_'.md5(uniqid(rand(), true)).'.png';

}


答:
Use an update join:

```<code>UPDATE WORKSHOP w
INNER JOIN ORDERS o
    ON w.STOCK_ID = o.STOCK_ID
SET w.STOCK_LEVEL =
   (w.STOCK_LEVEL - o.QUANTITY_ORDERED)
</code>```

Another way to do the update would be via a correlated subquery:

```<code>UPDATE WORKSHOP w
SET w.STOCK_LEVEL = w.STOCK_LEVEL -
    (SELECT o.QUANTITY_ORDERED FROM ORDERS o
     WHERE w.STOCK_ID = o.STOCK_ID)
</code>```

If you were using Oracle, this might be your only option as Oracle does not support update join syntax.

Body:
Use an update join:

UPDATE WORKSHOP w
INNER JOIN ORDERS o
    ON w.STOCK_ID = o.STOCK_ID
SET w.STOCK_LEVEL =
   (w.STOCK_LEVEL - o.QUANTITY_ORDERED)

Another way to do the update would be via a correlated subquery:

UPDATE WORKSHOP w
SET w.STOCK_LEVEL = w.STOCK_LEVEL -
    (SELECT o.QUANTITY_ORDERED FROM ORDERS o
     WHERE w.STOCK_ID = o.STOCK_ID)

If you were using Oracle, this might be your only option as Oracle does not support update join syntax.


Title: Nodejs returns the full JSON of the Blockchain Rates API but I can't access particular objects inside it. Why?

Body:
I have a file that makes a request to blockchain.info/ticker API in order to pull the latest price of bitcoin.

script.js:

let request = require('request');
let url = "https://blockchain.info/ticker"

request.get(url,
function(error, response, body) {
    console.log(body); //first
    console.log(body.USD); //second
});

The first console.log statement inside the request.get returns:

{
  "USD" : {"15m" : 1034.99, "last" : 1034.99, "buy" : 1033.63, "sell" : 1034.99,  "symbol" : "$"},
  "ISK" : {"15m" : 116090.37, "last" : 116090.37, "buy" : 115937.82, "sell" : 116090.37,  "symbol" : "kr"},
  "HKD" : {"15m" : 8043.46, "last" : 8043.46, "buy" : 8032.89, "sell" : 8043.46,  "symbol" : "$"},
  "TWD" : {"15m" : 31374.69, "last" : 31374.69, "buy" : 31333.46, "sell" : 31374.69,  "symbol" : "NT$"},
  "CHF" : {"15m" : 1030.89, "last" : 1030.89, "buy" : 1029.53, "sell" : 1030.89,  "symbol" : "CHF"},
  "EUR" : {"15m" : 963.89, "last" : 963.89, "buy" : 962.63, "sell" : 963.89,  "symbol" : "€"},
  "DKK" : {"15m" : 7170.6, "last" : 7170.6, "buy" : 7161.17, "sell" : 7170.6,  "symbol" : "kr"},
  "CLP" : {"15m" : 685784.37, "last" : 685784.37, "buy" : 684883.24, "sell" : 685784.37,  "symbol" : "$"},
  "CAD" : {"15m" : 1380.41, "last" : 1380.41, "buy" : 1378.6, "sell" : 1380.41,  "symbol" : "$"},
  "CNY" : {"15m" : 7131.48, "last" : 7131.48, "buy" : 7122.11, "sell" : 7131.48,  "symbol" : "¥"},
  "THB" : {"15m" : 35634.71, "last" : 35634.71, "buy" : 35587.88, "sell" : 35634.71,  "symbol" : "฿"},
  "AUD" : {"15m" : 1349.36, "last" : 1349.36, "buy" : 1347.58, "sell" : 1349.36,  "symbol" : "$"},
  "SGD" : {"15m" : 1443.9, "last" : 1443.9, "buy" : 1442.01, "sell" : 1443.9,  "symbol" : "$"},
  "KRW" : {"15m" : 1155773.33, "last" : 1155773.33, "buy" : 1154254.62, "sell" : 1155773.33,  "symbol" : "₩"},
  "JPY" : {"15m" : 115110.38, "last" : 115110.38, "buy" : 114959.12, "sell" : 115110.38,  "symbol" : "¥"},
  "PLN" : {"15m" : 4072.84, "last" : 4072.84, "buy" : 4067.49, "sell" : 4072.84,  "symbol" : "zł"},
  "GBP" : {"15m" : 832.11, "last" : 832.11, "buy" : 831.01, "sell" : 832.11,  "symbol" : "£"},
  "SEK" : {"15m" : 9212.32, "last" : 9212.32, "buy" : 9200.21, "sell" : 9212.32,  "symbol" : "kr"},
  "NZD" : {"15m" : 1474.6, "last" : 1474.6, "buy" : 1472.66, "sell" : 1474.6,  "symbol" : "$"},
  "BRL" : {"15m" : 3232.68, "last" : 3232.68, "buy" : 3228.43, "sell" : 3232.68,  "symbol" : "R$"},
  "RUB" : {"15m" : 58287.38, "last" : 58287.38, "buy" : 58210.79, "sell" : 58287.38,  "symbol" : "RUB"}

}

The second console.log statement returns:

undefined

What have I tried:
I have tried to assign the same output that I get in the terminal to a variable in a chrome inspector and access different objects just to test out if my syntax is correct. Syntax is correct so, I'm really puzzled.

Why is my second console.log statement undefined and how can I fix this in order to get the "15m" price inside of the USD object?

Body:
Here is your code fixed:

let request = require('request');
let url = "https://blockchain.info/ticker"

request.get(url, function(error, response, body) {
    console.log(body); //first
    console.log(JSON.parse(body).USD); // second
});

Request return the response as a JSON.
You have to parse it with JSON.parse in order to retrieve the USD attribute.

Output

{
  "USD" : {"15m" : 1034.66, "last" : 1034.66, "buy" : 1033, "sell" : 1034.66,  "symbol" : "$"},
  "ISK" : {"15m" : 116053.35, "last" : 116053.35, "buy" : 115867.16, "sell" : 116053.35,  "symbol" : "kr"},
  "HKD" : {"15m" : 8040.9, "last" : 8040.9, "buy" : 8028, "sell" : 8040.9,  "symbol" : "$"},
  "TWD" : {"15m" : 31364.68, "last" : 31364.68, "buy" : 31314.36, "sell" : 31364.68,  "symbol" : "NT$"},
  "CHF" : {"15m" : 1030.56, "last" : 1030.56, "buy" : 1028.91, "sell" : 1030.56,  "symbol" : "CHF"},
  "EUR" : {"15m" : 963.59, "last" : 963.59, "buy" : 962.04, "sell" : 963.59,  "symbol" : "€"},
  "DKK" : {"15m" : 7168.31, "last" : 7168.31, "buy" : 7156.81, "sell" : 7168.31,  "symbol" : "kr"},
  "CLP" : {"15m" : 685565.72, "last" : 685565.72, "buy" : 684465.8, "sell" : 685565.72,  "symbol" : "$"},
  "CAD" : {"15m" : 1379.97, "last" : 1379.97, "buy" : 1377.76, "sell" : 1379.97,  "symbol" : "$"},
  "CNY" : {"15m" : 7129.21, "last" : 7129.21, "buy" : 7117.77, "sell" : 7129.21,  "symbol" : "¥"},
  "THB" : {"15m" : 35623.34, "last" : 35623.34, "buy" : 35566.19, "sell" : 35623.34,  "symbol" : "฿"},
  "AUD" : {"15m" : 1348.93, "last" : 1348.93, "buy" : 1346.76, "sell" : 1348.93,  "symbol" : "$"},
  "SGD" : {"15m" : 1443.44, "last" : 1443.44, "buy" : 1441.13, "sell" : 1443.44,  "symbol" : "$"},
  "KRW" : {"15m" : 1155404.82, "last" : 1155404.82, "buy" : 1153551.1, "sell" : 1155404.82,  "symbol" : "₩"},
  "JPY" : {"15m" : 115073.68, "last" : 115073.68, "buy" : 114889.05, "sell" : 115073.68,  "symbol" : "¥"},
  "PLN" : {"15m" : 4071.54, "last" : 4071.54, "buy" : 4065.01, "sell" : 4071.54,  "symbol" : "zł"},
  "GBP" : {"15m" : 831.84, "last" : 831.84, "buy" : 830.51, "sell" : 831.84,  "symbol" : "£"},
  "SEK" : {"15m" : 9209.38, "last" : 9209.38, "buy" : 9194.6, "sell" : 9209.38,  "symbol" : "kr"},
  "NZD" : {"15m" : 1474.13, "last" : 1474.13, "buy" : 1471.76, "sell" : 1474.13,  "symbol" : "$"},
  "BRL" : {"15m" : 3231.65, "last" : 3231.65, "buy" : 3226.47, "sell" : 3231.65,  "symbol" : "R$"},
  "RUB" : {"15m" : 58268.79, "last" : 58268.79, "buy" : 58175.31, "sell" : 58268.79,  "symbol" : "RUB"}

}
{ '15m': 1034.66,
  last: 1034.66,
  buy: 1033,
  sell: 1034.66,
  symbol: '$' }


答:
There is no property "usd" in the object. Try the following:</p>

```<code>console.log(body.USD);
</code>```

Body:
There is no property "usd" in the object. Try the following:

console.log(body.USD);


问:
Replacing part of of an attribute value using cheerio?
I need to replace the sub string target with the string deploy for the href value of the following element using gulp-cheerio:

```<code>  <link rel="stylesheet" type="text/css" href="../../../target/test/css/index.css">
</code>```

答:
I haven't used cheerio before, but assuming the jQuery syntax will work, you do </p>

```<code>.pipe(cheerio(function($, file) {
  $('link[href="../../../target/test/css/index.css"]').attr('href',
    $('link[href="../../../target/test/css/index.css"]').attr('href').replace('target', 'deploy'));
}))
</code>```

Body:
I need to replace the sub string target with the string deploy for the href value of the following element using gulp-cheerio:

  <link rel="stylesheet" type="text/css" href="../../../target/test/css/index.css">

Body:
I haven't used cheerio before, but assuming the jQuery syntax will work, you do

.pipe(cheerio(function($, file) {
  $('link[href="../../../target/test/css/index.css"]').attr('href',
    $('link[href="../../../target/test/css/index.css"]').attr('href').replace('target', 'deploy'));
}))


问:
Configure UICollectionViewCells having same cell type but different UI styles
I have a UICollectionView that has the same cell type, but every cell has different UI properties like background color, textColor ...

I could configure them inside collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell as below:

```<code> func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let item = indexPath.item
    switch item {
    case 1:
        let cell = collectionView.dequeueReusableCell(forIndexPath: indexPath) as ACollectionViewCell
        cell.ScoreName.text = xxx
        cell.ScoreName.textColor = xxx
        cell.score.text = xxx
        cell.score.backgroundColor = xxx
        cell.....

        return cell
    case 2: ...
    case 3: ...
    case 4: ...
    case 5: ...
    case 6:
        let cell = collectionView.dequeueReusableCell(forIndexPath: indexPath) as BCollectionViewCell
        cell.title.text = "xxx xxx"
        cell.score.isHidden = true
        return cell
    default:

        let cell = collectionView.dequeueReusableCell(forIndexPath: indexPath) as DCollectionViewCell
        cell.title.text = "xxx"
        cell.score.text = "xx"
        cell.score.backgroundColor = .green
        cell....
        return cell
    }
}
</code>```

As you can see from case 1 to 5 same cell type with different UI properties, it is not appealing at all also it is not scalable so what is the best approach to deal with such configuration ?

答:
You need keep data in memory so you have to store the configuration of cell due to reusable nature of UICollectionViewCell.

```<code>let dictForCell = ["color":UIColor.redColor(),"isHidden":false] //add key value according to your need
let arrOfCell   = [dictForCell] //also add dictionary of detail

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let dictData = [indexPath.row]
        let cell = collectionView.dequeueReusableCell(forIndexPath: indexPath) as ACollectionViewCell
        cell.ScoreName.textColor = dictData["color"] as! UIColor
        cell.score.isHidden = dictData["color"] as! Bool
        cell.score.text = xxx
        cell.score.backgroundColor = xxx
        cell.ScoreName.text = xxx
        return cell
    }
</code>```

Body:
I have a UICollectionView that has the same cell type, but every cell has different UI properties like background color, textColor ...

I could configure them inside collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell as below:

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let item = indexPath.item
    switch item {
    case 1:
        let cell = collectionView.dequeueReusableCell(forIndexPath: indexPath) as ACollectionViewCell
        cell.ScoreName.text = xxx
        cell.ScoreName.textColor = xxx
        cell.score.text = xxx
        cell.score.backgroundColor = xxx
        cell.....

        return cell
    case 2: ...
    case 3: ...
    case 4: ...
    case 5: ...
    case 6:
        let cell = collectionView.dequeueReusableCell(forIndexPath: indexPath) as BCollectionViewCell
        cell.title.text = "xxx xxx"
        cell.score.isHidden = true
        return cell
    default:

        let cell = collectionView.dequeueReusableCell(forIndexPath: indexPath) as DCollectionViewCell
        cell.title.text = "xxx"
        cell.score.text = "xx"
        cell.score.backgroundColor = .green
        cell....
        return cell
    }
}

As you can see from case 1 to 5 same cell type with different UI properties, it is not appealing at all also it is not scalable so what is the best approach to deal with such configuration ?

Body:
You need keep data in memory so you have to store the configuration of cell due to reusable nature of UICollectionViewCell.

let dictForCell = ["color":UIColor.redColor(),"isHidden":false] //add key value according to your need
let arrOfCell   = [dictForCell] //also add dictionary of detail

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let dictData = [indexPath.row]
        let cell = collectionView.dequeueReusableCell(forIndexPath: indexPath) as ACollectionViewCell
        cell.ScoreName.textColor = dictData["color"] as! UIColor
        cell.score.isHidden = dictData["color"] as! Bool
        cell.score.text = xxx
        cell.score.backgroundColor = xxx
        cell.ScoreName.text = xxx
        return cell
    }


答:
You need to copy the number which you use to find out how much digits your number has. Otherwise you change the number itself and don't know anymore what it was.
The second mistake is that you divide an integer by Math.pow() which returns a double. So your result is double. You want to have an integer to use the modulo operator.

```<code> public static boolean isFriendly(int number)
{
    int counter = 1;
    int tmpNumber = number;
    while (tmpNumber / 10 >= 1)
    {
        counter ++;
        tmpNumber = tmpNumber / 10;
    }

    boolean check = true;

    for (int i = 1; i <= counter; i++)
    {

        if ((int)(number / Math.pow(10, (counter - i))) % i == 0 && check)
        {
            check = true;
        }
        else
        {
            check = false;
        }

    }
    return check;

}
</code>```

Title: Java program on "friendly numbers "

Body:
I am working on a assignment about so called "friendly-numbers" with the following definition: An integer is said to be friendly if the leftmost digit is divisible by 1, the leftmost two digits are divisible by 2, and the leftmost three digits are divisible by 3, and so on. The n-digit itself is divisible by n.

Also it was given we need to call a method (as I did or at least tried to do in the code below). It should print whether a number is friendly or not. However, my program prints "The integer is not friendly." in both cases. From what I have tried, I know the counter does work. I just cannot find what I am missing or doing wrong. Help would be appreciated, and preferably with an adaptation of the code below, since that is what I came up with myself.

import java.util.Scanner;
public class A5E4 {

    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Please enter an integer: ");
        int friendlyNumber = in.nextInt();
        boolean result = isFriendly(friendlyNumber);
        if (result)
        {
            System.out.println("The integer is friendly");
        }
        else
        {
            System.out.println("The integer is not friendly");
        }
    }
    public static boolean isFriendly(int number)
    {
        int counter = 1;

        while (number / 10 >= 1)
        {
            counter ++;
            number = number / 10;
        }

        boolean check = true;

        for (int i = 1; i <= counter; i++)
        {

            if (number / Math.pow(10, (counter - i)) % i == 0 && check)
            {
                check = true;
            }
            else
            {
                check = false;
            }

        }
        return check;

    }
}

Body:
You need to copy the number which you use to find out how much digits your number has. Otherwise you change the number itself and don't know anymore what it was.
The second mistake is that you divide an integer by Math.pow() which returns a double. So your result is double. You want to have an integer to use the modulo operator.

 public static boolean isFriendly(int number)
{
    int counter = 1;
    int tmpNumber = number;
    while (tmpNumber / 10 >= 1)
    {
        counter ++;
        tmpNumber = tmpNumber / 10;
    }

    boolean check = true;

    for (int i = 1; i <= counter; i++)
    {

        if ((int)(number / Math.pow(10, (counter - i))) % i == 0 && check)
        {
            check = true;
        }
        else
        {
            check = false;
        }

    }
    return check;

}


问:
Newbie stuck on a jQuery question...conditional statement
So I'm a complete newbie and stuck on a conditional statement.  Here's my code:

```<code><script type="text/javascript">
$(document).ready(function(){
 if($('span.fc_cart_item_price_total') == 0) {
  $(span.fc_info).addClass('foo');
 };
});
</script>
</code>```

So I'm attempting to see if span with a class of "fc_cart_item_price_total" has a value of "0", to then add a class of "foo" to the span with a class of ".fc_info".  This code above is not working.  Here's the HTML:

```<code><span class="fc_info">Info 1</span><br />
<span class="fc_cart_item_price_total">$0.00</span><br />
<span class="fc_info">Info 2</span>
</code>```

Here's the other challenge I have.  I'm trying to select the span with the value of "fc_info" before the span with the class of "fc_cart_item_price_total" but have no idea of how to just select this one span.

答:
Comparing with 0 is not the best that you can do. Try this instead:

```<code>if (!parseFloat($('.fc_cart_item_price_total').text()) {
....
</code>```

Use ParseInt or ParseFloat depending on the data you expect.

Body:
So I'm a complete newbie and stuck on a conditional statement.  Here's my code:

So I'm attempting to see if span with a class of "fc_cart_item_price_total" has a value of "0", to then add a class of "foo" to the span with a class of ".fc_info".  This code above is not working.  Here's the HTML:

Info 1

$0.00

Info 2

Here's the other challenge I have.  I'm trying to select the span with the value of "fc_info" before the span with the class of "fc_cart_item_price_total" but have no idea of how to just select this one span.

Body:
Comparing with 0 is not the best that you can do. Try this instead:

if (!parseFloat($('.fc_cart_item_price_total').text()) {
....

Use ParseInt or ParseFloat depending on the data you expect.


问:
I got an error message about some Neon code
To learn ARM Neon on Android, I tried to run a sample code.

But I got an error message.

```<code> uint16_t in[8] = {0, 1, 2, 3, 4, 5, 6, 7};
 uint16_t out[8];
 r = vld1q_u16(&in[0]);
 **vst1q_u16(&out[0], r);** <-- Here comes an error message
</code>```

the error message is Invalid Arguments

I don't understand why the problem was.

vld1q_u16 works correctly and the value of r is also correct.

but vst1q_u16 doesn't work.

答:
You should use

```<code>r = vld1q_u16(in);
vst1q_u16(out, r);
</code>```

SIMD engines like NEON read memory contents backwards by default so giving it address of array element 0 is bad idea.

Body:
To learn ARM Neon on Android, I tried to run a sample code.

But I got an error message.

 uint16_t in[8] = {0, 1, 2, 3, 4, 5, 6, 7};
 uint16_t out[8];
 r = vld1q_u16(&in[0]);
 **vst1q_u16(&out[0], r);** <-- Here comes an error message

the error message is Invalid Arguments

I don't understand why the problem was.

vld1q_u16 works correctly and the value of r is also correct.

but vst1q_u16 doesn't work.

Body:
You should use

r = vld1q_u16(in);
vst1q_u16(out, r);

SIMD engines like NEON read memory contents backwards by default so giving it address of array element 0 is bad idea.


答:
Simplest solution would be something like that</p>

```<code>/* here you declare what should be swap to what, it can be in order, or you can index them manually */
$arrayToSwap = [
    1 => 'white',
    2 => 'black'
 ];
/* Here you change keys for future use */
$newArray = []
foreach ($urlImages as $key => $uu) {
    $newArray[$arrayToSwap[$key]] = $u;
}
</code>```

Title: Convert value number key to string php?

Body:
Simplest solution would be something like that

/* here you declare what should be swap to what, it can be in order, or you can index them manually */
$arrayToSwap = [
    1 => 'white',
    2 => 'black'
 ];
/* Here you change keys for future use */
$newArray = []
foreach ($urlImages as $key => $uu) {
    $newArray[$arrayToSwap[$key]] = $u;
}


答: console.log(body.USD);//case sensitive

Body: console.log(body.USD);//case sensitive


问:
How to compare if any of the elements in a row is same
Is there a way to compare whether "any value of" a row is identical to "any value" of the row above -- regardless of the order? Below is a very random input data table.

```<code>DT <- data.table(A=c("a","a","b","d","e","f","h","i","j"),
                 B=c("a","b","c","c","f","g",NA,"j",NA),
                 C=c("a","b","c","b","g","h",NA,NA,NA))

> DT
   A  B  C
1: a  a  a
2: a  b  b
3: b  c  c
4: d  c  b
5: e  f  g
6: f  g  h
7: h NA NA
8: i  j NA
9: j NA NA
</code>```

I would like to add a column D that compares a row with the row above, and compare whether any values of the two rows are identical (regardless of the order). So the desired output would be:

```<code> > DT
   A  B  C  D
1: a  a  a  0 #No row above to compare; could be either NA or 0
2: a  b  b  1 #row 2 has "a", which is in row 1; returns 1
3: b  c  c  1 #row 3 has "b", which is in row 2; returns 1
4: d  c  b  1 #row 4 has "b" and "c", which are in row 3; returns 1
5: e  f  g  0 #row 5 has nothing that is in row 4; returns 0
6: f  g  h  1 #row 6 has "f" and "g", which are in row 5; returns 1
7: h NA NA  1 #row 7 has "h", which is in row 6; returns 1
8: i  j NA  0 #row 8 has nothing that is in row 7 (NA doesn't count)
9: j NA NA  1 #row 9 has "j", which is in row 8; returns 1 (NA doesn't count)
</code>```

The main idea is that I would like to compare a row (or a vector) with another row (vector), and define two rows to be identical if any of the elements in each row (vector) are.  (without reiterating to compare each element)

答:
We can do this by getting the lead rows of the dataset, paste each row, check for any pattern in with the pasteed rows of original dataset using grepl and Map, then unlist and convert to integer

```<code>DT[, D := {
     v1 <- do.call(paste, .SD)
     v2 <- do.call(paste, c(shift(.SD, type = "lead"), sep="|"))
     v2N <- gsub("NA\\|*|\\|*NA", "", v2)
     v3 <- unlist(Map(grepl, v2N, v1), use.names = FALSE)
     as.integer(head(c(FALSE, v3), -1))
}]

DT
#   A  B  C D
#1: a  a  a 0
#2: a  b  b 1
#3: b  c  c 1
#4: d  c  b 1
#5: e  f  g 0
#6: f  g  h 1
#7: h NA NA 1
#8: i  j NA 0
#9: j NA NA 1
</code>```

Or we can do a split and do comparison using Map

```<code>as.integer(c(FALSE, unlist(Map(function(x,y) {
     x1 <- na.omit(unlist(x))
     y1 <- na.omit(unlist(y))
    any(x1 %in% y1 | y1 %in% x1)  },
     split(DT[-nrow(DT)], 1:(nrow(DT)-1)), split(DT[-1], 2:nrow(DT))), use.names = FALSE)))
</code>```

Body:
Is there a way to compare whether "any value of" a row is identical to "any value" of the row above -- regardless of the order? Below is a very random input data table.

DT <- data.table(A=c("a","a","b","d","e","f","h","i","j"),
                 B=c("a","b","c","c","f","g",NA,"j",NA),
                 C=c("a","b","c","b","g","h",NA,NA,NA))

> DT
   A  B  C
1: a  a  a
2: a  b  b
3: b  c  c
4: d  c  b
5: e  f  g
6: f  g  h
7: h NA NA
8: i  j NA
9: j NA NA

I would like to add a column D that compares a row with the row above, and compare whether any values of the two rows are identical (regardless of the order). So the desired output would be:

 > DT
   A  B  C  D
1: a  a  a  0 #No row above to compare; could be either NA or 0
2: a  b  b  1 #row 2 has "a", which is in row 1; returns 1
3: b  c  c  1 #row 3 has "b", which is in row 2; returns 1
4: d  c  b  1 #row 4 has "b" and "c", which are in row 3; returns 1
5: e  f  g  0 #row 5 has nothing that is in row 4; returns 0
6: f  g  h  1 #row 6 has "f" and "g", which are in row 5; returns 1
7: h NA NA  1 #row 7 has "h", which is in row 6; returns 1
8: i  j NA  0 #row 8 has nothing that is in row 7 (NA doesn't count)
9: j NA NA  1 #row 9 has "j", which is in row 8; returns 1 (NA doesn't count)

The main idea is that I would like to compare a row (or a vector) with another row (vector), and define two rows to be identical if any of the elements in each row (vector) are.  (without reiterating to compare each element)

Body:
We can do this by getting the lead rows of the dataset, paste each row, check for any pattern in with the pasteed rows of original dataset using grepl and Map, then unlist and convert to integer

DT[, D := {
     v1 <- do.call(paste, .SD)
     v2 <- do.call(paste, c(shift(.SD, type = "lead"), sep="|"))
     v2N <- gsub("NA\\|*|\\|*NA", "", v2)
     v3 <- unlist(Map(grepl, v2N, v1), use.names = FALSE)
     as.integer(head(c(FALSE, v3), -1))
}]

DT
#   A  B  C D
#1: a  a  a 0
#2: a  b  b 1
#3: b  c  c 1
#4: d  c  b 1
#5: e  f  g 0
#6: f  g  h 1
#7: h NA NA 1
#8: i  j NA 0
#9: j NA NA 1

Or we can do a split and do comparison using Map

as.integer(c(FALSE, unlist(Map(function(x,y) {
     x1 <- na.omit(unlist(x))
     y1 <- na.omit(unlist(y))
    any(x1 %in% y1 | y1 %in% x1)  },
     split(DT[-nrow(DT)], 1:(nrow(DT)-1)), split(DT[-1], 2:nrow(DT))), use.names = FALSE)))


问:
Error when calling method in ES6
Im getting an error that this.filterEvents is not define when calling a method from an onChange event in my class ? Cant quite figure out why?

I've tried calling it with Datepicker.filterEvents or this.constructor.filterEvents and this.filterEvents() -  without any luck :( - So hoping someone can point me in the right direction on where the error is?

Code here:

```<code>const daterangeConfig = {
  mode: "range",
  minDate: "today",
  dateFormat: "j M",
  weekNumbers: true,
  locale: 'da',
  onChange: function(selectedDates, dateStr) { //instance also param
    //update filter label with selected dates
    let filterBtn = document.querySelectorAll('[data-filterTrigger]');
    let filterBtnIndex = 1;
    let filterLabelTargetSpan = filterBtn[filterBtnIndex].nextElementSibling.querySelector('.btn--filter__labelb');
    filterLabelTargetSpan.innerText = dateStr;
    Datepicker.filterEvents(selectedDates);
  }
};

class Datepicker {
  constructor(container) {
    // Run initializing code once the DOM is ready.
    onReady(() => this.init(container));
    // You can put other initializer-code here if it isn't dependent on the DOM in any way.
    this.picker = new Flatpickr(this.dom.container, daterangeConfig);
  }

  init(container) {
    this.dom = {
      container
    };
  }

  filterEvents(dates) {
    console.log("filter events now");
  }
}
</code>```

答:
If filterEvents() is intended as a static method, meaning its logic is relevant to the DatePicker class but independent of any instance, then you can make it a static method as follows

```<code>class DatePicker {
  static filterEvents(dates) {
    ...
  }
}
</code>```

and refer to it as DatePicker.filterEvents.

In your code, you define filterEvents() as an instance method rather than a static method, which makes it accessible to instances of DatePicker but not available as a method of the DatePicker class. If you do intend to perform logic in filterEvents() which depends on a specific instance, then filterEvents() should be declared as you have done without the use of the static keyword and be referenced as this.filterEvents. It's important to understand that the this must refer to the relevant DatePicker instance.

See also the bind() method which may be useful depending on the desired behavior and code structure.

Title: Error when calling method in ES6

Body:
Im getting an error that this.filterEvents is not define when calling a method from an onChange event in my class ? Cant quite figure out why?

I've tried calling it with Datepicker.filterEvents or this.constructor.filterEvents and this.filterEvents() -  without any luck :( - So hoping someone can point me in the right direction on where the error is?

Code here:

const daterangeConfig = {
  mode: "range",
  minDate: "today",
  dateFormat: "j M",
  weekNumbers: true,
  locale: 'da',
  onChange: function(selectedDates, dateStr) { //instance also param
    //update filter label with selected dates
    let filterBtn = document.querySelectorAll('[data-filterTrigger]');
    let filterBtnIndex = 1;
    let filterLabelTargetSpan = filterBtn[filterBtnIndex].nextElementSibling.querySelector('.btn--filter__labelb');
    filterLabelTargetSpan.innerText = dateStr;
    Datepicker.filterEvents(selectedDates);
  }
};

class Datepicker {
  constructor(container) {
    // Run initializing code once the DOM is ready.
    onReady(() => this.init(container));
    // You can put other initializer-code here if it isn't dependent on the DOM in any way.
    this.picker = new Flatpickr(this.dom.container, daterangeConfig);
  }

  init(container) {
    this.dom = {
      container
    };
  }

  filterEvents(dates) {
    console.log("filter events now");
  }
}

Body:
If filterEvents() is intended as a static method, meaning its logic is relevant to the DatePicker class but independent of any instance, then you can make it a static method as follows

class DatePicker {
  static filterEvents(dates) {
    ...
  }
}

and refer to it as DatePicker.filterEvents.

In your code, you define filterEvents() as an instance method rather than a static method, which makes it accessible to instances of DatePicker but not available as a method of the DatePicker class. If you do intend to perform logic in filterEvents() which depends on a specific instance, then filterEvents() should be declared as you have done without the use of the static keyword and be referenced as this.filterEvents. It's important to understand that the this must refer to the relevant DatePicker instance.

See also the bind() method which may be useful depending on the desired behavior and code structure.