问:
How to put 9X equally sized buttons over a ImageView in Constraint Layout?
I have a ImageView inside a Constraint Layout as follow

```<code><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
    android:id="@+id/imageView"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginTop="8dp"
    android:adjustViewBounds="true"
    android:cropToPadding="false"
    android:scaleType="fitXY"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@drawable/argentina"
    android:layout_marginLeft="16dp"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintVertical_bias="0.501"
    android:layout_marginRight="16dp"
    android:layout_marginStart="16dp"
    android:layout_marginEnd="16dp" />
</code>```

and i want to cover this image with a 9X equally sized buttons as shown Here

notice that the Imageview change with the size of the constraint layout

答:
yes you can achieve that using constraint chain and the match_constraint(0dp) property
you have to define here vertical and horizontal chain to all button below is the sample for same

```<code><android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:layout_editor_absoluteY="81dp"
    tools:layout_editor_absoluteX="0dp">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:layout_marginTop="8dp"
            android:adjustViewBounds="true"
            android:cropToPadding="false"
            android:scaleType="fitXY"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:srcCompat="@drawable/firefox"
            android:layout_marginLeft="16dp"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintVertical_bias="0.501"
            android:layout_marginRight="16dp"
            android:layout_marginStart="16dp"
            android:layout_marginEnd="16dp" />
        <Button
            android:id="@+id/button1"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:text="Button"
            app:layout_constraintEnd_toEndOf="@+id/imageView"
            app:layout_constraintTop_toTopOf="@+id/imageView"
            app:layout_constraintStart_toEndOf="@+id/button5"
            app:layout_constraintBottom_toTopOf="@id/button41"
            app:layout_constraintVertical_chainStyle="spread_inside"/>

        <Button
            android:id="@+id/button31"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:text="Button"
            app:layout_constraintStart_toStartOf="@+id/imageView"
            app:layout_constraintTop_toTopOf="@+id/imageView"
            app:layout_constraintBottom_toTopOf="@id/button311"
            app:layout_constraintHorizontal_chainStyle="spread_inside"
            app:layout_constraintEnd_toStartOf="@+id/button51"
            app:layout_constraintVertical_chainStyle="spread_inside" />

        <Button
            android:id="@+id/button5"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:text="Button"
            app:layout_constraintTop_toTopOf="@+id/imageView"
            app:layout_constraintEnd_toStartOf="@+id/button11"
            app:layout_constraintStart_toEndOf="@+id/button13"
            app:layout_constraintBottom_toTopOf="@+id/button133"
            app:layout_constraintVertical_chainStyle="spread_inside" />

        <Button
            android:id="@+id/button311"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:text="Button"
            app:layout_constraintStart_toStartOf="@+id/imageView"
            app:layout_constraintTop_toBottomOf="@+id/button31"
            app:layout_constraintBottom_toTopOf="@+id/button13"
            app:layout_constraintEnd_toStartOf="@+id/button133"
            app:layout_constraintHorizontal_chainStyle="spread_inside" />

        <Button
            android:id="@+id/button133"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:text="Button"
            app:layout_constraintStart_toEndOf="@+id/button311"
            app:layout_constraintEnd_toStartOf="@+id/button41"
            app:layout_constraintTop_toBottomOf="@+id/button5"
            app:layout_constraintBottom_toTopOf="@+id/button51" />
        <Button
            android:id="@+id/button41"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintEnd_toEndOf="@+id/imageView"
            android:text="Button"
            app:layout_constraintTop_toBottomOf="@+id/button1"
            app:layout_constraintBottom_toTopOf="@+id/button11"
            app:layout_constraintStart_toEndOf="@+id/button133" />

        <Button
            android:id="@+id/button11"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:text="Button"
            app:layout_constraintEnd_toEndOf="@+id/imageView"
            app:layout_constraintBottom_toBottomOf="@+id/imageView"
            app:layout_constraintStart_toEndOf="@+id/button51"
            app:layout_constraintTop_toBottomOf="@id/button41"
            />

        <Button
            android:id="@+id/button13"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:text="Button"
            app:layout_constraintStart_toStartOf="@+id/imageView"
            app:layout_constraintBottom_toBottomOf="@+id/imageView"
            app:layout_constraintTop_toBottomOf="@id/button311"
            app:layout_constraintHorizontal_chainStyle="spread_inside"
            app:layout_constraintEnd_toStartOf="@+id/button51" />

        <Button
            android:id="@+id/button51"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:text="Button"
            app:layout_constraintBottom_toBottomOf="@+id/imageView"
            app:layout_constraintEnd_toStartOf="@+id/button11"
            app:layout_constraintStart_toEndOf="@+id/button13"
            app:layout_constraintTop_toBottomOf="@id/button133"/>
</android.support.constraint.ConstraintLayout>
</code>```

here is the design and blue print

you can get all the details here about chain and constraint
https://developer.android.com/reference/android/support/constraint/ConstraintLayout.html#Chains

this will work on all device size and orientation

NOTE: i recommend u too add some minHeight to your image view so to avoid to hiding the button but i don't know your requirement but it an noticeable point

Body:
I have a ImageView inside a Constraint Layout as follow

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
    android:id="@+id/imageView"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginTop="8dp"
    android:adjustViewBounds="true"
    android:cropToPadding="false"
    android:scaleType="fitXY"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@drawable/argentina"
    android:layout_marginLeft="16dp"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintVertical_bias="0.501"
    android:layout_marginRight="16dp"
    android:layout_marginStart="16dp"
    android:layout_marginEnd="16dp" />

and i want to cover this image with a 9X equally sized buttons as shown Here

notice that the Imageview change with the size of the constraint layout

Body:
yes you can achieve that using constraint chain and the match_constraint(0dp) property
you have to define here vertical and horizontal chain to all button below is the sample for same

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:layout_editor_absoluteY="81dp"
    tools:layout_editor_absoluteX="0dp">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:layout_marginTop="8dp"
            android:adjustViewBounds="true"
            android:cropToPadding="false"
            android:scaleType="fitXY"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:srcCompat="@drawable/firefox"
            android:layout_marginLeft="16dp"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintVertical_bias="0.501"
            android:layout_marginRight="16dp"
            android:layout_marginStart="16dp"
            android:layout_marginEnd="16dp" />
        <Button
            android:id="@+id/button1"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:text="Button"
            app:layout_constraintEnd_toEndOf="@+id/imageView"
            app:layout_constraintTop_toTopOf="@+id/imageView"
            app:layout_constraintStart_toEndOf="@+id/button5"
            app:layout_constraintBottom_toTopOf="@id/button41"
            app:layout_constraintVertical_chainStyle="spread_inside"/>

        <Button
            android:id="@+id/button31"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:text="Button"
            app:layout_constraintStart_toStartOf="@+id/imageView"
            app:layout_constraintTop_toTopOf="@+id/imageView"
            app:layout_constraintBottom_toTopOf="@id/button311"
            app:layout_constraintHorizontal_chainStyle="spread_inside"
            app:layout_constraintEnd_toStartOf="@+id/button51"
            app:layout_constraintVertical_chainStyle="spread_inside" />

        <Button
            android:id="@+id/button5"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:text="Button"
            app:layout_constraintTop_toTopOf="@+id/imageView"
            app:layout_constraintEnd_toStartOf="@+id/button11"
            app:layout_constraintStart_toEndOf="@+id/button13"
            app:layout_constraintBottom_toTopOf="@+id/button133"
            app:layout_constraintVertical_chainStyle="spread_inside" />

        <Button
            android:id="@+id/button311"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:text="Button"
            app:layout_constraintStart_toStartOf="@+id/imageView"
            app:layout_constraintTop_toBottomOf="@+id/button31"
            app:layout_constraintBottom_toTopOf="@+id/button13"
            app:layout_constraintEnd_toStartOf="@+id/button133"
            app:layout_constraintHorizontal_chainStyle="spread_inside" />

        <Button
            android:id="@+id/button133"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:text="Button"
            app:layout_constraintStart_toEndOf="@+id/button311"
            app:layout_constraintEnd_toStartOf="@+id/button41"
            app:layout_constraintTop_toBottomOf="@+id/button5"
            app:layout_constraintBottom_toTopOf="@+id/button51" />
        <Button
            android:id="@+id/button41"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintEnd_toEndOf="@+id/imageView"
            android:text="Button"
            app:layout_constraintTop_toBottomOf="@+id/button1"
            app:layout_constraintBottom_toTopOf="@+id/button11"
            app:layout_constraintStart_toEndOf="@+id/button133" />

        <Button
            android:id="@+id/button11"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:text="Button"
            app:layout_constraintEnd_toEndOf="@+id/imageView"
            app:layout_constraintBottom_toBottomOf="@+id/imageView"
            app:layout_constraintStart_toEndOf="@+id/button51"
            app:layout_constraintTop_toBottomOf="@id/button41"
            />

        <Button
            android:id="@+id/button13"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:text="Button"
            app:layout_constraintStart_toStartOf="@+id/imageView"
            app:layout_constraintBottom_toBottomOf="@+id/imageView"
            app:layout_constraintTop_toBottomOf="@id/button311"
            app:layout_constraintHorizontal_chainStyle="spread_inside"
            app:layout_constraintEnd_toStartOf="@+id/button51" />

        <Button
            android:id="@+id/button51"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:text="Button"
            app:layout_constraintBottom_toBottomOf="@+id/imageView"
            app:layout_constraintEnd_toStartOf="@+id/button11"
            app:layout_constraintStart_toEndOf="@+id/button13"
            app:layout_constraintTop_toBottomOf="@id/button133"/>
</android.support.constraint.ConstraintLayout>

here is the design and blue print

you can get all the details here about chain and constraint
https://developer.android.com/reference/android/support/constraint/ConstraintLayout.html#Chains

this will work on all device size and orientation

NOTE: i recommend u too add some minHeight to your image view so to avoid to hiding the button but i don't know your requirement but it an noticeable point


来源: stackexchange

