问:
Vector erase elements from range
Why programm stopped? That programm compile, but if i run, that he break, and give some message about iterator vector not incrementable.
What is wrong?</p>

```<code>int main()
{
    std::vector<int> vec;
    for (int i = 1; i <= 100; ++i)
        vec.push_back(i);
    for (auto itr = vec.begin() + 5; itr < vec.end() - 5; ++itr)
        vec.erase(itr);
    for (const auto& itr : vec)
            std::cout << itr << std::endl;
    return 0;
}
</code>```

答:
If you want to erase elements in the vector using a for loop you can do so by iterating backwards through the set of elements. For example

```<code>#include <vector>
#include <iostream>
int main()
{
    std::vector<int> vec;
    for (int i = 0; i <= 100; ++i)
        vec.push_back(i);
    for (auto itr = vec.end() - 6; itr > vec.begin() + 4; --itr)
        vec.erase(itr);
    for (const auto& itr : vec)
        std::cout << itr << std::endl;
    return 0;
}
</code>```

As pointed out by 21koizyd, if you want to erase a range of elements you can use the second argument of std::vector::erase to specify an end element.

Title: Vector erase elements from range

Body:
Why programm stopped? That programm compile, but if i run, that he break, and give some message about iterator vector not incrementable.
What is wrong?

int main()
{
    std::vector<int> vec;
    for (int i = 1; i <= 100; ++i)
        vec.push_back(i);
    for (auto itr = vec.begin() + 5; itr < vec.end() - 5; ++itr)
        vec.erase(itr);
    for (const auto& itr : vec)
            std::cout << itr << std::endl;
    return 0;
}

Body:
If you want to erase elements in the vector using a for loop you can do so by iterating backwards through the set of elements. For example

#include <vector>
#include <iostream>
int main()
{
    std::vector<int> vec;
    for (int i = 0; i <= 100; ++i)
        vec.push_back(i);
    for (auto itr = vec.end() - 6; itr > vec.begin() + 4; --itr)
        vec.erase(itr);
    for (const auto& itr : vec)
        std::cout << itr << std::endl;
    return 0;
}

As pointed out by 21koizyd, if you want to erase a range of elements you can use the second argument of std::vector::erase to specify an end element.


来源: stackexchange

问:
Improving Key Search Time Complexity in a Priority Queue Heap
I have a custom Task class which contains a priority value as well as some additional fields, shown below:

```<code>class Task{

    int ID;
    int Priority;
    int Time;

    public Task(int i, int p, int t){
        this.ID = i;
        this.Priority = p;
        this.Time = t;
    }

    //Getters, etc
}
</code>```

These are stored in a max heap by priority, which works fine. However, if I want to find a Task object with a specific ID value, that has to be done in O(n) time due to the linear search (using a basic array of Tasks as a heap):

```<code>public int getTimeOfID(int ID){

    for(int i = 1; i < heapSize+1; i++){
        if (heap[i].getTaskID() == taskID){
            return heap[i].getTimeLeft();
        }
    }

    return -1;
}
</code>```

I've come across several references to a "modified heap" that could be used to improve ID search to O(1) time, but haven't found a concrete implementation example. Is this possible to do, and if so, how would I do it? A Java or pseudcode example would be greatly appreciated, but even just the name of a relevant data structure to begin my search would be helpful. Thanks for any assistance.

EDIT: Additional code added as requested:

```<code>//initial variables

private Task[] heap;
private int heapSize, capacity;
int maxTasksHigh;

//Constructor

public PQ(int maxTasks){
    this.capacity = maxTasks+1;
    heap = new Task[this.capacity];
    heapSize = 0;
    maxTasksHigh = maxTasks;
}

//Addition

public void add(int ID, int time){
    Task newTask = new Task(ID, time);
    heapSize++;
    heap[heapSize] = newTask;
    int target = heapSize;

    heap[target] = newTask;
    reorder(target);
}

//etc.
</code>```

答:
What you can do is add a HashMap to map between an ID and the Task object in the Max Heap.

Then when adding or removing an item you add or remove it from the HashMap<String, Task>. These operations will take O(1) so will not harm the time complexity of the Max Heap. By using the HashMap in addition to the Max Heap you can check if a given ID exists and retrieve its item in O(1).

A word of caution: If you return the reference to the object in the Max Heap through these extra methods an outsider can change the value of the item and therefore break the Max Heap. Solve it by returning a deep clone of the object or by having your Task immutable.

Update after adding code:

Create a new member of the class of HashMap<String, Task> and
initialize it in the constructor.

In the add method check if a.containsKey() for the given Task. If not add it to the Max Heap and to the HashMap.

Update logic of other methods as needed.

ContentLicense: CC BY-SA 3.0

Body:
I have a custom Task class which contains a priority value as well as some additional fields, shown below:

class Task{

    int ID;
    int Priority;
    int Time;

    public Task(int i, int p, int t){
        this.ID = i;
        this.Priority = p;
        this.Time = t;
    }

    //Getters, etc
}

These are stored in a max heap by priority, which works fine. However, if I want to find a Task object with a specific ID value, that has to be done in O(n) time due to the linear search (using a basic array of Tasks as a heap):

public int getTimeOfID(int ID){

    for(int i = 1; i < heapSize+1; i++){
        if (heap[i].getTaskID() == taskID){
            return heap[i].getTimeLeft();
        }
    }

    return -1;
}

I've come across several references to a "modified heap" that could be used to improve ID search to O(1) time, but haven't found a concrete implementation example. Is this possible to do, and if so, how would I do it? A Java or pseudcode example would be greatly appreciated, but even just the name of a relevant data structure to begin my search would be helpful. Thanks for any assistance.

EDIT: Additional code added as requested:

//initial variables

private Task[] heap;
private int heapSize, capacity;
int maxTasksHigh;

//Constructor

public PQ(int maxTasks){
    this.capacity = maxTasks+1;
    heap = new Task[this.capacity];
    heapSize = 0;
    maxTasksHigh = maxTasks;
}

//Addition

public void add(int ID, int time){
    Task newTask = new Task(ID, time);
    heapSize++;
    heap[heapSize] = newTask;
    int target = heapSize;

    heap[target] = newTask;
    reorder(target);
}

//etc.


问:
Whitespace below footer in bootstrap?

I do not know how is that space coming. I do not want fixed footer but only want fixed navbar. My navbar is working fine but footer is having some white space below it.

```<code>body {
  padding-top: 4.5rem;
    min-height:100%;
}
.footer {
  position: relative;
  bottom: 0;
  width: 100%;
  /* Set the fixed height of the footer here */
    left: 0;
  height: 60px;
  line-height: 60px; /* Vertically center the text there */
  background-color: #000000;
}
</code>```

This is the CSS for footer. I am using Bootstrap 4.

```<code><body>
    <div class="container-fluid">
        <nav ..... #code for navbar
        </nav>
    <div class="row justify-content-center">
        <div class="col-6">
           <div class="card">
       ~~~~MY CONTENT~~~
           </div>
         </div>
     </div>
     <div class="row">
        <footer class="footer">
          <div class="container">
            <span class="text-muted">Place sticky footer content here.</span>
          </div>
        </footer></div>
        </div>
    </div>
</code>```

However, when I change the CSS to position:fixed. It works fine but I do not want that. Thank you in advance.

答: Your content element's height is not the screen's height. Therefore your footer will be like that, you can do it with JavaScript or just put content in your container.</p>

Title: Whitespace below footer in bootstrap?

Body:
I do not know how is that space coming. I do not want fixed footer but only want fixed navbar. My navbar is working fine but footer is having some white space below it.

body {
  padding-top: 4.5rem;
    min-height:100%;
}
.footer {
  position: relative;
  bottom: 0;
  width: 100%;
  /* Set the fixed height of the footer here */
    left: 0;
  height: 60px;
  line-height: 60px; /* Vertically center the text there */
  background-color: #000000;
}

This is the CSS for footer. I am using Bootstrap 4.

        <nav ..... #code for navbar

       ~~~~MY CONTENT~~~

            Place sticky footer content here.

However, when I change the CSS to position:fixed. It works fine but I do not want that. Thank you in advance.


问:
What is the difference between a Pane and a Group?
In JavaFX, what is the difference between a Pane and a Group? I can't make out any difference.

答:
Also, note that Group was designed to be very lightweight and doesn't support a lot of styles. For example, you can't set border or background color for the group.

See this answer for more details.

ContentLicense: CC BY-SA 4.0


问:
Android FAB anchor changing when swapping fragments
I have this weird issue that when I replace a fragment and go back to it using the back stack, the FAB is sometimes showing on the upper left of the screen when I anchored it to bottom | end. Its perfectly anchored to bottom | end when just loaded from the activity. How can I solve this? Thanks in advance.

Edit
There's like a 50% chance that it anchors correctly and 50% that it will not.

I have tried manually setting the gravity of the FAB in the java code using this but still does not work.

```<code>FloatingActionButton fab = (FloatingActionButton)view.findViewById(R.id.fab);
        CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
        lp.anchorGravity = Gravity.BOTTOM | GravityCompat.END;
        fab.setLayoutParams(lp);
</code>```

Here's my code for the FAB

```<code><android.support.design.widget.CoordinatorLayout 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"
    android:orientation="vertical"
    tools:context="com.berstek.gradius.fragments.RecordsFragment">

    <!-- TODO: Update blank fragment layout -->
    <LinearLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recview_records0"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"></android.support.v7.widget.RecyclerView>

    </LinearLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_add_white"
        app:layout_anchor="@id/container"
        app:layout_anchorGravity="bottom|end" />

</android.support.design.widget.CoordinatorLayout>
</code>```