问:
time pass algorithm in python
```<code>import time
import random
info = """welcome to contest!..
pls answer question as quick as possible you can
pls enter small letter...\n"""
print(info)
questions = {"2 * 2 ?":"4",
"what is the capital city of turkey?":"ankara",
"what is the king of jungle?":"lion",
"what is the meaning of book in turkish language?":"kitap",
"who is the foundation of turkish government":"atatürk",
"what is the most popular drink in turkey?":"raki",
"pls tell us a hero as comic":"temel"}
correct = 0
wrong = 0
blank = 0
current_time = time.time() #system time
allowed_time = 25 #total time to reply the question

for i in random.sample(list(questions), 5):
     question = questions[i]
     if time.time() < current_time+allowed_time:
         answer = input("1. soru --> {} : ".format(i))
     if answer == question:
         correct += 1
     elif answer == "":
         blank += 1
     else:
         wrong += 1
print()
print("right answer  :", correct)
print("wrong answer :", wrong)
print("blank answer :", blank)
</code>```

Please see my survey code above. It's selecting random 5 question in total time 25 seconds. But, I'd like to make it time option for every single question.
For example, questions must be replied with in ten seconds otherwise change question automatically.

Could you help on how to do that?

答:
The input() function - by its definition - waits for the input infinitely. Probably there is no cross-platform solution for it.

For *nix operating systems you may do this:

Create another thread with the timer which will interrupt the main thread after some time limit.

You may define a function for your input which will do it:

```<code>import thread      # _thread for Python 3.x
import threading

def timed_input(prompt, timeout=25.):
    timer = threading.Timer(timeout, thread.interrupt_main)
    answer = ""
    try:
        timer.start()
        answer = input(prompt)
    except KeyboardInterrupt:
        pass
    timer.cancel()
    return answer
</code>```

and then use it instead of the standard input() function in your code (and of course without your original attempts with the time module).

ContentLicense: CC BY-SA 3.0

Title: time pass algorithm in python

Body:
import time
import random
info = """welcome to contest!..
pls answer question as quick as possible you can
pls enter small letter...\n"""
print(info)
questions = {"2 * 2 ?":"4",
"what is the capital city of turkey?":"ankara",
"what is the king of jungle?":"lion",
"what is the meaning of book in turkish language?":"kitap",
"who is the foundation of turkish government":"atatürk",
"what is the most popular drink in turkey?":"raki",
"pls tell us a hero as comic":"temel"}
correct = 0
wrong = 0
blank = 0
current_time = time.time() #system time
allowed_time = 25 #total time to reply the question

for i in random.sample(list(questions), 5):
     question = questions[i]
     if time.time() < current_time+allowed_time:
         answer = input("1. soru --> {} : ".format(i))
     if answer == question:
         correct += 1
     elif answer == "":
         blank += 1
     else:
         wrong += 1
print()
print("right answer  :", correct)
print("wrong answer :", wrong)
print("blank answer :", blank)

Please see my survey code above. It's selecting random 5 question in total time 25 seconds. But, I'd like to make it time option for every single question.
For example, questions must be replied with in ten seconds otherwise change question automatically.

Could you help on how to do that?

Body:
The input() function - by its definition - waits for the input infinitely. Probably there is no cross-platform solution for it.

For *nix operating systems you may do this:

Create another thread with the timer which will interrupt the main thread after some time limit.

You may define a function for your input which will do it:

import thread      # _thread for Python 3.x
import threading

def timed_input(prompt, timeout=25.):
    timer = threading.Timer(timeout, thread.interrupt_main)
    answer = ""
    try:
        timer.start()
        answer = input(prompt)
    except KeyboardInterrupt:
        pass
    timer.cancel()
    return answer

and then use it instead of the standard input() function in your code (and of course without your original attempts with the time module).


问:
How to index every 1000 number together
I have a table with a 'billnumber' column (INT 11)

billnumber value may changed every 3 or 4 records so if I index a 1M record I will have a 250K index

What I want is anyway to index every 1000 billnumber together
- from 1 to 1000
- from 1001 to 2000

答:
Is there actually a problem?

INDEX(billnumber) is non-unique, this will return 3 or 4 rows without difficulty:

```<code>SELECT ...
    WHERE bill_number = 1234
</code>```

If you want to select 1..1000, simply do

```<code>SELECT ...
    WHERE bill_number BETWEEN 1 AND 1000;
</code>```

Both are efficient.

Keep in mind, a data base table has no order.  To get the rows ordered, you must use ORDER BY.

Meanwhile, INDEXes try to make WHERE and ORDER BY efficient.

Title: How to index every 1000 number together

Body:
Is there actually a problem?

INDEX(billnumber) is non-unique, this will return 3 or 4 rows without difficulty:

SELECT ...
    WHERE bill_number = 1234

If you want to select 1..1000, simply do

SELECT ...
    WHERE bill_number BETWEEN 1 AND 1000;

Both are efficient.

Keep in mind, a data base table has no order.  To get the rows ordered, you must use ORDER BY.

Meanwhile, INDEXes try to make WHERE and ORDER BY efficient.


问:
How many variables are too much for a class?
I want to see if anyone has a better design for a class (class as in OOP) I am writing. We have a script that puts shared folder stats in a CSV file. I am reading that in and putting it in a Share class.

My boss wants to know information like:

Total Number of Files

Total Size of Files

Number of Office Files

Size of Office Files

Number of Exe Files

Size of Exe Files

etc ....

I have a class with variables like $numOfficeFiles, $sizeOfficeFiles, etc. with a ton of get/set methods. Isn't there a better way to do this? What is the general rule if you have a class with a lot of variables/properties?

I think of this as a language agnostic question, but if it matters, I am using PHP.

答: Maybe I didn't understand the goal, but why do you load all the values into memory by using the variables, just to dump them to the csv file (when?). I'd prefer a stateless listener to the directory and writing values immediately to the csv. </p>

OwnerDisplayName: Ben

LastEditorDisplayName: mmyers

ContentLicense: CC BY-SA 2.5


问:
Repeater with HiddenField
I have the following HiddenField within a Repeater labeled "AdminGetAllRPT":

```<code> <asp:Repeater ID="AdminGetAllRPT" runat="server" OnLoad="AdminGetAllRPT_Load">
    <HeaderTemplate>
        <table id="AdminGetAllTBL">
            <tr>
                <td></td>
                <td>Username</td>
                <td>Email Address</td>
                <td>First Name</td>
                <td>Last Name</td>
                <td>Active?</td>
            </tr>
    </HeaderTemplate>
    <ItemTemplate>
       <tr>
           <td>
               <asp:LinkButton ID="AdminEditLnk" runat="server" OnClick="AdminEdit_OnClick">Edit
               <asp:HiddenField ID="editAdminEmail" runat="server" Value='<%# Eval("emailAddress") %>' />
               </asp:LinkButton>
           </td>
           <td><%# Eval("userName") %></td>
           <td><%# Eval("emailAddress") %></td>
           <td><%# Eval("firstName") %></td>
           <td><%# Eval("lastName") %></td>
           <td><%# Eval("isActive") %></td>
       </tr>
    </ItemTemplate>
    <AlternatingItemTemplate>
        <tr class="alternateTemplate">
           <td>
               <asp:LinkButton ID="AdminEditLnk" runat="server" OnClick="AdminEdit_OnClick">Edit
               <asp:HiddenField ID="editAdminEmail" runat="server" Value='<%# Eval("emailAddress") %>' />
               </asp:LinkButton>
           </td>
           <td><%# Eval("userName") %></td>
           <td><%# Eval("emailAddress") %></td>
           <td><%# Eval("firstName") %></td>
           <td><%# Eval("lastName") %></td>
           <td><%# Eval("isActive") %></td>
       </tr>
    </AlternatingItemTemplate>
    <FooterTemplate>
            <tr>
                <td colspan="2"><a href="#">Add Administrator</a></td>
            </tr>
        </table>
    </FooterTemplate>
</asp:Repeater>
</code>```

I have a linkbutton that fires this code:

```<code>protected void AdminEdit_OnClick(object sender, EventArgs e)
{
    HiddenField hf = (HiddenField)AdminGetAllRPT.FindControl("editAdminEmail");
</code>```

but the hf is coming up null. What am I doing wrong?

答:
You need to find the hidden field within a RepeaterItem.</p>

```<code>foreach(var item in AdminGetAllRPT.Items)
{
   var hf = (HiddenField)item.FindControl("editAdminEmail");
}
</code>```

Title: Repeater with HiddenField

Body:
I have the following HiddenField within a Repeater labeled "AdminGetAllRPT":

 <asp:Repeater ID="AdminGetAllRPT" runat="server" OnLoad="AdminGetAllRPT_Load">
    <HeaderTemplate>

                Username
                Email Address
                First Name
                Last Name
                Active?

    </HeaderTemplate>
    <ItemTemplate>

               <asp:LinkButton ID="AdminEditLnk" runat="server" OnClick="AdminEdit_OnClick">Edit
               <asp:HiddenField ID="editAdminEmail" runat="server" Value='<%# Eval("emailAddress") %>' />
               </asp:LinkButton>

           <%# Eval("userName") %>
           <%# Eval("emailAddress") %>
           <%# Eval("firstName") %>
           <%# Eval("lastName") %>
           <%# Eval("isActive") %>

    </ItemTemplate>
    <AlternatingItemTemplate>

               <asp:LinkButton ID="AdminEditLnk" runat="server" OnClick="AdminEdit_OnClick">Edit
               <asp:HiddenField ID="editAdminEmail" runat="server" Value='<%# Eval("emailAddress") %>' />
               </asp:LinkButton>

           <%# Eval("userName") %>
           <%# Eval("emailAddress") %>
           <%# Eval("firstName") %>
           <%# Eval("lastName") %>
           <%# Eval("isActive") %>

    </AlternatingItemTemplate>
    <FooterTemplate>

                Add Administrator

    </FooterTemplate>
</asp:Repeater>

I have a linkbutton that fires this code:

protected void AdminEdit_OnClick(object sender, EventArgs e)
{
    HiddenField hf = (HiddenField)AdminGetAllRPT.FindControl("editAdminEmail");

but the hf is coming up null. What am I doing wrong?

Body:
You need to find the hidden field within a RepeaterItem.

foreach(var item in AdminGetAllRPT.Items)
{
   var hf = (HiddenField)item.FindControl("editAdminEmail");
}


问:
Location Annotation Images
I am currently working on a function where the user can tap on a maps annotation and be taken to another screen which will hold an image of that location. I am using Mapbox and the tapOnCallout function to segue to another view controller (imageLocationViewController) which will hold an image view.

The issue I am facing is letting this imageLocationViewController know which annotation has been clicked and therefore which image should be shown. I am using firebase to hold my data and within the annotation data I have a photoUrl which holds the relevant image.

I am currently able to print the relevant name of the annotation and photo Url when I am segueing. However, once I am within the imageLocation View Controller I believe I lose this data?

Does anybody know how I can pass this data into the new view controller so that I can pass the correct photoUrl into the image view.

This is my current code to segue to the imageLocationViewController.

```<code> func mapView(_ mapView: MGLMapView, tapOnCalloutFor annotation: MGLAnnotation) {

    if let annotation = annotation as? SkateAnnotation {

        self.performSegue(withIdentifier: "SkateImageSegue", sender: annotation.id)

        print("YourAnnotation: \(annotation.photoUrl)")

    }
}
</code>```

Update ** Code for prepare for segue

```<code> override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "EditSaveSpotSegue" {
        let destination = segue.destination as! EditSaveSpotViewController
        destination.parkId = sender as! String
    }
}
</code>```

答:
I would set a local variable whenever your mapView delegate function fires, just before you call performSegue, and then use that variable in prepareForSegue. See below

```<code> var annotationId: String = ""

 func mapView(_ mapView: MGLMapView, tapOnCalloutFor annotation: MGLAnnotation) {

    if let annotation = annotation as? SkateAnnotation {

        annotationId = annotation.id
        self.performSegue(withIdentifier: "SkateImageSegue", sender:self)

        print("YourAnnotation: \(annotation.photoUrl)")

    }
}

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "EditSaveSpotSegue" {
        let destination = segue.destination as! EditSaveSpotViewController
        destination.parkId = annotationId
    }
}
</code>```

Title: Location Annotation Images

Body:
I am currently working on a function where the user can tap on a maps annotation and be taken to another screen which will hold an image of that location. I am using Mapbox and the tapOnCallout function to segue to another view controller (imageLocationViewController) which will hold an image view.

The issue I am facing is letting this imageLocationViewController know which annotation has been clicked and therefore which image should be shown. I am using firebase to hold my data and within the annotation data I have a photoUrl which holds the relevant image.

I am currently able to print the relevant name of the annotation and photo Url when I am segueing. However, once I am within the imageLocation View Controller I believe I lose this data?

Does anybody know how I can pass this data into the new view controller so that I can pass the correct photoUrl into the image view.

This is my current code to segue to the imageLocationViewController.

 func mapView(_ mapView: MGLMapView, tapOnCalloutFor annotation: MGLAnnotation) {

    if let annotation = annotation as? SkateAnnotation {

        self.performSegue(withIdentifier: "SkateImageSegue", sender: annotation.id)

        print("YourAnnotation: \(annotation.photoUrl)")

    }
}

Update ** Code for prepare for segue

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "EditSaveSpotSegue" {
        let destination = segue.destination as! EditSaveSpotViewController
        destination.parkId = sender as! String
    }
}

Body:
I would set a local variable whenever your mapView delegate function fires, just before you call performSegue, and then use that variable in prepareForSegue. See below

 var annotationId: String = ""

 func mapView(_ mapView: MGLMapView, tapOnCalloutFor annotation: MGLAnnotation) {

    if let annotation = annotation as? SkateAnnotation {

        annotationId = annotation.id
        self.performSegue(withIdentifier: "SkateImageSegue", sender:self)

        print("YourAnnotation: \(annotation.photoUrl)")

    }
}

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "EditSaveSpotSegue" {
        let destination = segue.destination as! EditSaveSpotViewController
        destination.parkId = annotationId
    }
}


问:
Python passing user input of name of file to open
I don't understand why something this simple isn't very intuitive.

This is what I have so far:

```<code>    print("Enter name of file on Desktop:")
    filename = sys.stdin.readline()

    directory = os.path.join(os.path.expanduser("~"),"Desktop")
        for subdir, dirs, files in os.walk(directory):
            for file in files:
                if file.startswith(filename):
                    f = open(os.path.join(subdir, file),'r+', encoding="Latin-1")
                    data = f.read()
                    print(data)
                    f.close()
</code>```

Why can't I pass the sys.stdin that was assigned to the variable filename
to the 'if' statement:

```<code>   `if file.startswith(filename):`?
</code>```

I tried:

```<code>    if file.startswith(str(filename)):
    if file.startswith("'" + filename + "'")
    if file.startswith(filename):
</code>```

no options seem to "go through" and no errors pop up.

It just pretends like I didn't pass anything. Any help? Thanks.

答:
A line, whether read from stdin or from a file, includes a newline character. It seems unlikely that any of your filenames end in a newline.

But don't use sys.stdin.readline to get input from the user. Use the appropriately-named input function:

```<code>filename = input("Enter name of file on Desktop:")
</code>```

(Note, in Python 2.x you should use raw_input rather than input.)

Body:
I don't understand why something this simple isn't very intuitive.

This is what I have so far:

    print("Enter name of file on Desktop:")
    filename = sys.stdin.readline()

    directory = os.path.join(os.path.expanduser("~"),"Desktop")
        for subdir, dirs, files in os.walk(directory):
            for file in files:
                if file.startswith(filename):
                    f = open(os.path.join(subdir, file),'r+', encoding="Latin-1")
                    data = f.read()
                    print(data)
                    f.close()

Why can't I pass the sys.stdin that was assigned to the variable filename
to the 'if' statement:

   `if file.startswith(filename):`?

I tried:

    if file.startswith(str(filename)):
    if file.startswith("'" + filename + "'")
    if file.startswith(filename):

no options seem to "go through" and no errors pop up.

It just pretends like I didn't pass anything. Any help? Thanks.

Body:
A line, whether read from stdin or from a file, includes a newline character. It seems unlikely that any of your filenames end in a newline.

But don't use sys.stdin.readline to get input from the user. Use the appropriately-named input function:

filename = input("Enter name of file on Desktop:")

(Note, in Python 2.x you should use raw_input rather than input.)


问:
R: Convert binary categorical variables to long data format
```<code>mydata <- structure(list(id = 1:10, cafe = c(0, 1, 0, 0, 1, 1, 0, 0, 1,
1), playground = c(1, 1, 1, 1, 1, 1, 0, 1, 1, 0), classroom = c(0,
0, 0, 0, 0, 1, 1, 1, 1, 1), gender = structure(c(2L, 2L, 2L,
2L, 2L, 2L, 1L, 2L, 1L, 2L), .Label = c("Female", "Male"), class = "factor"),
    job = structure(c(2L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 1L), .Label = c("Student",
    "Teacher"), class = "factor")), .Names = c("id", "cafe",
"playground", "classroom", "gender", "job"), row.names = c(NA,
-10L), class = "data.frame")

> mydata
   id cafe playground classroom gender     job
1   1    0          1         0   Male Teacher
2   2    1          1         0   Male Student
3   3    0          1         0   Male Teacher
4   4    0          1         0   Male Student
5   5    1          1         0   Male Teacher
6   6    1          1         1   Male Teacher
7   7    0          0         1 Female Teacher
8   8    0          1         1   Male Teacher
9   9    1          1         1 Female Teacher
10 10    1          0         1   Male Student
</code>```

My desired long format data set should look like:

```<code>id      response    gender        job
1     playground      Male    Teacher
2           cafe      Male    Student
2     playground      Male    Student
3     playground      Male    Teacher
...
</code>```

Essentially, the response column corresponds to which of the cafe, playground, and classroom columns have a value of 1. I've looked into several examples here and here, but they do not deal with binary data columns.

答:
We can use do this with tidyverse

```<code>library(tidyverse)
mydata %>%
    gather(response, value, cafe:classroom) %>%
    filter(value==1) %>%
    select(id, response, gender, job)
</code>```

Body:
mydata <- structure(list(id = 1:10, cafe = c(0, 1, 0, 0, 1, 1, 0, 0, 1,
1), playground = c(1, 1, 1, 1, 1, 1, 0, 1, 1, 0), classroom = c(0,
0, 0, 0, 0, 1, 1, 1, 1, 1), gender = structure(c(2L, 2L, 2L,
2L, 2L, 2L, 1L, 2L, 1L, 2L), .Label = c("Female", "Male"), class = "factor"),
    job = structure(c(2L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 1L), .Label = c("Student",
    "Teacher"), class = "factor")), .Names = c("id", "cafe",
"playground", "classroom", "gender", "job"), row.names = c(NA,
-10L), class = "data.frame")

> mydata
   id cafe playground classroom gender     job
1   1    0          1         0   Male Teacher
2   2    1          1         0   Male Student
3   3    0          1         0   Male Teacher
4   4    0          1         0   Male Student
5   5    1          1         0   Male Teacher
6   6    1          1         1   Male Teacher
7   7    0          0         1 Female Teacher
8   8    0          1         1   Male Teacher
9   9    1          1         1 Female Teacher
10 10    1          0         1   Male Student

My desired long format data set should look like:

id      response    gender        job
1     playground      Male    Teacher
2           cafe      Male    Student
2     playground      Male    Student
3     playground      Male    Teacher
...

Essentially, the response column corresponds to which of the cafe, playground, and classroom columns have a value of 1. I've looked into several examples here and here, but they do not deal with binary data columns.

Body:
We can use do this with tidyverse

library(tidyverse)
mydata %>%
    gather(response, value, cafe:classroom) %>%
    filter(value==1) %>%
    select(id, response, gender, job)


问:
What does shell do when we redirect using "<"?
Say I have a program called fstatcheck. It takes one argument from the command line and treat it as file descriptor. It checks the stat information of the file pointed by the file descriptor.

For example:

```<code>$./fstatcheck 1
l = 1
type: other, read: yes
</code>```

Another example:

```<code>$./fstatcheck 3 < foobar.txt
l = 3
Fstat error: Bad file descriptor
</code>```

Questions:

What is the shell doing in the second example?
I can guess that it takes 3 as a file descriptor and starts to analyze the stat, but descriptor 3 is not open. But how does shell treat the redirection?

I assume the shell performs the following algorithm:

```<code>if (fork() == 0) {
  // What does the shell do here?
  execve("fstatcheck", argv, envp);
}
</code>```

Is there any way I can create a file descriptor 3 and let it connect to an open file table which points to foobar.txt file stat by just using the shell command (instead of using C code)?

答:
Let's find out with strace:

```<code>$ strace sh -c 'cat < /dev/null'
[...]
open("/dev/null", O_RDONLY)             = 3
fcntl(0, F_DUPFD, 10)                   = 10
close(0)                                = 0
fcntl(10, F_SETFD, FD_CLOEXEC)          = 0
dup2(3, 0)                              = 0
close(3)                                = 0
[...]
execve("/bin/cat", ["cat"], [/* 28 vars */]) = 0
[...]
</code>```

So in your code, the relevant parts would be:

```<code>if (fork() == 0) {
  int fd = open(filename, O_RDONLY);  // Open the file
  close(0);                           // Close old stdin
  dup2(fd, 0);                        // Copy fd as new stdin
  close(fd);                          // Close the original fd
  execve("fstatcheck", argv, envp);   // Execute
}
</code>```

As for opening another fd, absolutely:

```<code>myprogram 3< file
</code>```

This will open file for reading on fd 3 for the program. < alone is a synonym for 0<.

Body:
Say I have a program called fstatcheck. It takes one argument from the command line and treat it as file descriptor. It checks the stat information of the file pointed by the file descriptor.

For example:

$./fstatcheck 1
l = 1
type: other, read: yes

Another example:

$./fstatcheck 3 < foobar.txt
l = 3
Fstat error: Bad file descriptor

Questions:

What is the shell doing in the second example?
I can guess that it takes 3 as a file descriptor and starts to analyze the stat, but descriptor 3 is not open. But how does shell treat the redirection?

I assume the shell performs the following algorithm:

if (fork() == 0) {
  // What does the shell do here?
  execve("fstatcheck", argv, envp);
}

Is there any way I can create a file descriptor 3 and let it connect to an open file table which points to foobar.txt file stat by just using the shell command (instead of using C code)?

Body:
Let's find out with strace:

$ strace sh -c 'cat < /dev/null'
[...]
open("/dev/null", O_RDONLY)             = 3
fcntl(0, F_DUPFD, 10)                   = 10
close(0)                                = 0
fcntl(10, F_SETFD, FD_CLOEXEC)          = 0
dup2(3, 0)                              = 0
close(3)                                = 0
[...]
execve("/bin/cat", ["cat"], [/* 28 vars */]) = 0
[...]

So in your code, the relevant parts would be:

if (fork() == 0) {
  int fd = open(filename, O_RDONLY);  // Open the file
  close(0);                           // Close old stdin
  dup2(fd, 0);                        // Copy fd as new stdin
  close(fd);                          // Close the original fd
  execve("fstatcheck", argv, envp);   // Execute
}

As for opening another fd, absolutely:

myprogram 3< file

This will open file for reading on fd 3 for the program. < alone is a synonym for 0<.


问:
Problem to connect mysql and Java
I am trying to connect Java code to mySQL. Here is the error that I got. I dont understand why no driver is found since I have put the connector jar at the classpath.

```<code>Class Not Found Exception:
No suitable driver found for jdbc:mysql://localhost/hpdata?user=root&password=12
3456
Exception in thread "main" java.lang.NullPointerException
    at edu.indiana.iucbrf.feature.featurespec.FeatureSpecRDB.open(FeatureSpe
cRDB.java:122)
    at edu.indiana.iucbrf.feature.featurespec.FeatureSpecRDB.<init>(FeatureS
pecRDB.java:66)
    at edu.indiana.iucbrf.domain.componentfactory.RDBComponentFactory.constr
uctProblemFeatureSpecCollection(RDBComponentFactory.java:112)
    at edu.indiana.iucbrf.domain.Domain.<init>(Domain.java:239)
    at edu.indiana.iucbrf.domain.Domain.<init>(Domain.java:197)
    at edu.indiana.iucbrf.examples.honeypotRDBTemplate.HDomainRDB.<in
it>(HDomainRDB.java:56)
    at edu.indiana.iucbrf.examples.hRDBTemplate.HSystemRDB.set
 upDomain(HSystemRDB.java:198)
    at edu.indiana.iucbrf.examples.hRDBTemplate.HSystemRDB.<in
it>(HSystemRDB.java:131)
    at edu.indiana.iucbrf.examples.hRDBTemplate.HTestClassRDB.
main(HTestClassRDB.java:65)
</code>```

Here is my code :

```<code>   private static void flush() {

  Class.forName("com.mysql.jdbc.Driver").newInstance();

    try {

   conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/hpdata?user=root&password=123456");

      } catch (Exception e) {
          System.out.println("Class Not Found Exception:");
          System.out.println(e.getMessage());
      }
</code>```

答:
Try loading the driver before using it by incorporating this line.</p>

```<code>Class.forName("com.mysql.jdbc.Driver")
</code>```

Title: Problem to connect mysql and Java

Body:
I am trying to connect Java code to mySQL. Here is the error that I got. I dont understand why no driver is found since I have put the connector jar at the classpath.

Class Not Found Exception:
No suitable driver found for jdbc:mysql://localhost/hpdata?user=root&password=12
3456
Exception in thread "main" java.lang.NullPointerException
    at edu.indiana.iucbrf.feature.featurespec.FeatureSpecRDB.open(FeatureSpe
cRDB.java:122)
    at edu.indiana.iucbrf.feature.featurespec.FeatureSpecRDB.<init>(FeatureS
pecRDB.java:66)
    at edu.indiana.iucbrf.domain.componentfactory.RDBComponentFactory.constr
uctProblemFeatureSpecCollection(RDBComponentFactory.java:112)
    at edu.indiana.iucbrf.domain.Domain.<init>(Domain.java:239)
    at edu.indiana.iucbrf.domain.Domain.<init>(Domain.java:197)
    at edu.indiana.iucbrf.examples.honeypotRDBTemplate.HDomainRDB.<in
it>(HDomainRDB.java:56)
    at edu.indiana.iucbrf.examples.hRDBTemplate.HSystemRDB.set
 upDomain(HSystemRDB.java:198)
    at edu.indiana.iucbrf.examples.hRDBTemplate.HSystemRDB.<in
it>(HSystemRDB.java:131)
    at edu.indiana.iucbrf.examples.hRDBTemplate.HTestClassRDB.
main(HTestClassRDB.java:65)