答:
One solution that works for me is to call RequestLayout of your view (the one that has the Floating action button) in the OnResume:

```<code>@Override
public void onResume() {
    super.onResume();

    getView().post(new Runnable() {
        @Override
        public void run() {
           getView().requestLayout();
        });
}
</code>```

On Xamarin Android:

```<code>public override void OnResume()
{
    base.OnResume();

    this.View.Post(() => this.View.RequestLayout());
}
</code>```

Hope it helps.

Body:
I have this weird issue that when I replace a fragment and go back to it using the back stack, the FAB is sometimes showing on the upper left of the screen when I anchored it to bottom | end. Its perfectly anchored to bottom | end when just loaded from the activity. How can I solve this? Thanks in advance.

Edit
There's like a 50% chance that it anchors correctly and 50% that it will not.

I have tried manually setting the gravity of the FAB in the java code using this but still does not work.

FloatingActionButton fab = (FloatingActionButton)view.findViewById(R.id.fab);
        CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
        lp.anchorGravity = Gravity.BOTTOM | GravityCompat.END;
        fab.setLayoutParams(lp);

Here's my code for the FAB

<android.support.design.widget.CoordinatorLayout 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"
    android:orientation="vertical"
    tools:context="com.berstek.gradius.fragments.RecordsFragment">

    <LinearLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recview_records0"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"></android.support.v7.widget.RecyclerView>

    </LinearLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_add_white"
        app:layout_anchor="@id/container"
        app:layout_anchorGravity="bottom|end" />

</android.support.design.widget.CoordinatorLayout>

Body:
One solution that works for me is to call RequestLayout of your view (the one that has the Floating action button) in the OnResume:

@Override
public void onResume() {
    super.onResume();

    getView().post(new Runnable() {
        @Override
        public void run() {
           getView().requestLayout();
        });
}

On Xamarin Android:

public override void OnResume()
{
    base.OnResume();

    this.View.Post(() => this.View.RequestLayout());
}

Hope it helps.


问:
Like static resource, is it possible to serve JSPs which are placed out side of webapps
I am using Struts2 in my application with Tomcat.

I am serving static resource of my application by placing them outside of webapps with setting in server.xml.

Now I have to serve JSPs in same way, which are outside of  my context. Is it possible? Or is there any way to achieve this?

答:
You can place JSPs anywhere, but the web application should be aware of the location of the resources.

Since you didn't pointed where exactly you want to store JSPs, I couldn't tell you how to do that. I can say that resources are retrieved via URL in Java, if you can point the server to some URL where resources are stored, then you can access these resources.

If you need to learn more about how in Java accessing resources you can read Location-Independent Access to Resources.

Resources, names, and contexts

A resource is identified by a string consisting of a sequence of
  substrings, delimited by slashes (/), followed by a resource name.
  Each substring must be a valid Java identifier. The resource name is
  of the form shortName or shortName.extension. Both shortName and
  extension must be Java identifiers.

The name of a resource is independent of the Java implementation; in
  particular, the path separator is always a slash (/). However, the
  Java implementation controls the details of how the contents of the
  resource are mapped into a file, database, or other object containing
  the actual resource.

The interpretation of a resource name is relative to a class loader
  instance. Methods implemented by the ClassLoader class do this
  interpretation.

The difference between static resources and dynamic resources:

static resources could be run directly by browser

dynamic resources (like JSPs) are run on server.

Don't confuse loading dynamic resources the same way as static resources, because the static resources could be returned with the response, but dynamic resources should be returned to the server.


问:
TFS 2010: Gated Check-In On Main Branch; Rolling Builds on Dev Branch?
I recently migrated from VSS to TFS 2010 and I've been absolutely loving it, but there's something I haven't yet been able to get working the way I think it should.

GOALS

I'd like to quickly know when a change to Development breaks a build. If we find out after-the-fact, it's no big deal.  Since a lot of check-ins happen throughout the day, we don't want to wait on the build to finish, so it should be asynchronous.

With our Main branch, I'd like to ensure that any time a merge happens into it, we make sure it's not going to break the build.  I want immediate feedback on this. The wait time is fine, since we won't be merging into Main often.

CURRENT SETUP

My solution is under a folder called Main.  I've made a branch off of that called Development.  The workspace I'm working in is tied to the top-level, which includes both Main and Development branches. I tried adjusting my workspace to only point to Development, in case that was the problem. That didn't seem to fix my issue, so I set it back to the way I had it originally -- with both Main and Development.

Within the workspace's Build definitions, I have two definitions defined -- one for the Main branch and another for Development.

The first definition is for building the Main branch.  It has a Gated Check-In trigger and "Items to Build" points to the solution file within Main.

The second definition is for building the solution in the Development branch.  It has a Rolling Builds trigger and "Items to Build" points to the solution file within Development.

RESULT

Currently, when a change is made in Development and a check-in is performed, the gated check-in to Main is triggered.  This not only causes confusion, but it also tends to slow down our overall process.

NEXT STEP

I've looked at some of the TFS guides to branching, general TFS usage, etc. Unfortunately, I haven't yet found a solution to my issue.  If you've run across this issue before, I'd appreciate any suggestions you can give.

答:
I'm not 100% sure at the moment, but the build should be triggered by check-ins into the part of the source tree that is covered by the build definition workspace.

So please have a look into the build definition and see what part of the source tree each build definition gets. Your CI build should only get the Dev branch, the gated build should only get the Main branch.

ContentLicense: CC BY-SA 2.5


问:
Display textview below imageview and not bottom to the parent
I'm working on an Android application and I have an issue with how to display an image in a view. My issue is that I want to display an image and two textViews just below my imageView without aligning their bottom to the parent's. See the wireframe below.

My problem is that when the imageView is taking all the height of the relativeLayout, my textViews are hidden below the parents view.

I have tried a lot of things but nothing is satisfaying...
I have tried to put my imageview in a linearLayout and put a weight on it but if my imageView is smaller I have a blank between the imageView and the textView.

It's complicated because each image I load can have a different size and thus I can't fix a default size to it.
Also, my layout is in a viewPager and when I want to have the Height of the view when I instantiate it on my adapter it returns 0. So I can't compute the size of the elements in the view.

Have you any idea how can I make my layout ?

Maybe in a coordinatorLayout to have circular dependencies (but I don't know how to make it) ?

Here a wireframe of what I want to do with my view: image

And here the code of my layout :

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/layout_photo_detail"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

    <RelativeLayout
        android:id="@+id/relative_photo_detail_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/relative_photo_detail_bottom_infos">

        <ImageView
            android:id="@+id/photo_detail_full_size"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"
            android:scaleType="fitCenter"
            android:src="@drawable/placeholder"
            android:layout_alignParentTop="true"
            android:layout_alignParentStart="true"/>

        <TextView
            android:id="@+id/photo_detail_owner"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/photo_detail_full_size"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="5dp"
            android:textColor="@color/grey"/>
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/relative_photo_detail_bottom_infos"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/relative_photo_detail_image"
        android:padding="10dp">

        <ImageView
            android:id="@+id/photo_detail_delete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:src="@drawable/delete"/>
    </RelativeLayout>
</RelativeLayout>
</code>```

答:
Update your layout structure as below:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_photo_detail"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- TextView 2 -->
    <TextView
        android:id="@+id/photo_detail_owner_description"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginTop="8dp"
        android:padding="8dp"
        android:gravity="center"
        android:textSize="16sp"
        android:textColor="@android:color/holo_red_dark"
        android:text="This is TextView Two"/>

    <!-- TextView 1 -->
    <TextView
        android:id="@+id/photo_detail_owner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/photo_detail_owner_description"
        android:layout_marginTop="8dp"
        android:padding="8dp"
        android:gravity="center"
        android:textSize="18sp"
        android:textColor="@android:color/black"
        android:text="This is TextView One"/>

    <RelativeLayout
        android:id="@+id/relative_photo_detail_image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/photo_detail_owner"
        android:background="@android:color/black">

        <!-- Image -->
        <ImageView
            android:id="@+id/photo_detail_full_size"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:adjustViewBounds="true"
            android:scaleType="fitCenter"
            android:src="@drawable/dummy"
            android:layout_alignParentTop="true"
            android:layout_alignParentStart="true"/>

        <!-- Delete Icon -->
        <ImageView
            android:id="@+id/photo_detail_delete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_margin="16dp"
            android:src="@drawable/delete"/>
    </RelativeLayout>
</RelativeLayout>
</code>```

OUTPUT:

Hope this will help~

Body:
I'm working on an Android application and I have an issue with how to display an image in a view. My issue is that I want to display an image and two textViews just below my imageView without aligning their bottom to the parent's. See the wireframe below.

My problem is that when the imageView is taking all the height of the relativeLayout, my textViews are hidden below the parents view.

I have tried a lot of things but nothing is satisfaying...
I have tried to put my imageview in a linearLayout and put a weight on it but if my imageView is smaller I have a blank between the imageView and the textView.

It's complicated because each image I load can have a different size and thus I can't fix a default size to it.
Also, my layout is in a viewPager and when I want to have the Height of the view when I instantiate it on my adapter it returns 0. So I can't compute the size of the elements in the view.

Have you any idea how can I make my layout ?

Maybe in a coordinatorLayout to have circular dependencies (but I don't know how to make it) ?

Here a wireframe of what I want to do with my view: image

And here the code of my layout :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/layout_photo_detail"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

    <RelativeLayout
        android:id="@+id/relative_photo_detail_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/relative_photo_detail_bottom_infos">

        <ImageView
            android:id="@+id/photo_detail_full_size"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"
            android:scaleType="fitCenter"
            android:src="@drawable/placeholder"
            android:layout_alignParentTop="true"
            android:layout_alignParentStart="true"/>

        <TextView
            android:id="@+id/photo_detail_owner"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/photo_detail_full_size"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="5dp"
            android:textColor="@color/grey"/>
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/relative_photo_detail_bottom_infos"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/relative_photo_detail_image"
        android:padding="10dp">

        <ImageView
            android:id="@+id/photo_detail_delete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:src="@drawable/delete"/>
    </RelativeLayout>
</RelativeLayout>

Body:
Update your layout structure as below:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_photo_detail"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- TextView 2 -->
    <TextView
        android:id="@+id/photo_detail_owner_description"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginTop="8dp"
        android:padding="8dp"
        android:gravity="center"
        android:textSize="16sp"
        android:textColor="@android:color/holo_red_dark"
        android:text="This is TextView Two"/>

    <!-- TextView 1 -->
    <TextView
        android:id="@+id/photo_detail_owner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/photo_detail_owner_description"
        android:layout_marginTop="8dp"
        android:padding="8dp"
        android:gravity="center"
        android:textSize="18sp"
        android:textColor="@android:color/black"
        android:text="This is TextView One"/>

    <RelativeLayout
        android:id="@+id/relative_photo_detail_image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/photo_detail_owner"
        android:background="@android:color/black">

        <!-- Image -->
        <ImageView
            android:id="@+id/photo_detail_full_size"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:adjustViewBounds="true"
            android:scaleType="fitCenter"
            android:src="@drawable/dummy"
            android:layout_alignParentTop="true"
            android:layout_alignParentStart="true"/>

        <!-- Delete Icon -->
        <ImageView
            android:id="@+id/photo_detail_delete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_margin="16dp"
            android:src="@drawable/delete"/>
    </RelativeLayout>
</RelativeLayout>

OUTPUT:

Hope this will help~


问:
In html, how to stretch an image in only one dimension?
Let's say that I want to fit an 10*60 image into a 15*15 container. That is to say, I want to stretch my image so that the width correspond (so that would be an image of 15*90), but I do not want the height to stretch more than the width, so the bottom of my image will not appear.

When I define my html image, I put an width=100% to stretch the width, but what do I say to the height?

Thank  you !

答:
You can simply use a background image and set its background-size property to contain (or cover, depends what you need).

.container {
  background: url(http://via.placeholder.com/350x300) no-repeat center center orange;
  background-size: contain;
  animation-duration: 3s;
  animation-name: changewidth;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

@keyframes changewidth {
  from {
    width: 100px;
    height: 300px
  }
  to {
    width: 300px;
    height: 100px
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container"></div></code>```

Body:
You can simply use a background image and set its background-size property to contain (or cover, depends what you need).

.container {
  background: url(http://via.placeholder.com/350x300) no-repeat center center orange;
  background-size: contain;
  animation-duration: 3s;
  animation-name: changewidth;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

@keyframes changewidth {
  from {
    width: 100px;
    height: 300px
  }
  to {
    width: 300px;
    height: 100px
  }
}

<div class="container"></div>


问:
C++ Binary >> no operator found which takes a right hand operand type of const char error
im trying to learn c++ and can't figure out the reason for this error it seems to match up with my other cout lines that aren't getting any errors </p>

```<code>#include "stdafx.h"
#include <iostream>
using namespace std;

int main()
{
    int number = 42;
    int guess;
    bool notguessed = true;
    while (notguessed);

    cout << "Guess my number";
    cin  >> "Guess";
    if (guess == number)
    {
        cout << "You got it" << endl;
        notguessed = false;
    }
    if (guess < number)
    {
        cout << "To low try again" << endl;
    }
    if (guess > number)
    {
        cout << "To high try again" << endl;
    }

    return 0;
}
</code>```

答:
Make change in line 10
while loop with ;
remove ;
provide some
while(condition){// do code }

Make change in line 13

```<code>you mistakenly ""
it means string
you need variable
String guess;
 cin  >> guess;
</code>```

Body:
im trying to learn c++ and can't figure out the reason for this error it seems to match up with my other cout lines that aren't getting any errors

#include "stdafx.h"
#include <iostream>
using namespace std;

int main()
{
    int number = 42;
    int guess;
    bool notguessed = true;
    while (notguessed);

    cout << "Guess my number";
    cin  >> "Guess";
    if (guess == number)
    {
        cout << "You got it" << endl;
        notguessed = false;
    }
    if (guess < number)
    {
        cout << "To low try again" << endl;
    }
    if (guess > number)
    {
        cout << "To high try again" << endl;
    }

    return 0;
}

Body:
Make change in line 10
while loop with ;
remove ;
provide some
while(condition){// do code }

Make change in line 13

you mistakenly ""
it means string
you need variable
String guess;
 cin  >> guess;


问:
Gradle How to include runtimeOnly dependencies in JavaExec classpath?
Gradle How to include runtimeOnly dependencies in JavaExec classpath?
For example,

subproject foo:

```<code>dependencies {
    runtimeOnly files('libs/hello.jar')
}
</code>```

subproject bar:

```<code>dependencies {
    compile project(':foo')
}

task execHello(type: JavaExec, dependsOn: 'compileJava') {
     classpath = configurations.runtime
     main 'myPackage.Hello'
}
</code>```

the main class myPackage.Hello is defined in the libs/hello.jar that is a runtimeOnly dependency for project foo.

configurations.runtime does not contain the runtimeOnly dependency hello.jar. If I changed the runtimeOnly dependency as api dependency in project foo, it will work.

```<code>classpath = configurations.runtime + configuration.runtimeOnly
</code>```

Error: runtimeOnly can not be explicitly resolved. How to add the hello.jar in the JavaExec classpath?

答: runtime and runtimeOnly are for declaring the dependencies. To use the dependencies you should use the configuration runtimeClasspath as per the docs at https://docs.gradle.org/current/userguide/java_library_plugin.html#sec:java_library_configurations_graph.

Body:
Gradle How to include runtimeOnly dependencies in JavaExec classpath?
For example,

subproject foo:

dependencies {
    runtimeOnly files('libs/hello.jar')
}

subproject bar:

dependencies {
    compile project(':foo')
}

task execHello(type: JavaExec, dependsOn: 'compileJava') {
     classpath = configurations.runtime
     main 'myPackage.Hello'
}

the main class myPackage.Hello is defined in the libs/hello.jar that is a runtimeOnly dependency for project foo.

configurations.runtime does not contain the runtimeOnly dependency hello.jar. If I changed the runtimeOnly dependency as api dependency in project foo, it will work.

classpath = configurations.runtime + configuration.runtimeOnly

Error: runtimeOnly can not be explicitly resolved. How to add the hello.jar in the JavaExec classpath?


问:
select query with multiple conditions on same column
i am having 2 master tables with id

```<code>ingredients master
------
id int
name varchar(50)

product master
-----
id int
pname varchar(50)

product ingredients
----
inId int (fk - ingredients master)
prId int (fk - product master)
</code>```

now scenario is that a product is having below data

ingredients master
  ----- (id , name) {[1 , floor], [2 , salt], [3 , sugar], [4 , oil], [5 , pepper]}

product master
   ----- (id , pname) {[1 , chapati], [2 , pizza bun], [3 , chappati type 2], [4 , pizza bun type 2]}

product ingredients
   ----- (inId , prId) {[1, 1], [2, 1], [3, 1], [1, 2], [2, 2], [3, 2], [4, 2], [1, 3], [2, 3], [3, 3], [1, 4], [2, 4], [3, 4], [4, 4]}

now i want to fire a select query where i could get chapati type 2 as an alternative to chapati or pizza bun type 2 as an alternative to pizza bun

i have tried google and much but cannot come up with a feasible solution.

i just want that which is the exact alternate item of the given item. like chapati and chapati type 2 are completely identical in matter of ingredients. and pizza bun and pizza bun type 2 are completely identical but when i am trying queries it gives all items. as there are some items like floor are common in all.

答:
When 2 products have same ingredients, it is considered as alternative products. Each product has multiple ingredients - multiple rows. It is difficult compare values crossing rows. If each product has only 1 ingredient - combine multiple rows to 1 value, it is a lot easier to identify what products have same ingredients.</p>

```<code>CREATE TABLE #IngredientsMaster
(IngredientId INT
,IngredientName VARCHAR(50)
);
CREATE TABLE #ProductMaster
(ProductId INT
, ProductName VARCHAR(50)
);
CREATE TABLE #ProductIngredients
(IngredientId INT
,ProductId INT
);
INSERT #IngredientsMaster
VALUES(1 , 'floor'), (2 , 'salt'), (3 , 'sugar'), (4 , 'oil'), (5 , 'pepper');

INSERT #ProductMaster
VALUES(1 , 'chapati'), (2 , 'pizza bun'), (3 , 'chappati type 2'), (4 , 'pizza bun type 2');

INSERT #ProductIngredients
VALUES (1, 1), (2, 1), (3, 1), (1, 2), (2, 2), (3, 2), (4, 2), (1, 3), (2, 3), (3, 3), (1, 4), (2, 4), (3, 4), (4, 4)

;WITH cte AS (SELECT pg.ProductId, Productname
                , STUFF((SELECT '-' + cast(t.IngredientId AS VARCHAR(3))
                FROM #ProductIngredients t
                WHERE t.productId = pg.productId
                ORDER BY t.ingredientId
                FOR XML PATH('')
                ), 1, 1, '') AS Ingredients
FROM #ProductIngredients pg
INNER JOIN #IngredientsMaster i
ON i.IngredientId = pg.IngredientId
INNER JOIN #ProductMaster p
ON p.ProductId = pg.ProductId
GROUP BY pg.ProductId, Productname
)
SELECT *
FROM cte cte
WHERE EXISTS (SELECT * FROM cte t WHERE t.Ingredients = cte.Ingredients AND t.ProductId = 2);
</code>```

Body:
i am having 2 master tables with id

ingredients master
------
id int
name varchar(50)

product master
-----
id int
pname varchar(50)

product ingredients
----
inId int (fk - ingredients master)
prId int (fk - product master)

now scenario is that a product is having below data

ingredients master
  ----- (id , name) {[1 , floor], [2 , salt], [3 , sugar], [4 , oil], [5 , pepper]}

product master
   ----- (id , pname) {[1 , chapati], [2 , pizza bun], [3 , chappati type 2], [4 , pizza bun type 2]}

product ingredients
   ----- (inId , prId) {[1, 1], [2, 1], [3, 1], [1, 2], [2, 2], [3, 2], [4, 2], [1, 3], [2, 3], [3, 3], [1, 4], [2, 4], [3, 4], [4, 4]}

now i want to fire a select query where i could get chapati type 2 as an alternative to chapati or pizza bun type 2 as an alternative to pizza bun

i have tried google and much but cannot come up with a feasible solution.

i just want that which is the exact alternate item of the given item. like chapati and chapati type 2 are completely identical in matter of ingredients. and pizza bun and pizza bun type 2 are completely identical but when i am trying queries it gives all items. as there are some items like floor are common in all.

Body:
When 2 products have same ingredients, it is considered as alternative products. Each product has multiple ingredients - multiple rows. It is difficult compare values crossing rows. If each product has only 1 ingredient - combine multiple rows to 1 value, it is a lot easier to identify what products have same ingredients.

CREATE TABLE #IngredientsMaster
(IngredientId INT
,IngredientName VARCHAR(50)
);
CREATE TABLE #ProductMaster
(ProductId INT
, ProductName VARCHAR(50)
);
CREATE TABLE #ProductIngredients
(IngredientId INT
,ProductId INT
);
INSERT #IngredientsMaster
VALUES(1 , 'floor'), (2 , 'salt'), (3 , 'sugar'), (4 , 'oil'), (5 , 'pepper');

INSERT #ProductMaster
VALUES(1 , 'chapati'), (2 , 'pizza bun'), (3 , 'chappati type 2'), (4 , 'pizza bun type 2');

INSERT #ProductIngredients
VALUES (1, 1), (2, 1), (3, 1), (1, 2), (2, 2), (3, 2), (4, 2), (1, 3), (2, 3), (3, 3), (1, 4), (2, 4), (3, 4), (4, 4)

;WITH cte AS (SELECT pg.ProductId, Productname
                , STUFF((SELECT '-' + cast(t.IngredientId AS VARCHAR(3))
                FROM #ProductIngredients t
                WHERE t.productId = pg.productId
                ORDER BY t.ingredientId
                FOR XML PATH('')
                ), 1, 1, '') AS Ingredients
FROM #ProductIngredients pg
INNER JOIN #IngredientsMaster i
ON i.IngredientId = pg.IngredientId
INNER JOIN #ProductMaster p
ON p.ProductId = pg.ProductId
GROUP BY pg.ProductId, Productname
)
SELECT *
FROM cte cte
WHERE EXISTS (SELECT * FROM cte t WHERE t.Ingredients = cte.Ingredients AND t.ProductId = 2);


问:
How to read from Azure Table Storage with a HTTP Trigger PowerShell Azure Function?
The Row Key will be passed in the query string. What is needed in the function to create the "connection string" to the Table Storage?

答:
Assume that you already have an app setting in your Function App named AzureWebJobsStorage that has the connection string to your Table Storage, then to retrieve that value in your PowerShell script, you will add the following,

```<code>$connectionString = $env:AzureWebJobsStorage;
</code>```

However, if you need to just write to Table Storage based on the row key, you could leverage the Table Storage binding that is already supported in Azure Functions.

Let's assume that there is a table named testtable is already created in your Table Storage and that is the table we will need to write to. Then, here's a sample setup that reads the row key from query string of an HTTP-trigger and writes an entry to Table Storage.

function.json:

```<code>{
  "bindings": [
    {
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "authLevel": "anonymous"
    },
    {
      "type": "table",
      "name": "outputTable",
      "tableName": "testtable",
      "connection": "AzureWebJobsStorage",
      "direction": "out"
    },
    {
      "name": "res",
      "type": "http",
      "direction": "out"
    }
  ],
  "disabled": false
}
</code>```

run.ps1:

```<code># POST method: $req
$requestBody = Get-Content $req -Raw | ConvertFrom-Json
$name = $requestBody.name

# GET method: each querystring parameter is its own variable
if ($req_query_name)
{
    $name = $req_query_name
}

Out-File -Encoding Ascii -FilePath $res -inputObject "Hello $name"

Write-Output "Message entity: '$requestBody'"
$entity = [PSObject]@{
  PartitionKey = $requestBody.role
  RowKey = $req_query_rowkey
  AccountId = $requestBody.id
}

$entity | ConvertTo-Json | Out-File -Encoding UTF8 $outputTable
</code>```

Test in Postman:

Log view:

```<code>2017-07-04T17:21:17.095 Function started (Id=775a36ce-9d71-454c-887c-05f08cfdb877)
2017-07-04T17:21:17.314 Message entity: '@{name=Azure; role=admin; id=78910}'
2017-07-04T17:21:17.314 Function completed (Success, Id=775a36ce-9d71-454c-887c-05f08cfdb877, Duration=222ms)
</code>```

Table entry view in Azure Storage Explorer:

Body:
Assume that you already have an app setting in your Function App named AzureWebJobsStorage that has the connection string to your Table Storage, then to retrieve that value in your PowerShell script, you will add the following,

$connectionString = $env:AzureWebJobsStorage;

However, if you need to just write to Table Storage based on the row key, you could leverage the Table Storage binding that is already supported in Azure Functions.

Let's assume that there is a table named testtable is already created in your Table Storage and that is the table we will need to write to. Then, here's a sample setup that reads the row key from query string of an HTTP-trigger and writes an entry to Table Storage.

function.json:

{
  "bindings": [
    {
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "authLevel": "anonymous"
    },
    {
      "type": "table",
      "name": "outputTable",
      "tableName": "testtable",
      "connection": "AzureWebJobsStorage",
      "direction": "out"
    },
    {
      "name": "res",
      "type": "http",
      "direction": "out"
    }
  ],
  "disabled": false
}

run.ps1:

# POST method: $req
$requestBody = Get-Content $req -Raw | ConvertFrom-Json
$name = $requestBody.name

# GET method: each querystring parameter is its own variable
if ($req_query_name)
{
    $name = $req_query_name
}

Out-File -Encoding Ascii -FilePath $res -inputObject "Hello $name"

Write-Output "Message entity: '$requestBody'"
$entity = [PSObject]@{
  PartitionKey = $requestBody.role
  RowKey = $req_query_rowkey
  AccountId = $requestBody.id
}

$entity | ConvertTo-Json | Out-File -Encoding UTF8 $outputTable

Test in Postman:

Log view:

2017-07-04T17:21:17.095 Function started (Id=775a36ce-9d71-454c-887c-05f08cfdb877)
2017-07-04T17:21:17.314 Message entity: '@{name=Azure; role=admin; id=78910}'
2017-07-04T17:21:17.314 Function completed (Success, Id=775a36ce-9d71-454c-887c-05f08cfdb877, Duration=222ms)

Table entry view in Azure Storage Explorer:


问:
insert,update in single button clickin winforms
I am not getting, how to do insert and update of the data in C# WinForms on single button click.</p>

```<code>private void save_Click(object sender, EventArgs e)
    {
        SqlConnection cn = new SqlConnection();
        cn.ConnectionString = "data source=Sai;database=kaur; user id=sa;password=azxc;";

        cn.Open();

        string gen;
        if (radioButton1.Checked == true)
            gen = "Male";
        else
            gen = "Female";
        string clas = null;
        clas = comboBox1.Text;

        string section = null;
        section = comboBox2.Text;
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "insert into studetail values('" + textBox1.Text + "','" + textBox2.Text + "','" + gen + "','" + textBox3.Text + "','" + clas + "','" + section + "')";

        cmd.Connection = cn;

        int n = cmd.ExecuteNonQuery();
        if (n > 0)
            MessageBox.Show(n + " Row Inserted.");
        else
            MessageBox.Show("Insertion failed.");

        SqlDataAdapter da = new SqlDataAdapter("select * from studetail ", cn);
        DataTable dt = new DataTable();
        da.Fill(dt);
        dataGridView1.DataSource = dt;
</code>```

答:
First off the SQL query isn't quite right. It should look something like the following:

```<code>INSERT INTO studetail (columnName1, columnName2, ...columnNameN)
VALUES (value1, value2, ...valueN);
</code>```

Where the column names are the columns where you want data to be inserted, and the values are the data you want inserted into said columns.

You should also be disposing the connection by wrapping the connection within a using statement.

```<code>using(var con = new SqlConnection(connectionString))
{
con.Open();
//rest of code that needs a connection here
}
</code>```

Additionally, you need to be wary of SQL injection. I highly suggest reading this example from the MSDN website. It will give you an example of using an SQL Update and avoiding SQL injection with use of SqlCommand.Paramaters property.

You should also have a Primary Key in your database tables, if you don't already, so you can uniquely identify each record in a table.

To do an update and a save on the same button, you will need to check if a row already exists for the data that is being edited. This when a Primary comes in handy. You will want to check your database to see if a record already exists

```<code>SELECT 1 FROM studetail WHERE <Condition>
</code>```

The WHERE condition will be the way you uniquely identify (a Primary Key) a row in your table. If the rows in the table are uniquely identified, the above SQL statement will return 1 if a value exists, which means you can UPDATE or 0 if no record exists, so you can INSERT

Body:
I am not getting, how to do insert and update of the data in C# WinForms on single button click.

private void save_Click(object sender, EventArgs e)
    {
        SqlConnection cn = new SqlConnection();
        cn.ConnectionString = "data source=Sai;database=kaur; user id=sa;password=azxc;";

        cn.Open();

        string gen;
        if (radioButton1.Checked == true)
            gen = "Male";
        else
            gen = "Female";
        string clas = null;
        clas = comboBox1.Text;

        string section = null;
        section = comboBox2.Text;
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "insert into studetail values('" + textBox1.Text + "','" + textBox2.Text + "','" + gen + "','" + textBox3.Text + "','" + clas + "','" + section + "')";

        cmd.Connection = cn;

        int n = cmd.ExecuteNonQuery();
        if (n > 0)
            MessageBox.Show(n + " Row Inserted.");
        else
            MessageBox.Show("Insertion failed.");

        SqlDataAdapter da = new SqlDataAdapter("select * from studetail ", cn);
        DataTable dt = new DataTable();
        da.Fill(dt);
        dataGridView1.DataSource = dt;

Body:
First off the SQL query isn't quite right. It should look something like the following:

INSERT INTO studetail (columnName1, columnName2, ...columnNameN)
VALUES (value1, value2, ...valueN);

Where the column names are the columns where you want data to be inserted, and the values are the data you want inserted into said columns.

You should also be disposing the connection by wrapping the connection within a using statement.

using(var con = new SqlConnection(connectionString))
{
con.Open();
//rest of code that needs a connection here
}

Additionally, you need to be wary of SQL injection. I highly suggest reading this example from the MSDN website. It will give you an example of using an SQL Update and avoiding SQL injection with use of SqlCommand.Paramaters property.

You should also have a Primary Key in your database tables, if you don't already, so you can uniquely identify each record in a table.

To do an update and a save on the same button, you will need to check if a row already exists for the data that is being edited. This when a Primary comes in handy. You will want to check your database to see if a record already exists

SELECT 1 FROM studetail WHERE <Condition>

The WHERE condition will be the way you uniquely identify (a Primary Key) a row in your table. If the rows in the table are uniquely identified, the above SQL statement will return 1 if a value exists, which means you can UPDATE or 0 if no record exists, so you can INSERT


问:
Why am I getting "undefined is not an object (evaluating PropTypes.shape)"?
Whenever I try to run my iOS simulator, I'm getting that error. All modules are installed, file path to my picture is correct, no errors being thrown within my IDE except for the one that's appearing in my simulator. Picture below of error.

Here's Login.js:

```<code>import React, {Component} from 'react';
import {StyleSheet, TextInput, Text, TouchableOpacity, KeyboardAvoidingView} from 'react-native';

class Login extends Component {
    onButtonPress() {
        this.props.navigator.push({
            id: 'CreateAccount'
        });
    }

    render() {
        return(
            <KeyboardAvoidingView behavior={"padding"} style={styles.container}>
                    <TextInput
                        style={styles.input}
                        returnKeyType={"next"}
                        keyboardType={"email-address"}
                        autoCorrect={false}
                        placeholder={"Email"}
                    />

                    <TextInput
                        style={styles.input}
                        returnKeyType={"go"}
                        placeholder={"Password"}
                        secureTextEntry
                    />

                    <TouchableOpacity>
                        <Text style={styles.loginAndCA}>Login</Text>
                    </TouchableOpacity>

                    <TouchableOpacity onPress={this.onButtonPress.bind(this)}>
                        <Text style={styles.loginAndCA}>Create Account</Text>
                    </TouchableOpacity>
            </KeyboardAvoidingView>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        padding: 20 // Length of text input boxes.
    },

    input: {
        backgroundColor: '#DAE5FF',
        padding: 20,
        paddingHorizontal: 15,
        marginBottom: 10,
        borderRadius: 15
    },

    loginAndCA: {
        fontSize: 40,
        textAlign: 'center',
        color: 'white',
        fontFamily: 'Bodoni 72 Smallcaps',
        paddingHorizontal: 10
    }
});

export default Login;
</code>```

Here's BackGround.js:

```<code>import React, {Component} from 'react';
import {StyleSheet, Image, View, Text} from 'react-native';
import Login from './Login';

class BackGround extends Component {
    render() {
        return(
            <View style={styles.first}>
                <Image style={styles.container} source={require('../pictures/smoke.jpg')}>
                    <View style={styles.second}>
                         <View>
                            <Text style={styles.title}>My App</Text>
                         </View>
                        <Login/>
                    </View>
                </Image>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        width: null,
        height: null,
        backgroundColor: 'rgba(0,0,0,0)'
    },

    first: {
        flex: 1
    },

    second: {
       paddingTop: 290 // Moves both <TextInput> boxes down.
    },

    title: {
        fontSize: 34,
        textAlign: 'center',
        justifyContent: 'center',
        flexDirection: 'row',
        fontFamily: 'Bodoni 72'
    }

    // movementTitle: {
    //     paddingBottom: 34
    // }
});

export default BackGround;
</code>```

Here's CreateAccount.js:

```<code>import React, {Component} from 'react';
import {Text} from 'react-native';

class CreateAccount extends Component {
    render() {
        return(
            <Text>Must get to this page</Text>
        );
    }
}

export default CreateAccount;
</code>```

Here's index.ios.js:

```<code>import React, {Component} from 'react';
import {View, StyleSheet, AppRegistry} from 'react-native';
import {Navigator} from 'react-native-deprecated-custom-components';
import BackGround from './components/BackGround';
import Login from "./components/Login";
import CreateAccount from "./components/CreateAccount";

export default class App extends Component {
    render() {
        return(
            <View style={styles.back}>
              <BackGround/>
              <Navigator
                  initialRoute={{id: 'Login'}}
                  renderScene={this.navigatorRenderScene}
              />
            </View>
        );
    }

    navigatorRenderScene() {
        _navigator = navigator;
        switch(route.id) {
            case 'Login':
                return (<Login navigator={navigator} title="Login"/>);
            case 'CreateAccount':
                return (<CreateAccount navigator={navigator} title="Create Account" />);
        }
    }
}

const styles = StyleSheet.create({
    back: {
        flex: 1
    }
});

AppRegistry.registerComponent('dendroApp', () => dendroApp);
</code>```

答:
It seems PropTypes is undefined. I don't see it declared anywhere in your code. You have to import it via a separate module as shown in the documents: PropTypes.

Update:

Perhaps a library you are using is using the now deprecated/non-supported React.PropTypes. I recommend using a more up to date library or actually going into the library and updating the package so it uses the new PropTypes from the separate package instead of React.PropTypes. This should fix your problem

Body:
Whenever I try to run my iOS simulator, I'm getting that error. All modules are installed, file path to my picture is correct, no errors being thrown within my IDE except for the one that's appearing in my simulator. Picture below of error.

Here's Login.js:

import React, {Component} from 'react';
import {StyleSheet, TextInput, Text, TouchableOpacity, KeyboardAvoidingView} from 'react-native';

class Login extends Component {
    onButtonPress() {
        this.props.navigator.push({
            id: 'CreateAccount'
        });
    }

    render() {
        return(
            <KeyboardAvoidingView behavior={"padding"} style={styles.container}>
                    <TextInput
                        style={styles.input}
                        returnKeyType={"next"}
                        keyboardType={"email-address"}
                        autoCorrect={false}
                        placeholder={"Email"}
                    />

                    <TextInput
                        style={styles.input}
                        returnKeyType={"go"}
                        placeholder={"Password"}
                        secureTextEntry
                    />

                    <TouchableOpacity>
                        <Text style={styles.loginAndCA}>Login</Text>
                    </TouchableOpacity>

                    <TouchableOpacity onPress={this.onButtonPress.bind(this)}>
                        <Text style={styles.loginAndCA}>Create Account</Text>
                    </TouchableOpacity>
            </KeyboardAvoidingView>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        padding: 20 // Length of text input boxes.
    },

    input: {
        backgroundColor: '#DAE5FF',
        padding: 20,
        paddingHorizontal: 15,
        marginBottom: 10,
        borderRadius: 15
    },

    loginAndCA: {
        fontSize: 40,
        textAlign: 'center',
        color: 'white',
        fontFamily: 'Bodoni 72 Smallcaps',
        paddingHorizontal: 10
    }
});

export default Login;

Here's BackGround.js:

import React, {Component} from 'react';
import {StyleSheet, Image, View, Text} from 'react-native';
import Login from './Login';

class BackGround extends Component {
    render() {
        return(
            <View style={styles.first}>
                <Image style={styles.container} source={require('../pictures/smoke.jpg')}>
                    <View style={styles.second}>
                         <View>
                            <Text style={styles.title}>My App</Text>
                         </View>
                        <Login/>
                    </View>
                </Image>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        width: null,
        height: null,
        backgroundColor: 'rgba(0,0,0,0)'
    },

    first: {
        flex: 1
    },

    second: {
       paddingTop: 290 // Moves both <TextInput> boxes down.
    },

    title: {
        fontSize: 34,
        textAlign: 'center',
        justifyContent: 'center',
        flexDirection: 'row',
        fontFamily: 'Bodoni 72'
    }

    // movementTitle: {
    //     paddingBottom: 34
    // }
});

export default BackGround;

Here's CreateAccount.js:

import React, {Component} from 'react';
import {Text} from 'react-native';

class CreateAccount extends Component {
    render() {
        return(
            <Text>Must get to this page</Text>
        );
    }
}

export default CreateAccount;

Here's index.ios.js:

import React, {Component} from 'react';
import {View, StyleSheet, AppRegistry} from 'react-native';
import {Navigator} from 'react-native-deprecated-custom-components';
import BackGround from './components/BackGround';
import Login from "./components/Login";
import CreateAccount from "./components/CreateAccount";

export default class App extends Component {
    render() {
        return(
            <View style={styles.back}>
              <BackGround/>
              <Navigator
                  initialRoute={{id: 'Login'}}
                  renderScene={this.navigatorRenderScene}
              />
            </View>
        );
    }

    navigatorRenderScene() {
        _navigator = navigator;
        switch(route.id) {
            case 'Login':
                return (<Login navigator={navigator} title="Login"/>);
            case 'CreateAccount':
                return (<CreateAccount navigator={navigator} title="Create Account" />);
        }
    }
}

const styles = StyleSheet.create({
    back: {
        flex: 1
    }
});

AppRegistry.registerComponent('dendroApp', () => dendroApp);


问:
Spring aop, unbound pointcut parameter
Im getting this error taht i dont really understand:

```<code>unbound pointcut parameter auditable
</code>```

following code:

```<code>@Aspect
public class TestAspect {

    @Before(value = "@annotation(Action)")
    public void audit(JoinPoint joinPoint, Action auditable) {
        System.out.println(auditable);
    }
}

 @Action(ActionType.FAST)
    public static void resolveFast(String name){
        System.out.println(name);
    }

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Action {

    ActionType value();
    boolean withArgs() default false;
}

public enum ActionType {
    FAST, SLOW
}
</code>```

the problem occurs on @Before annotation, these are my first steps in aop...

答:
try reference code</p>

```<code>@Before("execution(public String com.captaindebug.audit.controller.*Controller.*(..)) && @annotation(auditAnnotation)")
    public void auditScreen(JoinPoint joinPoint,Audit auditAnnotation) {...}
</code>```

Title: Spring aop, unbound pointcut parameter

Body:
Im getting this error taht i dont really understand:

unbound pointcut parameter auditable

following code:

@Aspect
public class TestAspect {

    @Before(value = "@annotation(Action)")
    public void audit(JoinPoint joinPoint, Action auditable) {
        System.out.println(auditable);
    }
}

 @Action(ActionType.FAST)
    public static void resolveFast(String name){
        System.out.println(name);
    }

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Action {

    ActionType value();
    boolean withArgs() default false;
}

public enum ActionType {
    FAST, SLOW
}

the problem occurs on @Before annotation, these are my first steps in aop...

Body:
try reference code

@Before("execution(public String com.captaindebug.audit.controller.*Controller.*(..)) && @annotation(auditAnnotation)")
    public void auditScreen(JoinPoint joinPoint,Audit auditAnnotation) {...}


问:
"Connect failed: Access denied for user 'root'@'localhost' (using password: YES)" from php function
I wrote some function used by a php webpage, in order to interact with a mysql database. When I test them on my server I get this error:

```<code>"Connect failed: Access denied for user 'root'@'localhost' (using password: YES)"
</code>```

I am able to use them on my pc (using XAMPP) and I can navigate through the tables of the database using the command line in the server. However, the webpage fails to connect. I've checked the password but with no results. It's correct (otherwise I could not log in to mysql from the command line).

The call of the function is the following:

```<code>$conn = new mysqli("localhost", "root", "password", "shop");
</code>```

Do I have to set something in my server? Thanks

Edit:
PHP version 5.3.3-7+squeeze1
mysql version:  5.1.49-3
both on debian

答:
Most likely it is not identifying your user properly.  root@localhost.
Select the Mysql version your MAMP is using.

/Applications/MAMP/Library/bin/mysqldump -uroot -p db_name > test_db_dump.sql

I actually wrote an alias on my computer so I don't have to remember how to get to the bin directory.

alias mysqldumpMAMP='/Applications/MAMP/Library/bin/mysqldump'

Which allows me to run this:

mysqldumpMAMP -uroot -p db_name > test_db_dump.sql

You can save an alias in your bash profile ~/.bash_profile or ~/.bash_rc

OwnerDisplayName: Francesco

Body:
I wrote some function used by a php webpage, in order to interact with a mysql database. When I test them on my server I get this error:

"Connect failed: Access denied for user 'root'@'localhost' (using password: YES)"

I am able to use them on my pc (using XAMPP) and I can navigate through the tables of the database using the command line in the server. However, the webpage fails to connect. I've checked the password but with no results. It's correct (otherwise I could not log in to mysql from the command line).

The call of the function is the following:

$conn = new mysqli("localhost", "root", "password", "shop");

Do I have to set something in my server? Thanks

Edit:
PHP version 5.3.3-7+squeeze1
mysql version:  5.1.49-3
both on debian


问:
Disk Space Check in Powershell
I am currently checking disk space size using power shell but was wondering how I can amend the below to add a percentage of space left?

```<code>Format-Table DeviceId, MediaType, @{n="Size";e={[math]::Round($_.Size/1MB,2)}},@{n="FreeSpace";e={[math]::Round($_.FreeSpace/1MB,2)}}
</code>```

I have tried to do it by changing the math but no luck.

```<code>gwmi win32_logicaldisk  -Computername PCNAME| Format-Table DeviceId, MediaType, @{n="Size";e={[math]::Round($_.Size/1MB,2)}},@{n="FreeSpace" (%);e={[math]::Round($_.FreeSpace/$_.Size*100,2)}}|Out-File c:\PMC\Disk\OutPut\Newcastle.txt
</code>```

This just returns an error.

答:
Here's part of a script I have written that may help you:</p>

```<code>If (Test-Path 'C:')
{
    $CDisk = GWMI Win32_LogicalDisk -Filter "DeviceID='C:'"
    $CDisk = @{'Size'      = [Math]::Round($CDisk.Size / 1GB);
               'FreeSpace' = [Math]::Round($CDisk.FreeSpace / 1GB)}
    $CDisk.Add('Usage', ($CDisk.Size - $CDisk.FreeSpace))
    $CDisk.Add('PercentUsage', [Math]::Round(($CDisk.Usage / $CDisk.Size) * 100))

    "C: drive free space: $($CDisk.FreeSpace)GB"
    "C: drive capacity:   $($CDisk.Size)GB"
    '--------------------------------'
    "Disk usage:          $($CDisk.Usage)GB ($($CDisk.PercentUsage)%)"
}
</code>```

Title: Disk Space Check in Powershell

Body:
I am currently checking disk space size using power shell but was wondering how I can amend the below to add a percentage of space left?

Format-Table DeviceId, MediaType, @{n="Size";e={[math]::Round($_.Size/1MB,2)}},@{n="FreeSpace";e={[math]::Round($_.FreeSpace/1MB,2)}}

I have tried to do it by changing the math but no luck.

gwmi win32_logicaldisk  -Computername PCNAME| Format-Table DeviceId, MediaType, @{n="Size";e={[math]::Round($_.Size/1MB,2)}},@{n="FreeSpace" (%);e={[math]::Round($_.FreeSpace/$_.Size*100,2)}}|Out-File c:\PMC\Disk\OutPut\Newcastle.txt

This just returns an error.

Body:
Here's part of a script I have written that may help you:

If (Test-Path 'C:')
{
    $CDisk = GWMI Win32_LogicalDisk -Filter "DeviceID='C:'"
    $CDisk = @{'Size'      = [Math]::Round($CDisk.Size / 1GB);
               'FreeSpace' = [Math]::Round($CDisk.FreeSpace / 1GB)}
    $CDisk.Add('Usage', ($CDisk.Size - $CDisk.FreeSpace))
    $CDisk.Add('PercentUsage', [Math]::Round(($CDisk.Usage / $CDisk.Size) * 100))

    "C: drive free space: $($CDisk.FreeSpace)GB"
    "C: drive capacity:   $($CDisk.Size)GB"
    '--------------------------------'
    "Disk usage:          $($CDisk.Usage)GB ($($CDisk.PercentUsage)%)"
}


问:
How to create Triangle shaped drawable?
I'm trying to draw a triangle shape in my XML layout.

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <rotate
            android:fromDegrees="45"
            android:pivotX="135%"
            android:pivotY="1%"
            android:toDegrees="45">
            <shape android:shape="rectangle">
                <solid android:color="@color/red" />
            </shape>
        </rotate>
    </item>
</layer-list>
</code>```

My expectation is to build my drawable like below image's top right corner.
I have to add this drawable in list item.

答:
You can try this,

```<code>    <?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item >
        <rotate
            android:fromDegrees="-45"
            android:pivotX="0%"
            android:pivotY="-45%">
            <shape android:shape="rectangle">
                <solid android:color="#ff0" />
            </shape>
        </rotate>
    </item>
</layer-list>
</code>```

example:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <View
        android:layout_width="100dp"
        android:background="@drawable/ssampl"
        android:layout_height="100dp">

    </View>
</LinearLayout>
</code>```

Title: How to create Triangle shaped drawable?

Body:
I'm trying to draw a triangle shape in my XML layout.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <rotate
            android:fromDegrees="45"
            android:pivotX="135%"
            android:pivotY="1%"
            android:toDegrees="45">
            <shape android:shape="rectangle">
                <solid android:color="@color/red" />
            </shape>
        </rotate>
    </item>
</layer-list>

My expectation is to build my drawable like below image's top right corner.
I have to add this drawable in list item.

Body:
You can try this,

    <?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item >
        <rotate
            android:fromDegrees="-45"
            android:pivotX="0%"
            android:pivotY="-45%">
            <shape android:shape="rectangle">
                <solid android:color="#ff0" />
            </shape>
        </rotate>
    </item>
</layer-list>

example:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <View
        android:layout_width="100dp"
        android:background="@drawable/ssampl"
        android:layout_height="100dp">

    </View>
</LinearLayout>


问:
How to Implement credit card and paypal transactions like fiverr in laravel
I want to integrate transactions like in fiverr or upwork in my laravel website. I have tried braintree but that only helps in checkouts. I want to store the payments in my application and then send them to a bank account or paypal when the work is done just like fiverr or upwork</p>

答:
Your requirement is to perform the transaction (send the payment to a bank/paypal) and create a records for your system, that the particular transaction happend, isn't it ?
If it's the case, if you are to use Paypal, the best possible way is to read the paymentID and payerID from the session when the transaction is complete (using the payment gateway) and locally (in your application) perform an insert query to your table with the data been extracted with any other system specific additional details you may need to add to you record.
If you use the following,
https://github.com/net-shell/laravel-paypal
you can easily modify the getDone() for this insertion.  </p>


问:
regular expression: match any word until first space
I have the following line:

```<code>hshd    household   8/29/2007   LB
</code>```

I want to match anything that comes before the first space (whitespace).  So, in this case, I want to get back

```<code>hshd
</code>```

答: I think, that will be good solution: /\S\w*/

Body:
I have the following line:

hshd    household   8/29/2007   LB

I want to match anything that comes before the first space (whitespace).  So, in this case, I want to get back

hshd


问:
pass value to next page
I have a php page (search.php) which has a link to another php page. (reserve.php). I want to

```<code>  1. pass the link text to the next page
  2. display that link text in a input box
</code>```

Please tell me how should I write the proper coding for the above tasks.

search.php

```<code><a href="Reserve.php"><?php echo $row['AccNo'];?></a>
</code>```

答:
You can use _GET to accomplish that:

```<code><a href="Reserve.php?accno=<?php echo $row['AccNo']?>"><?php echo $row['AccNo'];?></a>
</code>```

In the new page, the variable value is in the variable $_GET['accno']. To display that text in an input box, simply use echo $_GET['accno'].

Note though that the text will appear in the URL and hence can be altered easily. Depending on the purpose you're using this for, you might want to introduce additional checks, etc. in the new page.

Title: pass value to next page

Body:
I have a php page (search.php) which has a link to another php page. (reserve.php). I want to

  1. pass the link text to the next page
  2. display that link text in a input box

Please tell me how should I write the proper coding for the above tasks.

search.php

<?php echo $row['AccNo'];?>

Body:
You can use _GET to accomplish that:

<a href="Reserve.php?accno=<?php echo $row['AccNo']?>"><?php echo $row['AccNo'];?></a>

In the new page, the variable value is in the variable $_GET['accno']. To display that text in an input box, simply use echo $_GET['accno'].

Note though that the text will appear in the URL and hence can be altered easily. Depending on the purpose you're using this for, you might want to introduce additional checks, etc. in the new page.


问:
Curl return empty in php
```<code>    $loginUrl = 'http://mp3.zing.vn/json/song/get-source/ZmJmTknNCBmLNzHtZbxtvmLH';
    $agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL,$loginUrl);
    curl_setopt($ch, CURLOPT_USERAGENT, $agent);
    $result=curl_exec($ch);
    curl_close($ch);
    var_dump(json_decode($result));
</code>```

I have a problem to get the data using curl operation. If i use the url only in my browser then it returns the data but here i using var_dump its null. I have consult some post in stackoverflow but i cant sovle this problem.

Where i do some mistake, please help my. Thanks

答:
The URL is invalid, i.e. the path mentioned as the variable $loginURL doesnot exist.</p>

```<code>loginUrl = 'http://mp3.zing.vn/json/song/get-source/ZmJmTknNCBmLNzHtZbxtvmLH';
</code>```

Title: Curl return empty in php

Body:
    $loginUrl = 'http://mp3.zing.vn/json/song/get-source/ZmJmTknNCBmLNzHtZbxtvmLH';
    $agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL,$loginUrl);
    curl_setopt($ch, CURLOPT_USERAGENT, $agent);
    $result=curl_exec($ch);
    curl_close($ch);
    var_dump(json_decode($result));

I have a problem to get the data using curl operation. If i use the url only in my browser then it returns the data but here i using var_dump its null. I have consult some post in stackoverflow but i cant sovle this problem.

Where i do some mistake, please help my. Thanks

Body:
The URL is invalid, i.e. the path mentioned as the variable $loginURL doesnot exist.

loginUrl = 'http://mp3.zing.vn/json/song/get-source/ZmJmTknNCBmLNzHtZbxtvmLH';


问:
Convert Uncommon Date Format
Is there an easy way to transform this string into a meaningful date format?

date <- "Tue Apr 04 10:18:33 +0000 2017"

Right now I would use some regex and then the lubridate package. But I guess there is a less complicated way.

答:
Try this:</p>

```<code>as.POSIXct(date, format = "%a %b %d %H:%M:%S %z %Y")
</code>```

Title: Convert Uncommon Date Format

Body:
Try this:

as.POSIXct(date, format = "%a %b %d %H:%M:%S %z %Y")


问:
Spring Integration - ActiveMQ to Kafka
I am currently trying to write an adapter which will consume messages from ActiveMQ and publish it to Kafka.

I am thinking of using spring integration to integrate these two messaging systems.

My problem is that my application will not maintain registry of the Models using which many applications will publish the records to activeMQ. I want to receive these javax jms message and want to perform some transformation like adding jmscorrelationId into kafka message.

ALso, another requirement is to send acknowledgement to active mq only when kafka send/publish is successfull.

Can ack be send back to activemq using spring integration?

Will spring integration be a good option?

Kindly note my tech architect is not in favor of using Camel/Mule. Also, he does not want to use Kafka Connect as i was planning to use Kafka connect source.

Please suggest.

答:
The Spring Integration Kafka extension project has a sync mode for publishing, which will block the thread until Kafka confirms delivery (or throw an exception on a failure).

The JMS inbound gateway can be used to return a reply to a JMS queue.

You can add transformers (or whatever) in the flow to modify the message.

Title: Spring Integration - ActiveMQ to Kafka


问:
Using OpenMP (libgomp) in an already multithreaded application
We are using OpenMP (libgomp) in order to speed up some calculations in a multithreaded Qt application. The parallel OpenMP sections are located within two different threads, though in fact they never execute in parallel. What we observe in this case is that 2N (where N = OMP_THREAD_LIMIT) omp threads are launched, apparently interfering each with the other. The calculation time is very high, while the processor load is low. Setting OMP_WAIT_POLICY hardly has any effect.

We also tried moving all the omp sections to a single thread (this is not a good solution for us, though, from an architectural point of view). In this case, the overall calculation time does drop and the processor is fully loaded, but only if OMP_WAIT_POLICY is set to ACTIVE. When OMP_WAIT_POLICY == PASSIVE, the calculation time remains low and the processor is idle 50% of time.

Odd enough, when we use omp within a single thread, the first loop parallelized using omp (in a series of omp calulations) executes 10 times slower compared to the multithread case.

Upd: Our questions are:

a) is there any way to reuse the openmp threads when using omp in the context of different threads.

b) Why executing with OMP_WAIT_POLICY == PASSIVE slows everything. Does it take so long to wake the threads?

c) Is there any logical explanation for the phenomenon of the first parallel block being so slow (even when waiting in active mode)

Upd2: Please mind that the issue is probably related to GNU OMP implementation. icc doesn't have it.

答:
Try to start/stop openmp threads in runtime using omp_set_num_threads(1) and omp_set_num_threads(cpucount)

This call with (1) should stop all openmp worker threads, and call with (cpu_num) will restart them again.

So, at start of programm, run omp_set_num_threads(1).
Before omp-parallelized region, you can start omp threads even with WAIT_POLICY=active, and they will not consume cpu before this point.

After omp parallel region you can stop threads again.

The omp_set_num_threads(cpucount) call is very slow, slower than waking threads with wait_policy=passive. This can be the reason for (c) - if your libgomp starts threads only at first parallel region.


问:
Git switch master and project branch
I have a project branch and a master branch in my Git project. I would like to make the project branch become the master branch. However, I would like to keep the old master branch as a side branch. How can I do this?

Current:

```<code>----------- master
    \______ project
</code>```

What I want:

```<code>-------------------- project (new master branch)
    \______ master (old)
</code>```

答:
If you want to exchange the name of the branches, probably the easiest way would be:</p>

```<code>git checkout --detach master # we put HEAD on master
git branch -f master project # move master to project (HEAD doesn't move)
git branch -f project # set project to HEAD
git checkout project
</code>```

Title: Git switch master and project branch

Body:
I have a project branch and a master branch in my Git project. I would like to make the project branch become the master branch. However, I would like to keep the old master branch as a side branch. How can I do this?

Current:

----------- master
    \______ project

What I want:

-------------------- project (new master branch)
    \______ master (old)

Body:
If you want to exchange the name of the branches, probably the easiest way would be:

git checkout --detach master # we put HEAD on master
git branch -f master project # move master to project (HEAD doesn't move)
git branch -f project # set project to HEAD
git checkout project


问:
Adobe Animate CC
TypeError: Error #1034: Type Coercion failed: cannot convert "Um1" to flash.display.MovieClip

Um1, Um2, Um3..... MovieClip Object in my Stage

```<code>var Um: Array = new Array();
for (var i: int = 0; i < 10; i++) {
  Um[i] = "Um" + Number(i + 1);
}

this.addEventListener(Event.ENTER_FRAME, HitUm);
function HitUm(event: Event) {
  for (var i: int = 0; i < 10; i++) {
    if(MovieClip(Um[i]).hitTestObject(car_mc.rabond_mc)) {
      trace(Um[i]);
    }
  }
}
</code>```

答:
This line here:

```<code>Um[i] = "Um" + Number(i + 1);
</code>```

is populating your Um array with a string value.   You later use that value like it's a MovieClip (which it isn't), so you get that error.  Most likely your trace(Um[i]) line results in "Um1", "Um2" etc. when it should be "[Object MovieClip]"

Assuming you have instance names in the same scope you are trying to get references to, you can do one of the following.

Use getChildByName:

```<code>Um[i] = getChildByName("Um" + (i + 1));
</code>```

OR use the current timeline (this) like a dictionary:

```<code>Um[i] = this["Um" + (i + 1)];
</code>```

Title: Adobe Animate CC

Body:
TypeError: Error #1034: Type Coercion failed: cannot convert "Um1" to flash.display.MovieClip

Um1, Um2, Um3..... MovieClip Object in my Stage

var Um: Array = new Array();
for (var i: int = 0; i < 10; i++) {
  Um[i] = "Um" + Number(i + 1);
}

this.addEventListener(Event.ENTER_FRAME, HitUm);
function HitUm(event: Event) {
  for (var i: int = 0; i < 10; i++) {
    if(MovieClip(Um[i]).hitTestObject(car_mc.rabond_mc)) {
      trace(Um[i]);
    }
  }
}

Body:
This line here:

Um[i] = "Um" + Number(i + 1);

is populating your Um array with a string value.   You later use that value like it's a MovieClip (which it isn't), so you get that error.  Most likely your trace(Um[i]) line results in "Um1", "Um2" etc. when it should be "[Object MovieClip]"

Assuming you have instance names in the same scope you are trying to get references to, you can do one of the following.

Use getChildByName:

Um[i] = getChildByName("Um" + (i + 1));

OR use the current timeline (this) like a dictionary:

Um[i] = this["Um" + (i + 1)];


问:
Sort project folders in alphabetical order in Sublime Text 3 sidebar?
In the Sublime Text sidebar is there a way to have project folders displayed in alphabetical order, instead of by the order that the folders were added.

This is driving me nuts. I've searched everywhere for this and have given up, but it's so painful.

答:
The contents of side bar folders are displayed in a sorted (lexical) ordering, with all sub-folders brought to the top instead of being in their natural sort position. There is currently no setting available or internal API that allows for changing that.

That said, the ordering of top level folders that you have manually added to your project is entirely under your control and defaults (as you've noticed) to the order that they were added in.

The folders in the sidebar are listed in the order that they're listed in the folders section of the sublime-project file. You can use Project > Edit Project to open your project file and manually reorder the elements in the folders list.

Additionally you can also click and drag the top level folders to change their relative ordering. Doing so causes Sublime to automatically rewrite the project file for you.

If the Project > Edit Project setting is not enabled, you haven't saved the current session as a project yet. In that case there will be no project file until you create one, but you can still drag to reorder the folders.


问:
Ignore specific database while replication in mongodb replicaset
I am running a replicaset of three members, i want to ignore a specific database while replicating to secondaries.

Is is possible for mongodb, please help!!

答:
Why do you need a replica set member not to replicate? A replica set is a group of mongod instances that host the same data set, except for arbiters which doesn't host data.

One way is that you can remove the particular database from the replica set.

```<code>rs.remove(host:port)
</code>```

Alternately you can reconfigure the replica set to make the member an arbiter. Specify a different data directory other than the one holding the data in this case.

```<code>rs.addArb(host:port)
</code>```

If the requirement is to carry out some implementation or maintenance activities, in which case you need a backup then consider using Delayed members. Refer this article.

Body:
Why do you need a replica set member not to replicate? A replica set is a group of mongod instances that host the same data set, except for arbiters which doesn't host data.

One way is that you can remove the particular database from the replica set.

rs.remove(host:port)

Alternately you can reconfigure the replica set to make the member an arbiter. Specify a different data directory other than the one holding the data in this case.

rs.addArb(host:port)

If the requirement is to carry out some implementation or maintenance activities, in which case you need a backup then consider using Delayed members. Refer this article.


问:
Add extra key in laravel eloquent result
I have a laravel query builder result that looks like this

```<code>{
  "data": [
    {
      "id": "",
      "awardID": 2,
      "title": "Dummy title",
      "status": "active",
      "raceStart":"",
      "raceEnd:":""
    }
  ]
}
</code>```

What i want to output is something like this

```<code>{
  "data": [
    {
      "id": "",
      "awardID": 2,
      "title": "Dummy title",
      "status": "active",
      "period": {
        "raceStart":"",
        "raceEnd:":""
      }
    }
  ]
}
</code>```

This would have been much easier if the period was a table with a 1 to 1 relationship with parent table but this is not the case here.
How can this be achieved?

答:
Check if this will work. I haven't tried though but according to documentation we can add accessor and mutators. But it will change every response you are doing with the model.

Using Eloquent

```<code>// Your Model
class Race extends Model
{
    {...}
    protected $appends = ['period'];
    // accessor
    public function getPeriodAttribute($value)
    {
        $this->attributes['period'] = (object)[];
        $this->attributes['period']['raceStart'] = $this->attributes['raceStart'];
        $this->attributes['period']['raceEnd'] = $this->attributes['raceEnd'];
        unset($this->attributes['raceStart']); = $value;
        unset($this->attributes['raceEnd']);
        return $this->attributes['period'];
    }
}
</code>```

Now when you will access $race->period will give the raceStart and raceEnd value.

Ref: https://laravel.com/docs/5.4/eloquent-mutators#accessors-and-mutators

else another option is after query, do a map

```<code>{...}
->map(function($data) {
    $data->period = (object)[];
    $data->period['raceStart'] = $data->raceStart;
    $data->period['raceEnd'] = $data->raceEnd;
    unset($data->raceStart);
    unset($data->raceEnd);
    return $data;
});
</code>```

Ref: https://laravel.com/docs/5.4/eloquent-collections#introduction

Using QueryBuilder

```<code>$races = DB::table('races')->get();

$races = array_map(function ($data) {
    $data->period = (object)[
        "raceStart" => $data->raceStart,
        "raceEnd" => $data->raceEnd
    ];
    unset($data->raceStart);
    unset($data->raceEnd);
    return $data;
}, $races->data);
</code>```

Body:
I have a laravel query builder result that looks like this

{
  "data": [
    {
      "id": "",
      "awardID": 2,
      "title": "Dummy title",
      "status": "active",
      "raceStart":"",
      "raceEnd:":""
    }
  ]
}

What i want to output is something like this

{
  "data": [
    {
      "id": "",
      "awardID": 2,
      "title": "Dummy title",
      "status": "active",
      "period": {
        "raceStart":"",
        "raceEnd:":""
      }
    }
  ]
}

This would have been much easier if the period was a table with a 1 to 1 relationship with parent table but this is not the case here.
How can this be achieved?

Body:
Check if this will work. I haven't tried though but according to documentation we can add accessor and mutators. But it will change every response you are doing with the model.

Using Eloquent

// Your Model
class Race extends Model
{
    {...}
    protected $appends = ['period'];
    // accessor
    public function getPeriodAttribute($value)
    {
        $this->attributes['period'] = (object)[];
        $this->attributes['period']['raceStart'] = $this->attributes['raceStart'];
        $this->attributes['period']['raceEnd'] = $this->attributes['raceEnd'];
        unset($this->attributes['raceStart']); = $value;
        unset($this->attributes['raceEnd']);
        return $this->attributes['period'];
    }
}

Now when you will access $race->period will give the raceStart and raceEnd value.

Ref: https://laravel.com/docs/5.4/eloquent-mutators#accessors-and-mutators

else another option is after query, do a map

{...}
->map(function($data) {
    $data->period = (object)[];
    $data->period['raceStart'] = $data->raceStart;
    $data->period['raceEnd'] = $data->raceEnd;
    unset($data->raceStart);
    unset($data->raceEnd);
    return $data;
});

Ref: https://laravel.com/docs/5.4/eloquent-collections#introduction

Using QueryBuilder

$races = DB::table('races')->get();

$races = array_map(function ($data) {
    $data->period = (object)[
        "raceStart" => $data->raceStart,
        "raceEnd" => $data->raceEnd
    ];
    unset($data->raceStart);
    unset($data->raceEnd);
    return $data;
}, $races->data);