Here is my code :

   private static void flush() {

  Class.forName("com.mysql.jdbc.Driver").newInstance();

    try {

   conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/hpdata?user=root&password=123456");

      } catch (Exception e) {
          System.out.println("Class Not Found Exception:");
          System.out.println(e.getMessage());
      }

Body:
Try loading the driver before using it by incorporating this line.

Class.forName("com.mysql.jdbc.Driver")


问:
static variables, libgdx and android pause/resume memory usage
Program example:

```<code>public class main extends ApplicationAdapter
{
    public static int a;
    public static int b;
    public static Player player;

    public void create()
    {
        resume();
    }

    public void render()
    {
    }

    public void resize()
    {
    }

    //pause runs when home button is pressed
    public void pause()
    {
        player = null;
    }

    //resume runs when the program is re-opened
    public void resume()
    {
        a = 10;
        b = 20;
        player = new Player();
    }
}
</code>```

On android, when the home button is pressed, the program is kept in memory and static variables keep their values.  Now when this program is re-opened, does this example create new static variables or just assign values to the old static variables that were in memory?

I'm asking because I have a program that has an issue where pressing home and re-opening the program results in the memory increasing each time and I'm wondering if this could play a role in why that occurs.

updated: Does the player object get removed from memory when it is declared null before getting created again?

答:
The life-cycle of static references is not the same as the life-cycle of your application. In other words, it is possible that multiple instances of your application use the same static variable.

If you set a static variable to null in a method of your application then you will set it to null for all instances of your application running in the same VM. Setting a reference to null, however does not mean that the memory is actually free'd. Only when there are no other references to the same object and the garbage collector is run, then the object will removed.

That said, please note that the pause and resume methods are not the correct methods to do something like that. In fact, for above reasons you should never use the static keyword at all for things that are specific to one instance of your application, unless you are properly managing those static references. For example, libgdx does this behind the scenes by keeping a map of the instances of your application and the resources they use. This allows you to have "managed resources" which are automatically reloaded when needed (which is the default).

In your case that would be over complicating things and it's easier to simply remove the static keyword. This typically also forces you to have a better OO design as well and not use shortcuts like e.g. the singleton pattern which will usually lead to other issues on the long run as well.

Body:
Program example:

public class main extends ApplicationAdapter
{
    public static int a;
    public static int b;
    public static Player player;

    public void create()
    {
        resume();
    }

    public void render()
    {
    }

    public void resize()
    {
    }

    //pause runs when home button is pressed
    public void pause()
    {
        player = null;
    }

    //resume runs when the program is re-opened
    public void resume()
    {
        a = 10;
        b = 20;
        player = new Player();
    }
}

On android, when the home button is pressed, the program is kept in memory and static variables keep their values.  Now when this program is re-opened, does this example create new static variables or just assign values to the old static variables that were in memory?

I'm asking because I have a program that has an issue where pressing home and re-opening the program results in the memory increasing each time and I'm wondering if this could play a role in why that occurs.

updated: Does the player object get removed from memory when it is declared null before getting created again?


问:
Filter list of strings starting with specific keyword
How can I find a string (PartialWord) inside a List (WordList) in Python 2.7?

```<code>PartialWord = "ab"
WordList = ['absail', 'rehab', 'dolphin']
</code>```

A search with a wildcard like: ab*

Where it would ONLY find the word, if it starts with those letters (i.e. the result should only give absail, but not rehab, despite both having 'ab').

The WordList would be a dictionary, which is over 700KB.

答:
you can do :</p>

```<code>>>> WL = ['absail', 'rehab', 'dolphin']
>>> PW="ab"
>>> L=[a for a in WL if a[:len(PW)]==PW]
>>> L
['absail']
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can I find a string (PartialWord) inside a List (WordList) in Python 2.7?

PartialWord = "ab"
WordList = ['absail', 'rehab', 'dolphin']

A search with a wildcard like: ab*

Where it would ONLY find the word, if it starts with those letters (i.e. the result should only give absail, but not rehab, despite both having 'ab').

The WordList would be a dictionary, which is over 700KB.

Body:
you can do :

>>> WL = ['absail', 'rehab', 'dolphin']
>>> PW="ab"
>>> L=[a for a in WL if a[:len(PW)]==PW]
>>> L
['absail']


问:
Sending an http response with Json content using marshallers in Akka Http
I want to send a Http error response with a message in JSON format in the body. I am having trouble using the PredefinedToResponseMarshallers.

I saw an implementation in the Akka docs but I tried a similar thing and it throws a compilation error.

```<code>import argonaut._, Argonaut._
import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.model.headers._
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.marshalling.{ Marshaller, ToResponseMarshaller }

trait Sample extends Marshallers with Directives {
     def login(user: Login): CRIX[HttpResponse] = {
        for {
          verification ← verify(user)
          resp = if (verification) {
            HttpResponse(NoContent, headers = Seq(
              .........
            ))
          }//below is my http Error response
          else Marshal(401 → "It is an Unauthorized Request".asJson).to[HttpResponse]
        } yield resp
      }
    }
</code>```

It gives this compilation error :

```<code>Sample.scala:164: type mismatch;
[error]  found   : Object
[error]  required: akka.http.scaladsl.model.HttpResponse
[error]     } yield resp
[error]             ^
[error] one error found
[error] (http/compile:compileIncremental) Compilation failed
</code>```

I have just started Akka Http so forgive me if it is trivially easy.

TL;DR: I want(examples) to learn how to use ToResponseMarshallers in Akka Http.

答:
Method to[HttpResponse] of negative condition takes on Future[HttpResponse]. At the same time positive condition returns HttpResponse.

Try something like (I assume verify takes on Future[T]):

```<code>for {
  verification <- verify(user)
  resp <- if (verification)
           Future.successful(HttpResponse(NoContent, headers = Seq(.........)) )
         else
           Marshal(401 → "It is an Unauthorized Request".asJson).to[HttpResponse]
} yield resp
</code>```

Body:
I want to send a Http error response with a message in JSON format in the body. I am having trouble using the PredefinedToResponseMarshallers.

I saw an implementation in the Akka docs but I tried a similar thing and it throws a compilation error.

import argonaut._, Argonaut._
import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.model.headers._
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.marshalling.{ Marshaller, ToResponseMarshaller }

trait Sample extends Marshallers with Directives {
     def login(user: Login): CRIX[HttpResponse] = {
        for {
          verification ← verify(user)
          resp = if (verification) {
            HttpResponse(NoContent, headers = Seq(
              .........
            ))
          }//below is my http Error response
          else Marshal(401 → "It is an Unauthorized Request".asJson).to[HttpResponse]
        } yield resp
      }
    }

It gives this compilation error :

Sample.scala:164: type mismatch;
[error]  found   : Object
[error]  required: akka.http.scaladsl.model.HttpResponse
[error]     } yield resp
[error]             ^
[error] one error found
[error] (http/compile:compileIncremental) Compilation failed

I have just started Akka Http so forgive me if it is trivially easy.

TL;DR: I want(examples) to learn how to use ToResponseMarshallers in Akka Http.

Body:
Method to[HttpResponse] of negative condition takes on Future[HttpResponse]. At the same time positive condition returns HttpResponse.

Try something like (I assume verify takes on Future[T]):

for {
  verification <- verify(user)
  resp <- if (verification)
           Future.successful(HttpResponse(NoContent, headers = Seq(.........)) )
         else
           Marshal(401 → "It is an Unauthorized Request".asJson).to[HttpResponse]
} yield resp


问:
Remove or trim carriage return at the end of string

Possible Duplicate:

  Removing carriage return and new-line from the end of a string in c#

How do I remove the carriage return at the end of string.
I have already google out this but I cannot find the code I need.

This is my current code:

return s.Replace("\n", "").Replace("\r", "").Replace("\r\n", "").Trim();

but of course all the occurrence of the old character will be replaced.

I have tried these:

public string trim(string s)
{

```<code>string[] whiteSpace = {"\r", "\n", "\r\n"};

foreach(string ws in whiteSpace)
{
    if (s.EndsWith(ws))
    {
        s = s.Substring(0, s.Length - 1);
    }
}
return s;
</code>```

}

but is not working for me, maybe I miss something or there's a wrong with my code

I have also try using regular expression but I can't get what I need.

I get the string from word document then will be transfered to another docs.

I'll appreciate any help.Tnx

答:
Hi I found a solution in following link. So the credit should go to that author.

Example

However I have customized it to boost the demonstrative capability.

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            String s = "ABCDE\r\n" + "FGHIJ";
            MessageBox.Show(s);
            MessageBox.Show(RemoveAndNewlineLineFeed(s));
        }

        string RemoveAndNewlineLineFeed(string s)
        {
            String[] lf = { "\r", "\n" };
            return String.Join("",s.Split(lf,StringSplitOptions.RemoveEmptyEntries));
        }
    }
}
</code>```

Check this out.

Body:
Possible Duplicate:

  Removing carriage return and new-line from the end of a string in c#

How do I remove the carriage return at the end of string.
I have already google out this but I cannot find the code I need.

This is my current code:

return s.Replace("\n", "").Replace("\r", "").Replace("\r\n", "").Trim();

but of course all the occurrence of the old character will be replaced.

I have tried these:

public string trim(string s)
{

string[] whiteSpace = {"\r", "\n", "\r\n"};

foreach(string ws in whiteSpace)
{
    if (s.EndsWith(ws))
    {
        s = s.Substring(0, s.Length - 1);
    }
}
return s;

}

but is not working for me, maybe I miss something or there's a wrong with my code

I have also try using regular expression but I can't get what I need.

I get the string from word document then will be transfered to another docs.

I'll appreciate any help.Tnx

Body:
Hi I found a solution in following link. So the credit should go to that author.

Example

However I have customized it to boost the demonstrative capability.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            String s = "ABCDE\r\n" + "FGHIJ";
            MessageBox.Show(s);
            MessageBox.Show(RemoveAndNewlineLineFeed(s));
        }

        string RemoveAndNewlineLineFeed(string s)
        {
            String[] lf = { "\r", "\n" };
            return String.Join("",s.Split(lf,StringSplitOptions.RemoveEmptyEntries));
        }
    }
}

Check this out.


问:
Change the background of UISearchBar's textField
I'm struggling with this for a while now. Have searched everywhere but the solution provided only works with objective-c. Which consists in

UITextField *txt = [_searchBar valueForKey:@"_searchField"];

Although some might say that this is protected API and Apple might refuse an app with such code.

So, now I've tried so many ways to work this out and it's not working at all.
My code is this:

```<code>searchBar = UISearchBar(frame: CGRectMake(0, 0, 320.0, 30.0))
searchBar.autoresizingMask = UIViewAutoresizing.FlexibleWidth
searchBar.searchBarStyle = UISearchBarStyle.Minimal
searchBar.layer.cornerRadius = 15
searchBar.delegate = self

searchBar.backgroundColor = UIColor.whiteColor()

if floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1{
    // Load resources for iOS 6.1 or earlier
    searchBar.placeholder = "Search";
} else {
    // The following "hack" (if we can call that) breaks the UI for different size devices.
    // Load resources for iOS 7 or later
    searchBar.placeholder = "Search                                         ";
}
</code>```

This gives me the bizarre result:

While what I want is just the textfield inside the UISearchBar to have a white background and the SearchBar itself have a cornerRadius of, say, 15.

How can I do this?

Thanks so much in advance

答:
In Swift 3:</p>

```<code>if let txfSearchField = searchController.searchBar.value(forKey: "_searchField") as? UITextField {
        txfSearchField.borderStyle = .none
        txfSearchField.backgroundColor = .lightGray
    }
</code>```

Body:
I'm struggling with this for a while now. Have searched everywhere but the solution provided only works with objective-c. Which consists in

UITextField *txt = [_searchBar valueForKey:@"_searchField"];

Although some might say that this is protected API and Apple might refuse an app with such code.

So, now I've tried so many ways to work this out and it's not working at all.
My code is this:

searchBar = UISearchBar(frame: CGRectMake(0, 0, 320.0, 30.0))
searchBar.autoresizingMask = UIViewAutoresizing.FlexibleWidth
searchBar.searchBarStyle = UISearchBarStyle.Minimal
searchBar.layer.cornerRadius = 15
searchBar.delegate = self

searchBar.backgroundColor = UIColor.whiteColor()

if floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1{
    // Load resources for iOS 6.1 or earlier
    searchBar.placeholder = "Search";
} else {
    // The following "hack" (if we can call that) breaks the UI for different size devices.
    // Load resources for iOS 7 or later
    searchBar.placeholder = "Search                                         ";
}

This gives me the bizarre result:

While what I want is just the textfield inside the UISearchBar to have a white background and the SearchBar itself have a cornerRadius of, say, 15.

How can I do this?

Thanks so much in advance

Body:
In Swift 3:

if let txfSearchField = searchController.searchBar.value(forKey: "_searchField") as? UITextField {
        txfSearchField.borderStyle = .none
        txfSearchField.backgroundColor = .lightGray
    }


问:
How can I open a file content placed in a listView?
So, I manage to list all the files that I saved from and edit text into a listview and it works fine. What I want now is to open them into an edit text field. There is my code down below. How can I do that ? I hope you'll help me.

```<code>import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.MimeTypeMap;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.TextView;

import android.app.ListActivity;

public class Tab1 extends Activity
{

    private ToggleButton toggleButton1;
    private ImageView imageViewOn;
    private TextView textReceive;
    private Button refresh;
    EditText txtData;
    int data_block =100;
    private long lastTime = 0;

    private List<String> myList;
    private File file;
    final Handler handler = new Handler() {
    public void handleMessage(Message msg)
        {
            String data = msg.getData().getString("receivedData");
            // Affichage de data
            long t = System.currentTimeMillis();
            if(t-lastTime > 100)
            {

                textReceive.append("\n");
                lastTime = System.currentTimeMillis();
            }
            textReceive.append(data);
        }
    };
       final Handler handlerStatus = new Handler() {
        public void handleMessage(Message msg)
        {
            int co = msg.arg1;
            if(co == 1) {
            } else if(co == 2) {
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tab1);
       ListView listView = (ListView) findViewById(R.id.listView1);
          myList = new ArrayList<String>();

        File directory = Environment.getExternalStorageDirectory();
        file = new File(directory + "/Notes");
        final File list[] = file.listFiles();

        for (int i = 0; i < list.length; i++) {
            myList.add(list[i].getName());

        }
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1, myList);
        listView.setAdapter(adapter); //Set all the file in the list.

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

            }
        });
            }

}
</code>```

答:
Study View.setTag(string) method in android documentation. Then in your adapter class use view.setTag(param) ... Replace the view by the view name which you are returning and Param by file path ...
Next, in onItemClick method call view.getTag(). This will return the file path. Open the file then using its path. I hope you got the point.

Body:
So, I manage to list all the files that I saved from and edit text into a listview and it works fine. What I want now is to open them into an edit text field. There is my code down below. How can I do that ? I hope you'll help me.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.MimeTypeMap;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.TextView;

import android.app.ListActivity;

public class Tab1 extends Activity
{

    private ToggleButton toggleButton1;
    private ImageView imageViewOn;
    private TextView textReceive;
    private Button refresh;
    EditText txtData;
    int data_block =100;
    private long lastTime = 0;

    private List<String> myList;
    private File file;
    final Handler handler = new Handler() {
    public void handleMessage(Message msg)
        {
            String data = msg.getData().getString("receivedData");
            // Affichage de data
            long t = System.currentTimeMillis();
            if(t-lastTime > 100)
            {

                textReceive.append("\n");
                lastTime = System.currentTimeMillis();
            }
            textReceive.append(data);
        }
    };
       final Handler handlerStatus = new Handler() {
        public void handleMessage(Message msg)
        {
            int co = msg.arg1;
            if(co == 1) {
            } else if(co == 2) {
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tab1);
       ListView listView = (ListView) findViewById(R.id.listView1);
          myList = new ArrayList<String>();

        File directory = Environment.getExternalStorageDirectory();
        file = new File(directory + "/Notes");
        final File list[] = file.listFiles();

        for (int i = 0; i < list.length; i++) {
            myList.add(list[i].getName());

        }
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1, myList);
        listView.setAdapter(adapter); //Set all the file in the list.

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

            }
        });
            }

}


答: Make sure mysql-connector-java-<version-number>-bin.jar is in your classpath. If you don't have it, you can download it here.

Title: Problem to connect mysql and Java


问:
AngularJS Promise does not run a digest
I am new to promise concepts and I'm facing a problem while I'm trying to submit a login form.

When the promise is resolved, I want to update the UI by changing the value of a scope variable.

Here is the controller method which is called

```<code> $ctrl.loginForm = function(isValid) {
    // check to make sure the form is completely valid

    if (isValid) {
      LoginService.login($ctrl.user).then(function (value) {
          $ctrl.loginError = false;
          var cookie = value.token;
      }, function (reason) {
          $ctrl.loginError = true;

      });
    }

  };
</code>```

and here is my service method

```<code>  service.login = function(credentials) {
    return new Promise((resolve, reject) => {
      $http.post(AppConst.Settings.apiUrl + 'api-token-auth/',credentials).success((data) => {
        resolve(data);
      }).error((err, status) => {
        reject(err, status);
      });
    });
  };
</code>```

So once the promise is resolved the $ctrl.loginError in the controller changes its value but it does not update on the UI.

I've tried with $apply and it works, but I don't understand why I must use $apply! I thought that the digest cycle starts by default!

Am I doing something wrong?

答:
$http methods return you a promise which is a $q service. So, problem is that you use native promise wrapper which doesn't tell angular's scope to run $apply method.
Change your service to following

```<code>service.login = function(credentials) {
  return $http.post(AppConst.Settings.apiUrl + 'api-token-auth/',credentials);
};
</code>```

Title: AngularJS Promise does not run a digest

Body:
I am new to promise concepts and I'm facing a problem while I'm trying to submit a login form.

When the promise is resolved, I want to update the UI by changing the value of a scope variable.

Here is the controller method which is called

 $ctrl.loginForm = function(isValid) {
    // check to make sure the form is completely valid

    if (isValid) {
      LoginService.login($ctrl.user).then(function (value) {
          $ctrl.loginError = false;
          var cookie = value.token;
      }, function (reason) {
          $ctrl.loginError = true;

      });
    }

  };

and here is my service method

  service.login = function(credentials) {
    return new Promise((resolve, reject) => {
      $http.post(AppConst.Settings.apiUrl + 'api-token-auth/',credentials).success((data) => {
        resolve(data);
      }).error((err, status) => {
        reject(err, status);
      });
    });
  };

So once the promise is resolved the $ctrl.loginError in the controller changes its value but it does not update on the UI.

I've tried with $apply and it works, but I don't understand why I must use $apply! I thought that the digest cycle starts by default!

Am I doing something wrong?

Body:
$http methods return you a promise which is a $q service. So, problem is that you use native promise wrapper which doesn't tell angular's scope to run $apply method.
Change your service to following

service.login = function(credentials) {
  return $http.post(AppConst.Settings.apiUrl + 'api-token-auth/',credentials);
};


问:
Internal Server Error 500 on a blank php file
Sorry if this seems obvious. I'm very new to this, but I've been stuck on this problem for hours even after searching around for similar problems.

I am using the cpanel for managing the files.

Initially, I tried uploading a simple php file, but I kept on getting problems, so I tried an empty php file. This is the error I constantly receive.

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.`

Please contact the server administrator at webmaster@mywebsite.com to inform them of the time this error occurred, and the actions you performed just before this error.

More information about this error may be available in the server error log.

Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.`

After some more searching, I read about the .htaccess file.

I couldn't find the .htaccess, even after enabling "Show Hidden Files (dotfiles)" in the setting, so I created one. An empty one didn't work. I tried to look for what to place there and tried this.

```<code><IfModule mod_rewrite.c>
   RewriteEngine On

   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-l

   RewriteRule ^(.*)$ file.php?url=$1 [QSA,L]
</IfModule>
</code>```

In the error of the cpanel, this is what I receive

:error] [pid xxxx:tid xxxx] (12)Cannot allocate memory: [client xxxx] couldn't create child process: /usr/sbin/suphp for /home3/xxxx/public_html/file.php

I also tried to set the file permission to 644, and the folder to 755, but to no avail.

There were some other posts here about the php.ini and some commands in the command line, but I don't really know where to find them. There was also something about apache? but in the cpanel menu, there was only the apache handlers. Any help would be greatly appreciated! Again, sorry. I'm really new and I have no idea what I'm doing.

If it helps, the web hosting that I am using is zoom.ph (not sure if that is the proper term)

答:
Perhaps you already hit the limit of your allowed resources of your hosting, i found this on zoom.ph:

Fair Use Policy

This is where we really shine! Most hosting providers in the Philippines are resellers who are reselling cheap, traditional VPS services of other hosting firms. Often times, these hosting providers oversell their packages to the extent of offering unbelievable packages with unlimited disk and bandwidth, which means that they are selling resources more than the actual resources allotted to them by their parent hosting provider. This oftentimes results to resource hogging causing "500 Internal Server Error". Looks familiar?

Our system is designed to protect tenants from noisy neighbors which means that if one account turns to be consuming resource more than what is allotted for that account, then only that account will run out of resource but the rest of the tenants will be operating normally.

Although we know that diverse customer base will have different hosting package use cases, we cannot allow one account from disrupting shared services. To prevent this, all use cases are governed by our Acceptable Usage Policy or AUP. This AUP protects users from other kind of abuse that cannot be prevented automatically in a shared server environment.

At ZOOM Hosting, you will get the computing resource that you are paying for. We'll allow you to install whatever account level scripts you want to install provided it does not fall under unacceptable materials in our AUP. That's what we advertised and that's what we are giving you. Our packages are carefully designed to serve the needs of almost all business scales, from micro business to a global enterprise. We host small sites such as dental clinics to medium traffic websites such as those of the NGOs and SMEs to high traffic sites such as government, international remittance firm and ecommerce sites getting global visitors daily

Body:
Sorry if this seems obvious. I'm very new to this, but I've been stuck on this problem for hours even after searching around for similar problems.

I am using the cpanel for managing the files.

Initially, I tried uploading a simple php file, but I kept on getting problems, so I tried an empty php file. This is the error I constantly receive.

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.`

Please contact the server administrator at webmaster@mywebsite.com to inform them of the time this error occurred, and the actions you performed just before this error.

More information about this error may be available in the server error log.

Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.`

After some more searching, I read about the .htaccess file.

I couldn't find the .htaccess, even after enabling "Show Hidden Files (dotfiles)" in the setting, so I created one. An empty one didn't work. I tried to look for what to place there and tried this.

<IfModule mod_rewrite.c>
   RewriteEngine On

   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-l

   RewriteRule ^(.*)$ file.php?url=$1 [QSA,L]
</IfModule>

In the error of the cpanel, this is what I receive

:error] [pid xxxx:tid xxxx] (12)Cannot allocate memory: [client xxxx] couldn't create child process: /usr/sbin/suphp for /home3/xxxx/public_html/file.php

I also tried to set the file permission to 644, and the folder to 755, but to no avail.

There were some other posts here about the php.ini and some commands in the command line, but I don't really know where to find them. There was also something about apache? but in the cpanel menu, there was only the apache handlers. Any help would be greatly appreciated! Again, sorry. I'm really new and I have no idea what I'm doing.

If it helps, the web hosting that I am using is zoom.ph (not sure if that is the proper term)


问:
C# Threading - an array of threads, where each thread contains a form with an image
I have an array of five threads. Each thread contains the same form, each form is put on to the screen in a different location (still working on that method :P).

I am trying to have each form load its contents (an image) before the other forms have finishing being placed. At the moment this works for the first form, but the others are blank or disappear :P

Originally each form would be placed but the method would need to finish before all the forms contents were displayed.

Any help would be appreciated, thanks :)

```<code>public partial class TrollFrm : Form
{
    int number = 0;

    public TrollFrm()
    {
        InitializeComponent();

        startThreads();

    }

    private void TrollFrm_Load(object sender, EventArgs e)
    {

    }

    private void TrollFrm_FormClosing(object sender, FormClosingEventArgs e)
    {
        e.Cancel = true;
    }

    public void startThreads()
    {
        Thread[] ThreadArray = new Thread[5];

        for (int i = 0; i < 5; i++)
        {
            ThreadArray[i] = new Thread(new ThreadStart(createForm));

            ThreadArray[i].Start();
        }
    }

    public void createForm()
    {
        Form frm = new TrollChildFrm();

        Random randomX = new Random();

        Random randomY = new Random();

        number++;

        int xValue;

        int yValue;

        if (number % 2 == 0)    //number is even.
        {
            xValue = (Convert.ToInt32(randomX.Next(1, 1920))) + 200;

            yValue = (Convert.ToInt32(randomY.Next(1, 1080))) - 200;
        }

        else    //number is not even.
        {
            xValue = (Convert.ToInt32(randomX.Next(1, 1920))) - 200;

            yValue = (Convert.ToInt32(randomY.Next(1, 1080))) + 200;
        }

        frm.Show();

        frm.Location = new Point(xValue, yValue);

        Thread.Sleep(1000);
    }
</code>```

答:
I would suggest to use Thread.Sleep(1000) in this manner

Caller section

```<code>    for (int i = 0; i < 5; i++)
    {
        ThreadArray[i] = new Thread(new ThreadStart(createForm));
        ThreadArray[i].Start();
    }
    Thread.Sleep(1000);
</code>```

Also in the method that executing the work for the thread.

```<code>    while(!something)
    {
         Thread.Sleep(1000)
    }
</code>```

Body:
I have an array of five threads. Each thread contains the same form, each form is put on to the screen in a different location (still working on that method :P).

I am trying to have each form load its contents (an image) before the other forms have finishing being placed. At the moment this works for the first form, but the others are blank or disappear :P

Originally each form would be placed but the method would need to finish before all the forms contents were displayed.

Any help would be appreciated, thanks :)

public partial class TrollFrm : Form
{
    int number = 0;

    public TrollFrm()
    {
        InitializeComponent();

        startThreads();

    }

    private void TrollFrm_Load(object sender, EventArgs e)
    {

    }

    private void TrollFrm_FormClosing(object sender, FormClosingEventArgs e)
    {
        e.Cancel = true;
    }

    public void startThreads()
    {
        Thread[] ThreadArray = new Thread[5];

        for (int i = 0; i < 5; i++)
        {
            ThreadArray[i] = new Thread(new ThreadStart(createForm));

            ThreadArray[i].Start();
        }
    }

    public void createForm()
    {
        Form frm = new TrollChildFrm();

        Random randomX = new Random();

        Random randomY = new Random();

        number++;

        int xValue;

        int yValue;

        if (number % 2 == 0)    //number is even.
        {
            xValue = (Convert.ToInt32(randomX.Next(1, 1920))) + 200;

            yValue = (Convert.ToInt32(randomY.Next(1, 1080))) - 200;
        }

        else    //number is not even.
        {
            xValue = (Convert.ToInt32(randomX.Next(1, 1920))) - 200;

            yValue = (Convert.ToInt32(randomY.Next(1, 1080))) + 200;
        }

        frm.Show();

        frm.Location = new Point(xValue, yValue);

        Thread.Sleep(1000);
    }

Body:
I would suggest to use Thread.Sleep(1000) in this manner

Caller section

    for (int i = 0; i < 5; i++)
    {
        ThreadArray[i] = new Thread(new ThreadStart(createForm));
        ThreadArray[i].Start();
    }
    Thread.Sleep(1000);

Also in the method that executing the work for the thread.

    while(!something)
    {
         Thread.Sleep(1000)
    }


问:
Create annotation to a contact entity in Microsoft Dynamics CRM by API
This question is related to Microsoft Dynamics CRM 2015, that I'm calling through API.

I create contact entity:

```<code>POST [organization URI]/api/data/contacts
Content-Type: application/json; charset=utf-8
Accept: application/json
{
    "emailaddress1": "myemail@example.com",
}
</code>```

It works, I see new record, after I log into the panel.
And I can call it through the API:

```<code>[organization URI]/api/data/contacts(f76e4e7c-ea61-e511-80fd-3863bb342b00)
{
  "@odata.context":"[organization URI]/api/data/$metadata#contacts/$entity",
  "@odata.etag":"W/\"460199\"",
  ...
  "contactid":"f76e4e7c-ea61-e511-80fd-3863bb342b00",
  "emailaddress1":"myemail@example.com",
  ....
}
</code>```

Next thing I want to do, is to add annotation record associated with that contact.
Following the guide I call:

```<code>POST [organization URI]/api/data/annotations
Content-Type: application/json; charset=utf-8
Accept: application/json
{
    "notetext": "TEST",
    'contact@odata.bind': 'contacts(f76e4e7c-ea61-e511-80fd-3863bb342b00)'
}
</code>```

But it returns 400 error:

An undeclared property 'contact' which only has property annotations in the payload but no property value was found in the payload. In OData, only declared navigation properties and declared named streams can be represented as properties without values.

When I call:

```<code>POST [organization URI]/api/data/annotations
Content-Type: application/json; charset=utf-8
Accept: application/json
{
    "notetext": "TEST",
}
</code>```

New entity is created, but without a relation to contact.

How to properly compose this POST request? What am I missing here?
I suspect, that contact@odata.bind should be presented somehow different, I've tried contactid@odata.bind, object@odata.bind, objectid@odata.bind - but no effects.

Any ideas?

答:
This answer applies for web api usage:

If the references property has been defined using uppercase letters, you have to use uppercase letters in the property on update and insert. Look at the Schema name in the property list of the primary entity.

Lets say you have an entity called myprefix_entity with a reference to the account entity, and you named it Account, and the schema name became myprefix_AccountId, you would have to refer it as:

```<code>"myprefix_AccountId@odata.bind":"/accounts(f76e4e7c-ea61-e511-80fd-000000000000)"
</code>```

The uppercase A and the uppercase I in myprefix_AccountId matters, if that is how the schema name has been defined.

Body:
This question is related to Microsoft Dynamics CRM 2015, that I'm calling through API.

I create contact entity:

POST [organization URI]/api/data/contacts
Content-Type: application/json; charset=utf-8
Accept: application/json
{
    "emailaddress1": "myemail@example.com",
}

It works, I see new record, after I log into the panel.
And I can call it through the API:

[organization URI]/api/data/contacts(f76e4e7c-ea61-e511-80fd-3863bb342b00)
{
  "@odata.context":"[organization URI]/api/data/$metadata#contacts/$entity",
  "@odata.etag":"W/\"460199\"",
  ...
  "contactid":"f76e4e7c-ea61-e511-80fd-3863bb342b00",
  "emailaddress1":"myemail@example.com",
  ....
}

Next thing I want to do, is to add annotation record associated with that contact.
Following the guide I call:

POST [organization URI]/api/data/annotations
Content-Type: application/json; charset=utf-8
Accept: application/json
{
    "notetext": "TEST",
    'contact@odata.bind': 'contacts(f76e4e7c-ea61-e511-80fd-3863bb342b00)'
}

But it returns 400 error:

An undeclared property 'contact' which only has property annotations in the payload but no property value was found in the payload. In OData, only declared navigation properties and declared named streams can be represented as properties without values.

When I call:

POST [organization URI]/api/data/annotations
Content-Type: application/json; charset=utf-8
Accept: application/json
{
    "notetext": "TEST",
}

New entity is created, but without a relation to contact.

How to properly compose this POST request? What am I missing here?
I suspect, that contact@odata.bind should be presented somehow different, I've tried contactid@odata.bind, object@odata.bind, objectid@odata.bind - but no effects.

Any ideas?

Body:
This answer applies for web api usage:

If the references property has been defined using uppercase letters, you have to use uppercase letters in the property on update and insert. Look at the Schema name in the property list of the primary entity.

Lets say you have an entity called myprefix_entity with a reference to the account entity, and you named it Account, and the schema name became myprefix_AccountId, you would have to refer it as:

"myprefix_AccountId@odata.bind":"/accounts(f76e4e7c-ea61-e511-80fd-000000000000)"

The uppercase A and the uppercase I in myprefix_AccountId matters, if that is how the schema name has been defined.


问:
UISearchBar: changing background color of input field
I'm trying to change the background color of input field of UISearchBar.It's the rounded view where you input text to search, the default color is white. I would like to change it to gray

I tried:

```<code>for (UIView *subView in searchBar.subviews) {
    if ([subView isKindOfClass:NSClassFromString(@"UITextField")]) {
        UITextField *textField = (UITextField *)subView;
        [textField setBackgroundColor:[UIColor grayColor]];
    }
</code>```

But it doesn't work :(

I also tried to insert an image view to TextField but it seems the rounded view is separate from TextField. So, any clues?

答:
Solution in Swift 3:</p>

```<code>if let txfSearchField = searchController.searchBar.value(forKey: "_searchField") as? UITextField {
        txfSearchField.borderStyle = .none
        txfSearchField.backgroundColor = .lightGray
}
</code>```

Body:
I'm trying to change the background color of input field of UISearchBar.It's the rounded view where you input text to search, the default color is white. I would like to change it to gray

I tried:

for (UIView *subView in searchBar.subviews) {
    if ([subView isKindOfClass:NSClassFromString(@"UITextField")]) {
        UITextField *textField = (UITextField *)subView;
        [textField setBackgroundColor:[UIColor grayColor]];
    }

But it doesn't work :(

I also tried to insert an image view to TextField but it seems the rounded view is separate from TextField. So, any clues?

Body:
Solution in Swift 3:

if let txfSearchField = searchController.searchBar.value(forKey: "_searchField") as? UITextField {
        txfSearchField.borderStyle = .none
        txfSearchField.backgroundColor = .lightGray
}


问:
Searching items in cart using laravel crinsane cart
Am trying to get an item from a cart using Crinsane Larvel Shopping Cart.
The documentation talks about using a closure. I do not understand the example provided.

I am using Laravel 5.3, am trying to search items from the shopping cart using information from the Request object. This is my code :

View

```<code>@foreach($cart as $item)
<td>
    <div>
        <a href='{{url("cart?id=$item->id&add=1")}}'> + </a>
        <input type="text" name="qty" value="{{$item->qty}}" autocomplete="off" size="2">
        <a href='{{url("cart?id=$item->id&minus=1")}}'> - </a>
    </div>
</td>
@endforeach
</code>```

Route

```<code>Route::get('/cart', 'CartController@getCart');
</code>```

Controller

```<code>public function getCart(){

    //increment the quantity
    if (Request::get('id') && (Request::get('add')) == 1) {

        $inputItem = Request::get('id');
        //$rowId = Cart::search(['id' => Request::get('id')]);
        $cartItem = Cart::get($rowId);
        Cart::update($rowId, $cartItem->qty+1);
    }

    //decrease the quantity
    if (Request::get('id') && (Request::get('minus')) == 1) {

        $inputItem = Request::get('id');
        //$rowId = Cart::search(['id' => Request::get('id')]);
        $cartItem = Cart::get($rowId);
        Cart::update($rowId, $cartItem->qty-1);
    }

}
</code>```

Cart Content Collection

```<code>`Collection {#318 ▼
  #items: array:2 [▼
    "027c91341fd5cf4d2579b49c4b6a90da" => CartItem {#319 ▼
      +rowId: "027c91341fd5cf4d2579b49c4b6a90da"
      +id: "1"
      +qty: 1
      +name: "Banana"
      +price: 35.0
      +options: CartItemOptions {#320 ▼
        #items: []
      }
      -associatedModel: null
      -taxRate: 21
    }
    "370d08585360f5c568b18d1f2e4ca1df" => CartItem {#321 ▼
      +rowId: "370d08585360f5c568b18d1f2e4ca1df"
      +id: "2"
      +qty: 7
      +name: "Melon"
      +price: 64.0
      +options: CartItemOptions {#322 ▼
        #items: []
      }
      -associatedModel: null
      -taxRate: 21
    }
  ]
}`
</code>```

How can I use Cart::search() to find the Cart item with id 1 (banana)?

答:
You can do it just like this:

```<code>Cart::search(function($cartItem, $rowId) {
    return $cartItem->id == 1;
});
</code>```

The search method is a wrapper for Laravel's filter method on collections.

A Closure is simply a function passed to a function that may or may not receive variables as arguments from the parent function.

If you want to use the $request variable inside of this Closure you will have to use() it:

```<code>Cart::search(function($cartItem, rowId) use($request) {
    return $cartItem->id == $request->id;
});
</code>```

Of course make sure that $request->has('id') before you attempt to access that property.

Body:
Am trying to get an item from a cart using Crinsane Larvel Shopping Cart.
The documentation talks about using a closure. I do not understand the example provided.

I am using Laravel 5.3, am trying to search items from the shopping cart using information from the Request object. This is my code :

View

@foreach($cart as $item)

        id&add=1")}}'> +
        <input type="text" name="qty" value="{{$item->qty}}" autocomplete="off" size="2">
        id&minus=1")}}'> -

@endforeach

Route

Route::get('/cart', 'CartController@getCart');

Controller

public function getCart(){

    //increment the quantity
    if (Request::get('id') && (Request::get('add')) == 1) {

        $inputItem = Request::get('id');
        //$rowId = Cart::search(['id' => Request::get('id')]);
        $cartItem = Cart::get($rowId);
        Cart::update($rowId, $cartItem->qty+1);
    }

    //decrease the quantity
    if (Request::get('id') && (Request::get('minus')) == 1) {

        $inputItem = Request::get('id');
        //$rowId = Cart::search(['id' => Request::get('id')]);
        $cartItem = Cart::get($rowId);
        Cart::update($rowId, $cartItem->qty-1);
    }

}

Cart Content Collection

`Collection {#318 ▼
  #items: array:2 [▼
    "027c91341fd5cf4d2579b49c4b6a90da" => CartItem {#319 ▼
      +rowId: "027c91341fd5cf4d2579b49c4b6a90da"
      +id: "1"
      +qty: 1
      +name: "Banana"
      +price: 35.0
      +options: CartItemOptions {#320 ▼
        #items: []
      }
      -associatedModel: null
      -taxRate: 21
    }
    "370d08585360f5c568b18d1f2e4ca1df" => CartItem {#321 ▼
      +rowId: "370d08585360f5c568b18d1f2e4ca1df"
      +id: "2"
      +qty: 7
      +name: "Melon"
      +price: 64.0
      +options: CartItemOptions {#322 ▼
        #items: []
      }
      -associatedModel: null
      -taxRate: 21
    }
  ]
}`

How can I use Cart::search() to find the Cart item with id 1 (banana)?

Body:
You can do it just like this:

Cart::search(function($cartItem, $rowId) {
    return $cartItem->id == 1;
});

The search method is a wrapper for Laravel's filter method on collections.

A Closure is simply a function passed to a function that may or may not receive variables as arguments from the parent function.

If you want to use the $request variable inside of this Closure you will have to use() it:

Cart::search(function($cartItem, rowId) use($request) {
    return $cartItem->id == $request->id;
});

Of course make sure that $request->has('id') before you attempt to access that property.


问:
JavaScript - Search object property by key and add its value to array
Let's say I have an object like this:

```<code>var object =  {
  "Defender": {
    "player-1868": {
      "birthdate": "1 July 1996",
      "club_country": "IQ",
      "club_id": 171,
      "club_name": "Erbil",
      "forename": "Burhan Jumaah",
      "id": 1868,
      "league_id": 12,
      "league_name": "Iraqi Premier League",
      "name": "Burhan Jumaah",
      "nationality": "iq",
      "nationality_full": "Iraq",
      "position": "Defender",
      "surname": "Razzaq",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    }
  },
  "Goalkeeper": {
    "player-3076": {
      "birthdate": "15 December 1985",
      "club_country": "QA",
      "club_id": 1,
      "club_name": "Lekhwiya",
      "comments": [
        {
          "comment": "xxx",
          "name": "guy tester",
          "photoURL": "http://pbs.twimg.com/profile_images/855450315704979460/RGiq07D7_normal.jpg",
          "time": 1496529030321,
          "user": "y884F42mLCVdld5V5cMeRpl11gJ2"
        }
      ],
      "forename": "Qasem Abdulhamed",
      "id": 3076,
      "league_id": 1,
      "league_name": "Qatar Stars League",
      "name": "Qasem Burhan",
      "nationality": "qa",
      "nationality_full": "Qatar",
      "position": "Goalkeeper",
      "surname": "Burhan",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    },
    "player-3532": {
      "birthdate": "2 April 1992",
      "club_country": "SA",
      "club_id": 18,
      "club_name": "Al Ittihad",
      "forename": "Fawaz",
      "id": 3532,
      "league_id": 2,
      "league_name": "Saudi Professional League",
      "name": "Fawaz Al Qarni",
      "nationality": "sa",
      "nationality_full": "Saudi Arabia",
      "position": "Goalkeeper",
      "surname": "Al Qarni",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    }
  }
};
</code>```

How would I, using lodash, traverse through this object and add every time the property id appears inside an object key of player-xxxxxx, add that value to an array. Essentially, getting all of the player IDs in a single array?

答:
I was able to solve it myself after some more time on it.

var obj = {
  Defender: {
    "player-1868": {
      club_id: 171,
      id: 1868,
      league_id: 12,
      name: "Burhan Jumaah"
    }
  },
  Goalkeeper: {
    "player-3076": {
      club_id: 1,
      id: 3076,
      league_id: 1,
      name: "Qasem Burhan"
    },
    "player-3532": {
      club_id: 18,
      id: 3532,
      league_id: 2,
      name: "Fawaz Al Qarni"
    }
  }
};

function searchForProp(lookingFor, obj, arrYielded) {
  var arr = arrYielded ? arrYielded : [];
  Object.keys(obj).forEach(function(key, idx) {
    if (typeof(obj[key]) === 'object') {
  searchForProp(lookingFor, obj[key], arr);
 } else {
      if (key === 'id') {
    arr.push(obj[key]);
   }
    }
  });
 return arr;
}

var allIDs = searchForProp('id', obj);
console.log(allIDs);```

Body:
Let's say I have an object like this:

var object =  {
  "Defender": {
    "player-1868": {
      "birthdate": "1 July 1996",
      "club_country": "IQ",
      "club_id": 171,
      "club_name": "Erbil",
      "forename": "Burhan Jumaah",
      "id": 1868,
      "league_id": 12,
      "league_name": "Iraqi Premier League",
      "name": "Burhan Jumaah",
      "nationality": "iq",
      "nationality_full": "Iraq",
      "position": "Defender",
      "surname": "Razzaq",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    }
  },
  "Goalkeeper": {
    "player-3076": {
      "birthdate": "15 December 1985",
      "club_country": "QA",
      "club_id": 1,
      "club_name": "Lekhwiya",
      "comments": [
        {
          "comment": "xxx",
          "name": "guy tester",
          "photoURL": "http://pbs.twimg.com/profile_images/855450315704979460/RGiq07D7_normal.jpg",
          "time": 1496529030321,
          "user": "y884F42mLCVdld5V5cMeRpl11gJ2"
        }
      ],
      "forename": "Qasem Abdulhamed",
      "id": 3076,
      "league_id": 1,
      "league_name": "Qatar Stars League",
      "name": "Qasem Burhan",
      "nationality": "qa",
      "nationality_full": "Qatar",
      "position": "Goalkeeper",
      "surname": "Burhan",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    },
    "player-3532": {
      "birthdate": "2 April 1992",
      "club_country": "SA",
      "club_id": 18,
      "club_name": "Al Ittihad",
      "forename": "Fawaz",
      "id": 3532,
      "league_id": 2,
      "league_name": "Saudi Professional League",
      "name": "Fawaz Al Qarni",
      "nationality": "sa",
      "nationality_full": "Saudi Arabia",
      "position": "Goalkeeper",
      "surname": "Al Qarni",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    }
  }
};

How would I, using lodash, traverse through this object and add every time the property id appears inside an object key of player-xxxxxx, add that value to an array. Essentially, getting all of the player IDs in a single array?