问:
Fastest way to compare two huge csv files in python(numpy)
I am trying find the intesect sub set between two pretty big csv files of
phone numbers(one has 600k rows, and the other has 300mil). I am currently using pandas to open both files and then converting the needed columns into 1d numpy arrays and then using numpy intersect to get the intersect. Is there a better way of doing this, either with python or any other method. Thanks for any help</p>

```<code>import pandas as pd
import numpy as np

df_dnc = pd.read_csv('dncTest.csv', names = ['phone'])
df_test = pd.read_csv('phoneTest.csv', names = ['phone'])

dnc_phone = df_dnc['phone']
test_phone = df_test['phone']

np.intersect1d(dnc_phone, test_phone)
</code>```

答:
I will give you general solution with some Python pseudo code. What you are trying to solve here is the classical problem from the book "Programming Pearls" by Jon Bentley.

This is solved very efficiently with just a simple bit array, hence my comment, how long is (how many digits does have) the phone number.

Let's say the phone number is at most 10 digits long, than the max phone number you can have is: 9 999 999 999 (spaces are used for better readability). Here we can use 1bit per number to identify if the number is in set or not (bit is set or not set respectively), thus we are going to use 9 999 999 999 bits to identify each number, i.e.:

bits[0] identifies the number 0 000 000 000

bits[193] identifies the number 0 000 000 193

having a number 659 234-4567 would be addressed by the bits[6592344567]

Doing so we'd need to pre-allocate 9 999 999 999 bits initially set to 0, which is: 9 999 999 999 / 8 / 1024 / 1024 = around 1.2 GB of memory.

I think that holding the intersection of numbers at the end will use more space than the bits representation => at most 600k ints will be stored => 64bit * 600k = around 4.6 GB (actually int is not stored that efficiently and might use much more), if these are string you'll probably end with even more memory requirements.

Parsing a phone number string from CSV file (line by line or buffered file reader), converting it to a number and than doing a constant time memory lookup will be IMO faster than dealing with strings and merging them. Unfortunately, I don't have these phone number files to test, but would be interested to hear your findings.

```<code>from bitstring import BitArray

max_number = 9999999999

found_phone_numbers = BitArray(length=max_number+1)

# replace this function with the file open function and retrieving
#  the next found phone number
def number_from_file_iteator(dummy_data):
    for number in dummy_data:
        yield number

def calculate_intersect():
    # should be open a file1 and getting the generator with numbers from it
    #  we use dummy data here
    for number in number_from_file_iteator([1, 25, 77, 224322323, 8292, 1232422]):
        found_phone_numbers[number] = True

    # open second file and check if the number is there
    for number in number_from_file_iteator([4, 24, 224322323, 1232422, max_number]):
        if found_phone_numbers[number]:
            yield number

number_intersection = set(calculate_intersect())

print number_intersection
</code>```

I used BitArray from bitstring pip package and it needed around 2 secs to initialize the entire bitstring. Afterwards, scanning the file will use constant memory. At the end I used a set to store the items.

Note 1: This algorithm can be modified to just use the list. In that case a second loop as soon as bit number matches this bit must be reset, so that duplicates do not match again.

Note 2: Storing in the set/list occurs lazy, because we use the generator in the second for loop. Runtime complexity is linear, i.e. O(N).

Body:
I am trying find the intesect sub set between two pretty big csv files of
phone numbers(one has 600k rows, and the other has 300mil). I am currently using pandas to open both files and then converting the needed columns into 1d numpy arrays and then using numpy intersect to get the intersect. Is there a better way of doing this, either with python or any other method. Thanks for any help

import pandas as pd
import numpy as np

df_dnc = pd.read_csv('dncTest.csv', names = ['phone'])
df_test = pd.read_csv('phoneTest.csv', names = ['phone'])

dnc_phone = df_dnc['phone']
test_phone = df_test['phone']

np.intersect1d(dnc_phone, test_phone)

Body:
I will give you general solution with some Python pseudo code. What you are trying to solve here is the classical problem from the book "Programming Pearls" by Jon Bentley.

This is solved very efficiently with just a simple bit array, hence my comment, how long is (how many digits does have) the phone number.

Let's say the phone number is at most 10 digits long, than the max phone number you can have is: 9 999 999 999 (spaces are used for better readability). Here we can use 1bit per number to identify if the number is in set or not (bit is set or not set respectively), thus we are going to use 9 999 999 999 bits to identify each number, i.e.:

bits[0] identifies the number 0 000 000 000

bits[193] identifies the number 0 000 000 193

having a number 659 234-4567 would be addressed by the bits[6592344567]

Doing so we'd need to pre-allocate 9 999 999 999 bits initially set to 0, which is: 9 999 999 999 / 8 / 1024 / 1024 = around 1.2 GB of memory.

I think that holding the intersection of numbers at the end will use more space than the bits representation => at most 600k ints will be stored => 64bit * 600k = around 4.6 GB (actually int is not stored that efficiently and might use much more), if these are string you'll probably end with even more memory requirements.

Parsing a phone number string from CSV file (line by line or buffered file reader), converting it to a number and than doing a constant time memory lookup will be IMO faster than dealing with strings and merging them. Unfortunately, I don't have these phone number files to test, but would be interested to hear your findings.

from bitstring import BitArray

max_number = 9999999999

found_phone_numbers = BitArray(length=max_number+1)

# replace this function with the file open function and retrieving
#  the next found phone number
def number_from_file_iteator(dummy_data):
    for number in dummy_data:
        yield number

def calculate_intersect():
    # should be open a file1 and getting the generator with numbers from it
    #  we use dummy data here
    for number in number_from_file_iteator([1, 25, 77, 224322323, 8292, 1232422]):
        found_phone_numbers[number] = True

    # open second file and check if the number is there
    for number in number_from_file_iteator([4, 24, 224322323, 1232422, max_number]):
        if found_phone_numbers[number]:
            yield number

number_intersection = set(calculate_intersect())

print number_intersection

I used BitArray from bitstring pip package and it needed around 2 secs to initialize the entire bitstring. Afterwards, scanning the file will use constant memory. At the end I used a set to store the items.

Note 1: This algorithm can be modified to just use the list. In that case a second loop as soon as bit number matches this bit must be reset, so that duplicates do not match again.

Note 2: Storing in the set/list occurs lazy, because we use the generator in the second for loop. Runtime complexity is linear, i.e. O(N).


来源: stackexchange

问:
jquery: duplicate and paste html
hmm ok heres the shortened code

```<code> <div id="SideCategoryList">
        <div class="BlockContent">
           <ul>
              <li><a href="#">Link A</a></li>
              <li><a href="#">Link B</a></li>
          </ul>
       </div>
     </div>
    <div id="navcont">
    <ul class="menu" id="menu">
      <li id="hov"><a href="#">Top Link</a></li>
      <li><a href="#">Bottom Link</a></li>
    </ul>
   </div>
</code>```

i want to use jquery to duplicate whats in the first ul into the first li in the #menu so it looks like this

```<code><div id="SideCategoryList">
        <div class="BlockContent">
           <ul>
              <li><a href="#">Link A</a></li>
              <li><a href="#">Link B</a></li>
          </ul>
       </div>
     </div>
    <div id="navcont">
      <ul class="menu" id="menu">
         <li id="hov"><a href="#">Top Link</a>
            <ul>
               <li><a href="#">Link A</a></li>
               <li><a href="#">Link B</a></li>
            </ul>
        </li>
        <li><a href="#">Bottom Link</a></li>
      </ul>
   </div>
</code>```

so the finished product will be a 2 level list... let me know if this is makin sense lol

ContentLicense: CC BY-SA 2.5

Title: jquery: duplicate and paste html

Body:
hmm ok heres the shortened code

Link A

Link B

Top Link

Bottom Link

i want to use jquery to duplicate whats in the first ul into the first li in the #menu so it looks like this

Link A

Link B

Top Link

Link A

Link B

Bottom Link

so the finished product will be a 2 level list... let me know if this is makin sense lol

Body: $("#hov").append($(".BlockContent ul").clone());


问:
Not Showing banner only vibrate device when push notification received
When I Send push notification, I am getting notification on device, but it is not getting displayed as banner in the lock screen or notification center on the iPhone. I have iOS 9 installed on my iPhone.

Following is my code.

```<code> func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
    registerForPushNotifications(application)

    return true
}

func registerForPushNotifications(application: UIApplication)
{

    let settings = UIUserNotificationSettings(forTypes: [.Sound, .Alert, .Badge], categories: nil)

    UIApplication.sharedApplication().registerUserNotificationSettings(settings)

    UIApplication.sharedApplication().registerForRemoteNotifications()

}

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData)
{
    print("DEVICE TOKEN = \(deviceToken)")

    let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
    var tokenString = ""

    for i in 0..<deviceToken.length
    {
        tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
    }

    print("tokenString: \(tokenString)")
    strDeviceToken = tokenString
}

func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError)
{
    print("Error = \(error)")
}

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]){
        print(userInfo)
    }
</code>```

答: Finally i am resolve this issue. their issue on php code not in iOS code. in php code they are missing alert Keyword in aps array that why device only vibrate when receive Notification.

ContentLicense: CC BY-SA 3.0

Body:
When I Send push notification, I am getting notification on device, but it is not getting displayed as banner in the lock screen or notification center on the iPhone. I have iOS 9 installed on my iPhone.

Following is my code.

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
    registerForPushNotifications(application)

    return true
}

func registerForPushNotifications(application: UIApplication)
{

    let settings = UIUserNotificationSettings(forTypes: [.Sound, .Alert, .Badge], categories: nil)

    UIApplication.sharedApplication().registerUserNotificationSettings(settings)

    UIApplication.sharedApplication().registerForRemoteNotifications()

}

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData)
{
    print("DEVICE TOKEN = \(deviceToken)")

    let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
    var tokenString = ""

    for i in 0..<deviceToken.length
    {
        tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
    }

    print("tokenString: \(tokenString)")
    strDeviceToken = tokenString
}

func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError)
{
    print("Error = \(error)")
}

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]){
        print(userInfo)
    }


问:
three js - raycaster failing
I have a mesh defined which is at the origin.

```<code>var textureCanvas = new THREE.CanvasTexture( imageCanvas );
textureCanvas.repeat.set( 4, 4 );
textureCanvas.wrapS = THREE.RepeatWrapping;
textureCanvas.wrapT = THREE.RepeatWrapping;

var materialCanvas = new THREE.MeshBasicMaterial( { map: textureCanvas }
);

var geometry = new THREE.Geometry();
geometry.vertices.push(
    new THREE.Vector3(-4,-4,0),
    new THREE.Vector3(-4,4,0),
    new THREE.Vector3(4,4,0),
    new THREE.Vector3(4,-4,0),
);

geometry.faces.push(
    new THREE.Face3(3, 1, 0),
    new THREE.Face3(3, 2, 1)
);

var vertexMappings = [];
vertexMappings[0] = new THREE.Vector2(0,1);
vertexMappings[1] = new THREE.Vector2(0,0);
vertexMappings[2] = new THREE.Vector2(1,0);
vertexMappings[3] = new THREE.Vector2(1,1);
var vm = vertexMappings;

geometry.faceVertexUvs[ 0 ] = [];
geometry.faceVertexUvs[0][0] = [ vm[3], vm[1], vm[0] ];
geometry.faceVertexUvs[0][1] = [ vm[3], vm[2], vm[1] ];

meshCanvas = new THREE.Mesh( geometry, materialCanvas );
meshCanvas.rotation.x = - Math.PI / 3;
meshCanvas.rotation.z = - Math.PI / 2.5;

meshCanvas.scale.set( 80, 80, 80 );

scene.add( meshCanvas );
</code>```

I also have a line which goes through the mesh. It was originally passing through the origin but I moved it a bit (See github issue below).

```<code>var linegeo = new THREE.Geometry();
linegeo.vertices.push(
    new THREE.Vector3(55, 300, 0),
    new THREE.Vector3(-10, -300, 32)
);

scene.add(linemesh);
</code>```

I want to get the position where the line intersects the mesh, but the intersections result is always empty:

```<code>getInersectionPosition(linemesh, meshCanvas);

function getInersectionPosition(linemesh, meshCanvas) {
    linemesh.updateMatrixWorld();
    meshCanvas.updateMatrixWorld();

    var p1 = linemesh.geometry.vertices[0].clone(),
    p2 = linemesh.geometry.vertices[1].clone();

    p1.applyMatrix4(linemesh.matrixWorld);
    p2.applyMatrix4(linemesh.matrixWorld);

    //console.log(`p1: ${JSON.stringify(p1)}, p2: ${JSON.stringify(p2)}`);
    //console.log(`canvas position: ${JSON.stringify(meshCanvas.position)}`);

    var raycaster = new THREE.Raycaster(p1, p2);
    raycaster.linePrecision = 10;

    //var intersections = raycaster.intersectObjects([meshCanvas]);
    var intersections = raycaster.intersectObjects(scene.children, true);

    if (intersections.length > 0)
        console.log(`intersections: ${ intersections.length}`);
}
</code>```

Full sample: https://jsfiddle.net/mribbons/103wwsda/

Is it possible that I have this issue?
https://github.com/mrdoob/three.js/issues/11449

The raycaster.intersectObjects() call seems to fail here, with very large values for distance (2.7 million or so, while sphere.radius is ~450).

https://github.com/mrdoob/three.js/blob/dev/build/three.js#L9761

```<code>intersectsSphere: function ( sphere ) {
    var distance = this.distanceToPoint( sphere.center )

    return distance <= sphere.radius;

},
</code>```

答:
My mistake, raycaster expects a point and a normal, this resolves the issue:</p>

```<code>var normal = new THREE.Vector3();

normal.subVectors(p2, p1).normalize();

var raycaster = new THREE.Raycaster(p1, normal);

var intersections = raycaster.intersectObjects(scene.children, true);

if (intersections.length > 0)
    console.log(`intersections: ${ intersections.length}`); // outputs "intersections: 2"
</code>```

Title: three js - raycaster failing

Body:
I have a mesh defined which is at the origin.

var textureCanvas = new THREE.CanvasTexture( imageCanvas );
textureCanvas.repeat.set( 4, 4 );
textureCanvas.wrapS = THREE.RepeatWrapping;
textureCanvas.wrapT = THREE.RepeatWrapping;

var materialCanvas = new THREE.MeshBasicMaterial( { map: textureCanvas }
);

var geometry = new THREE.Geometry();
geometry.vertices.push(
    new THREE.Vector3(-4,-4,0),
    new THREE.Vector3(-4,4,0),
    new THREE.Vector3(4,4,0),
    new THREE.Vector3(4,-4,0),
);

geometry.faces.push(
    new THREE.Face3(3, 1, 0),
    new THREE.Face3(3, 2, 1)
);

var vertexMappings = [];
vertexMappings[0] = new THREE.Vector2(0,1);
vertexMappings[1] = new THREE.Vector2(0,0);
vertexMappings[2] = new THREE.Vector2(1,0);
vertexMappings[3] = new THREE.Vector2(1,1);
var vm = vertexMappings;

geometry.faceVertexUvs[ 0 ] = [];
geometry.faceVertexUvs[0][0] = [ vm[3], vm[1], vm[0] ];
geometry.faceVertexUvs[0][1] = [ vm[3], vm[2], vm[1] ];

meshCanvas = new THREE.Mesh( geometry, materialCanvas );
meshCanvas.rotation.x = - Math.PI / 3;
meshCanvas.rotation.z = - Math.PI / 2.5;

meshCanvas.scale.set( 80, 80, 80 );

scene.add( meshCanvas );

I also have a line which goes through the mesh. It was originally passing through the origin but I moved it a bit (See github issue below).

var linegeo = new THREE.Geometry();
linegeo.vertices.push(
    new THREE.Vector3(55, 300, 0),
    new THREE.Vector3(-10, -300, 32)
);

scene.add(linemesh);

I want to get the position where the line intersects the mesh, but the intersections result is always empty:

getInersectionPosition(linemesh, meshCanvas);

function getInersectionPosition(linemesh, meshCanvas) {
    linemesh.updateMatrixWorld();
    meshCanvas.updateMatrixWorld();

    var p1 = linemesh.geometry.vertices[0].clone(),
    p2 = linemesh.geometry.vertices[1].clone();

    p1.applyMatrix4(linemesh.matrixWorld);
    p2.applyMatrix4(linemesh.matrixWorld);

    //console.log(`p1: ${JSON.stringify(p1)}, p2: ${JSON.stringify(p2)}`);
    //console.log(`canvas position: ${JSON.stringify(meshCanvas.position)}`);

    var raycaster = new THREE.Raycaster(p1, p2);
    raycaster.linePrecision = 10;

    //var intersections = raycaster.intersectObjects([meshCanvas]);
    var intersections = raycaster.intersectObjects(scene.children, true);

    if (intersections.length > 0)
        console.log(`intersections: ${ intersections.length}`);
}

Full sample: https://jsfiddle.net/mribbons/103wwsda/

Is it possible that I have this issue?
https://github.com/mrdoob/three.js/issues/11449

The raycaster.intersectObjects() call seems to fail here, with very large values for distance (2.7 million or so, while sphere.radius is ~450).

https://github.com/mrdoob/three.js/blob/dev/build/three.js#L9761

intersectsSphere: function ( sphere ) {
    var distance = this.distanceToPoint( sphere.center )

    return distance <= sphere.radius;

},

Body:
My mistake, raycaster expects a point and a normal, this resolves the issue:

var normal = new THREE.Vector3();

normal.subVectors(p2, p1).normalize();

var raycaster = new THREE.Raycaster(p1, normal);

var intersections = raycaster.intersectObjects(scene.children, true);

if (intersections.length > 0)
    console.log(`intersections: ${ intersections.length}`); // outputs "intersections: 2"


问:
'this' property has value undefined on nodeJS
I'm still learning JavaScript and when I tried to get an understanding of this behavior, I've got a little confused. One thing that I understand that this keyword is actually refer to where is the call-site of the function when it called. I was trying run the example code below:

```<code>function foo() {
    console.log ( this.a );
}
var a = 2;
foo();
</code>```

The expected result is 2. It did show 2 on Chrome's console but when I tried to run it from NodeJS, result result would be undefined. my Node version is 6.10.1

Is the call-site will be different when the code run in Node compare to Browser's Console or is there anything that need my concern when I'm running code on nodeJS especially when using this keyword?

答:
In the browser your global object is the Window, "this" is referring to the window object. Every variable created in this execution context are attached to the Window object.

In NodeJS every variable defined outside of a specific execution context are attached to a "module" context which is considered the file you are working on and not to the global object that Nodes uses.

Therefore, the object invoking your function in the browser is the Window object and in node is the Global object.
In the browser, your variable 'a' is attached to the Windows object and 'this' points to it.
In Node 'a' is attached to the Module created for exporting the file but 'this' points to the Global object.

Check also this answer

Body:
I'm still learning JavaScript and when I tried to get an understanding of this behavior, I've got a little confused. One thing that I understand that this keyword is actually refer to where is the call-site of the function when it called. I was trying run the example code below:

function foo() {
    console.log ( this.a );
}
var a = 2;
foo();

The expected result is 2. It did show 2 on Chrome's console but when I tried to run it from NodeJS, result result would be undefined. my Node version is 6.10.1

Is the call-site will be different when the code run in Node compare to Browser's Console or is there anything that need my concern when I'm running code on nodeJS especially when using this keyword?


问:
Android floating button not coming proper
I am using a floating button. The image source I am using is also proper but not sure while setting it is showing it as dot in the center. Screenshot and Code below :

```<code><android.support.design.widget.FloatingActionButton
        android:id="@+id/fab_add_cg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:elevation="10dp"
        app:borderWidth="0dp"
        app:backgroundTint="@color/blue_4a90e2"
        android:src="@drawable/addbutton"/>
</code>```

答:
fabSize can adjust as "mini" & "normal".

```<code><android.support.design.widget.FloatingActionButton
  android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:src="@drawable/ic_done_white_24px"
 app:fabSize="mini"
 android:scaleType="center"/>
</code>```

Body:
I am using a floating button. The image source I am using is also proper but not sure while setting it is showing it as dot in the center. Screenshot and Code below :

<android.support.design.widget.FloatingActionButton
        android:id="@+id/fab_add_cg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:elevation="10dp"
        app:borderWidth="0dp"
        app:backgroundTint="@color/blue_4a90e2"
        android:src="@drawable/addbutton"/>

Body:
fabSize can adjust as "mini" & "normal".

<android.support.design.widget.FloatingActionButton
  android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:src="@drawable/ic_done_white_24px"
 app:fabSize="mini"
 android:scaleType="center"/>


问:
Extract text between characters, strings or brackets

I have following types of data :

```<code>pd.DataFrame({"Hashtags": [ "[]", "[u'AAPHealthCare4All']", "[u'CBI',","u'Delhi',", "u'Emergency']"]})
</code>```

Expected Output

```<code>pd.DataFrame({"Hashtags": [ " ", "AAPHealthCare4All", "CBI","Delhi", "Emergency"]})
</code>```

None of the brackets, parentheses or commas and quotes are missing/typo.
[] should be substituted with blanks. Basically I want to remove all the "[" , "]" , " [u' " etc.
I have used the following code, but to no avail :

```<code>for index,row in df.iterrows():
    if "RT @" in row["Tweet"]:
        df['Hashtags'] =df['Hashtags'].str.replace(r'[^[]]*\[|\][^]*|\[u\'*\'\]|\[\'*\'\]', '')
df.to_csv('string_HT.csv', index=False)
</code>```

答:
I think simpliset is use double strip with replace:

```<code>df['Hashtags'] = df['Hashtags'].str.strip("[u,]").str.strip("'").replace('', ' ')
print (df['Hashtags'].tolist())
[' ', 'AAPHealthCare4All', 'CBI', 'Delhi', 'Emergency']
</code>```

Double strip is necessary, because if only one, it remove all u from starts and ends of strings:

```<code>df = pd.DataFrame({"Hashtags": [ "[]", "[u'uuAAPHealthCare4All']",
                                "[u'uCBIuu',","u'uDelhi',", "u'Emergency']"]})
print (df)
                   Hashtags
0                        []
1  [u'uuAAPHealthCare4All']
2               [u'uCBIuu',
3                u'uDelhi',
4             u'Emergency']

df['Hashtags'] = df['Hashtags'].str.strip("[u,']")
print (df['Hashtags'])
0
1    AAPHealthCare4All
2                  CBI
3                Delhi
4            Emergency
Name: Hashtags, dtype: object
</code>```

Body:
I have following types of data :

pd.DataFrame({"Hashtags": [ "[]", "[u'AAPHealthCare4All']", "[u'CBI',","u'Delhi',", "u'Emergency']"]})

Expected Output

pd.DataFrame({"Hashtags": [ " ", "AAPHealthCare4All", "CBI","Delhi", "Emergency"]})

None of the brackets, parentheses or commas and quotes are missing/typo.
[] should be substituted with blanks. Basically I want to remove all the "[" , "]" , " [u' " etc.
I have used the following code, but to no avail :

for index,row in df.iterrows():
    if "RT @" in row["Tweet"]:
        df['Hashtags'] =df['Hashtags'].str.replace(r'[^[]]*\[|\][^]*|\[u\'*\'\]|\[\'*\'\]', '')
df.to_csv('string_HT.csv', index=False)

Body:
I think simpliset is use double strip with replace:

df['Hashtags'] = df['Hashtags'].str.strip("[u,]").str.strip("'").replace('', ' ')
print (df['Hashtags'].tolist())
[' ', 'AAPHealthCare4All', 'CBI', 'Delhi', 'Emergency']

Double strip is necessary, because if only one, it remove all u from starts and ends of strings:

df = pd.DataFrame({"Hashtags": [ "[]", "[u'uuAAPHealthCare4All']",
                                "[u'uCBIuu',","u'uDelhi',", "u'Emergency']"]})
print (df)
                   Hashtags
0                        []
1  [u'uuAAPHealthCare4All']
2               [u'uCBIuu',
3                u'uDelhi',
4             u'Emergency']

df['Hashtags'] = df['Hashtags'].str.strip("[u,']")
print (df['Hashtags'])
0
1    AAPHealthCare4All
2                  CBI
3                Delhi
4            Emergency
Name: Hashtags, dtype: object


问:
Hide a button in onload using angularjs
I have one form with three buttons edit update and cancel.Onload of the page I need to hide the update button.

When I click edit button edit should be hide and update should be displayed.
when I click on update I need to redirect some other page.

Hoe to do this?

```<code>                <form id="show_details">

                        <label>Project Name</label>
                        <label><input type="text"></label>

                        <label>Client </label>
                        <label><input type="text"></label>

                        <label>Project Co-ordinator</label>
                        <label><input type="text" disabled="true" ></label>

                        <label>Client Co-ordinator</label>
                        <label><input type="text"></label>

                        <label>Resource</label>
                        <label><input type="text" disabled="true"></label>
                    </div>
                </form>
                <div class="row">
                    <span class="pull-right btnMarginTop">
                        <button class="btn btn-primary" id="projectDetailsEdit"  ng-click="goEvent()">Edit</button>
                        <button class="btn btn-primary" id="projectDetailsUpdate" ng-hide="editMode=true" ng-click="goEvent()">Update</button>
                        <button class="btn btn-default" onclick="window.location.href = '/Project/ProjectList'">Cancel</button>
                    </span>
                </div>

<script>
    var app = angular
                    .module("intranet_App", [])
                    .controller(function ($scope, $http) {
                       $scope.editMode = false;
                       $scope.goEvent = function(){
                       $scope.editMode = !$scope.editMode;
                       if($scope.editMode){
                          $scope.editMode = false;
                       }else{
                           $scope.editMode = true;
                       }
                    }
                    })
</script>
</code>```

答:
Use ng-show/hide or ng-if..

var app = angular.module("intranet_App", []);
     app.controller('ctrl', function ($scope, $http) {
                       $scope.editMode = false;
                       $scope.goEvent = function(){
                       $scope.editMode = !$scope.editMode;
                    }
                    })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="intranet_App" ng-controller="ctrl">
   <form id="show_details">
   <div>
                        <label>Project Name</label>
                        <label><input type="text"></label>

                        <label>Client </label>
                        <label><input type="text"></label>

                        <label>Project Co-ordinator</label>
                        <label><input type="text" disabled="true" ></label>

                        <label>Client Co-ordinator</label>
                        <label><input type="text"></label>

                        <label>Resource</label>
                        <label><input type="text" disabled="true"></label>
                    </div>
                </form>
                <div class="row">
                    <span class="pull-right btnMarginTop">
      <button class="btn btn-primary" id="projectDetailsEdit" ng-if="!editMode"  ng-click="goEvent()">Edit</button>
                        <button class="btn btn-primary" id="projectDetailsUpdate" ng-if="editMode" ng-click="goEvent()">Update</button>
                        <button class="btn btn-default" onclick="window.location.href = '/Project/ProjectList'">Cancel</button>
                    </span>
                </div>
</body></code>```

Title: Hide a button in onload using angularjs

Body:
I have one form with three buttons edit update and cancel.Onload of the page I need to hide the update button.

When I click edit button edit should be hide and update should be displayed.
when I click on update I need to redirect some other page.

Hoe to do this?

                <form id="show_details">

                        Project Name
                        <input type="text">

                        Client
                        <input type="text">

                        Project Co-ordinator
                        <input type="text" disabled="true" >

                        Client Co-ordinator
                        <input type="text">

                        Resource
                        <input type="text" disabled="true">

                </form>

                        <button class="btn btn-primary" id="projectDetailsEdit"  ng-click="goEvent()">Edit</button>
                        <button class="btn btn-primary" id="projectDetailsUpdate" ng-hide="editMode=true" ng-click="goEvent()">Update</button>
                        <button class="btn btn-default" onclick="window.location.href = '/Project/ProjectList'">Cancel</button>

Body:
Use ng-show/hide or ng-if..

var app = angular.module("intranet_App", []);
     app.controller('ctrl', function ($scope, $http) {
                       $scope.editMode = false;
                       $scope.goEvent = function(){
                       $scope.editMode = !$scope.editMode;
                    }
                    })

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="intranet_App" ng-controller="ctrl">
   <form id="show_details">
   <div>
                        <label>Project Name</label>
                        <label><input type="text"></label>

                        <label>Client </label>
                        <label><input type="text"></label>

                        <label>Project Co-ordinator</label>
                        <label><input type="text" disabled="true" ></label>

                        <label>Client Co-ordinator</label>
                        <label><input type="text"></label>

                        <label>Resource</label>
                        <label><input type="text" disabled="true"></label>
                    </div>
                </form>
                <div class="row">
                    <span class="pull-right btnMarginTop">
      <button class="btn btn-primary" id="projectDetailsEdit" ng-if="!editMode"  ng-click="goEvent()">Edit</button>
                        <button class="btn btn-primary" id="projectDetailsUpdate" ng-if="editMode" ng-click="goEvent()">Update</button>
                        <button class="btn btn-default" onclick="window.location.href = '/Project/ProjectList'">Cancel</button>
                    </span>
                </div>
</body>


问:
Why shouldn't I use mysql_* functions in PHP?
What are the technical reasons for why one shouldn't use mysql_* functions? (e.g. mysql_query(), mysql_connect() or mysql_real_escape_string())?

Why should I use something else even if they work on my site?

If they don't work on my site, why do I get errors like

Warning: mysql_connect(): No such file or directory

答:
It's possible to define almost all mysql_* functions using mysqli or PDO. Just include them on top of your old PHP application, and it will work on PHP7. My solution here.

```<code><?php

define('MYSQL_LINK', 'dbl');
$GLOBALS[MYSQL_LINK] = null;

function mysql_link($link=null) {
    return ($link === null) ? $GLOBALS[MYSQL_LINK] : $link;
}

function mysql_connect($host, $user, $pass) {
    $GLOBALS[MYSQL_LINK] = mysqli_connect($host, $user, $pass);
    return $GLOBALS[MYSQL_LINK];
}

function mysql_pconnect($host, $user, $pass) {
    return mysql_connect($host, $user, $pass);
}

function mysql_select_db($db, $link=null) {
    $link = mysql_link($link);
    return mysqli_select_db($link, $db);
}

function mysql_close($link=null) {
    $link = mysql_link($link);
    return mysqli_close($link);
}

function mysql_error($link=null) {
    $link = mysql_link($link);
    return mysqli_error($link);
}

function mysql_errno($link=null) {
    $link = mysql_link($link);
    return mysqli_errno($link);
}

function mysql_ping($link=null) {
    $link = mysql_link($link);
    return mysqli_ping($link);
}

function mysql_stat($link=null) {
    $link = mysql_link($link);
    return mysqli_stat($link);
}

function mysql_affected_rows($link=null) {
    $link = mysql_link($link);
    return mysqli_affected_rows($link);
}

function mysql_client_encoding($link=null) {
    $link = mysql_link($link);
    return mysqli_character_set_name($link);
}

function mysql_thread_id($link=null) {
    $link = mysql_link($link);
    return mysqli_thread_id($link);
}

function mysql_escape_string($string) {
    return mysql_real_escape_string($string);
}

function mysql_real_escape_string($string, $link=null) {
    $link = mysql_link($link);
    return mysqli_real_escape_string($link, $string);
}

function mysql_query($sql, $link=null) {
    $link = mysql_link($link);
    return mysqli_query($link, $sql);
}

function mysql_unbuffered_query($sql, $link=null) {
    $link = mysql_link($link);
    return mysqli_query($link, $sql, MYSQLI_USE_RESULT);
}

function mysql_set_charset($charset, $link=null){
    $link = mysql_link($link);
    return mysqli_set_charset($link, $charset);
}

function mysql_get_host_info($link=null) {
    $link = mysql_link($link);
    return mysqli_get_host_info($link);
}

function mysql_get_proto_info($link=null) {
    $link = mysql_link($link);
    return mysqli_get_proto_info($link);
}
function mysql_get_server_info($link=null) {
    $link = mysql_link($link);
    return mysqli_get_server_info($link);
}

function mysql_info($link=null) {
    $link = mysql_link($link);
    return mysqli_info($link);
}

function mysql_get_client_info() {
    $link = mysql_link();
    return mysqli_get_client_info($link);
}

function mysql_create_db($db, $link=null) {
    $link = mysql_link($link);
    $db = str_replace('`', '', mysqli_real_escape_string($link, $db));
    return mysqli_query($link, "CREATE DATABASE `$db`");
}

function mysql_drop_db($db, $link=null) {
    $link = mysql_link($link);
    $db = str_replace('`', '', mysqli_real_escape_string($link, $db));
    return mysqli_query($link, "DROP DATABASE `$db`");
}

function mysql_list_dbs($link=null) {
    $link = mysql_link($link);
    return mysqli_query($link, "SHOW DATABASES");
}

function mysql_list_fields($db, $table, $link=null) {
    $link = mysql_link($link);
    $db = str_replace('`', '', mysqli_real_escape_string($link, $db));
    $table = str_replace('`', '', mysqli_real_escape_string($link, $table));
    return mysqli_query($link, "SHOW COLUMNS FROM `$db`.`$table`");
}

function mysql_list_tables($db, $link=null) {
    $link = mysql_link($link);
    $db = str_replace('`', '', mysqli_real_escape_string($link, $db));
    return mysqli_query($link, "SHOW TABLES FROM `$db`");
}

function mysql_db_query($db, $sql, $link=null) {
    $link = mysql_link($link);
    mysqli_select_db($link, $db);
    return mysqli_query($link, $sql);
}

function mysql_fetch_row($qlink) {
    return mysqli_fetch_row($qlink);
}

function mysql_fetch_assoc($qlink) {
    return mysqli_fetch_assoc($qlink);
}

function mysql_fetch_array($qlink, $result=MYSQLI_BOTH) {
    return mysqli_fetch_array($qlink, $result);
}

function mysql_fetch_lengths($qlink) {
    return mysqli_fetch_lengths($qlink);
}

function mysql_insert_id($qlink) {
    return mysqli_insert_id($qlink);
}

function mysql_num_rows($qlink) {
    return mysqli_num_rows($qlink);
}

function mysql_num_fields($qlink) {
    return mysqli_num_fields($qlink);
}

function mysql_data_seek($qlink, $row) {
    return mysqli_data_seek($qlink, $row);
}

function mysql_field_seek($qlink, $offset) {
    return mysqli_field_seek($qlink, $offset);
}

function mysql_fetch_object($qlink, $class="stdClass", array $params=null) {
    return ($params === null)
        ? mysqli_fetch_object($qlink, $class)
        : mysqli_fetch_object($qlink, $class, $params);
}

function mysql_db_name($qlink, $row, $field='Database') {
    mysqli_data_seek($qlink, $row);
    $db = mysqli_fetch_assoc($qlink);
    return $db[$field];
}

function mysql_fetch_field($qlink, $offset=null) {
    if ($offset !== null)
        mysqli_field_seek($qlink, $offset);
    return mysqli_fetch_field($qlink);
}

function mysql_result($qlink, $offset, $field=0) {
    if ($offset !== null)
        mysqli_field_seek($qlink, $offset);
    $row = mysqli_fetch_array($qlink);
    return (!is_array($row) || !isset($row[$field]))
        ? false
        : $row[$field];
}

function mysql_field_len($qlink, $offset) {
    $field = mysqli_fetch_field_direct($qlink, $offset);
    return is_object($field) ? $field->length : false;
}

function mysql_field_name($qlink, $offset) {
    $field = mysqli_fetch_field_direct($qlink, $offset);
    if (!is_object($field))
        return false;
    return empty($field->orgname) ? $field->name : $field->orgname;
}

function mysql_field_table($qlink, $offset) {
    $field = mysqli_fetch_field_direct($qlink, $offset);
    if (!is_object($field))
        return false;
    return empty($field->orgtable) ? $field->table : $field->orgtable;
}

function mysql_field_type($qlink, $offset) {
    $field = mysqli_fetch_field_direct($qlink, $offset);
    return is_object($field) ? $field->type : false;
}

function mysql_free_result($qlink) {
    try {
        mysqli_free_result($qlink);
    } catch (Exception $e) {
        return false;
    }
    return true;
}
</code>```

Body:
It's possible to define almost all mysql_* functions using mysqli or PDO. Just include them on top of your old PHP application, and it will work on PHP7. My solution here.

<?php

define('MYSQL_LINK', 'dbl');
$GLOBALS[MYSQL_LINK] = null;

function mysql_link($link=null) {
    return ($link === null) ? $GLOBALS[MYSQL_LINK] : $link;
}

function mysql_connect($host, $user, $pass) {
    $GLOBALS[MYSQL_LINK] = mysqli_connect($host, $user, $pass);
    return $GLOBALS[MYSQL_LINK];
}

function mysql_pconnect($host, $user, $pass) {
    return mysql_connect($host, $user, $pass);
}

function mysql_select_db($db, $link=null) {
    $link = mysql_link($link);
    return mysqli_select_db($link, $db);
}

function mysql_close($link=null) {
    $link = mysql_link($link);
    return mysqli_close($link);
}

function mysql_error($link=null) {
    $link = mysql_link($link);
    return mysqli_error($link);
}

function mysql_errno($link=null) {
    $link = mysql_link($link);
    return mysqli_errno($link);
}

function mysql_ping($link=null) {
    $link = mysql_link($link);
    return mysqli_ping($link);
}

function mysql_stat($link=null) {
    $link = mysql_link($link);
    return mysqli_stat($link);
}

function mysql_affected_rows($link=null) {
    $link = mysql_link($link);
    return mysqli_affected_rows($link);
}

function mysql_client_encoding($link=null) {
    $link = mysql_link($link);
    return mysqli_character_set_name($link);
}

function mysql_thread_id($link=null) {
    $link = mysql_link($link);
    return mysqli_thread_id($link);
}

function mysql_escape_string($string) {
    return mysql_real_escape_string($string);
}

function mysql_real_escape_string($string, $link=null) {
    $link = mysql_link($link);
    return mysqli_real_escape_string($link, $string);
}

function mysql_query($sql, $link=null) {
    $link = mysql_link($link);
    return mysqli_query($link, $sql);
}

function mysql_unbuffered_query($sql, $link=null) {
    $link = mysql_link($link);
    return mysqli_query($link, $sql, MYSQLI_USE_RESULT);
}

function mysql_set_charset($charset, $link=null){
    $link = mysql_link($link);
    return mysqli_set_charset($link, $charset);
}

function mysql_get_host_info($link=null) {
    $link = mysql_link($link);
    return mysqli_get_host_info($link);
}

function mysql_get_proto_info($link=null) {
    $link = mysql_link($link);
    return mysqli_get_proto_info($link);
}
function mysql_get_server_info($link=null) {
    $link = mysql_link($link);
    return mysqli_get_server_info($link);
}

function mysql_info($link=null) {
    $link = mysql_link($link);
    return mysqli_info($link);
}

function mysql_get_client_info() {
    $link = mysql_link();
    return mysqli_get_client_info($link);
}

function mysql_create_db($db, $link=null) {
    $link = mysql_link($link);
    $db = str_replace('`', '', mysqli_real_escape_string($link, $db));
    return mysqli_query($link, "CREATE DATABASE `$db`");
}

function mysql_drop_db($db, $link=null) {
    $link = mysql_link($link);
    $db = str_replace('`', '', mysqli_real_escape_string($link, $db));
    return mysqli_query($link, "DROP DATABASE `$db`");
}

function mysql_list_dbs($link=null) {
    $link = mysql_link($link);
    return mysqli_query($link, "SHOW DATABASES");
}

function mysql_list_fields($db, $table, $link=null) {
    $link = mysql_link($link);
    $db = str_replace('`', '', mysqli_real_escape_string($link, $db));
    $table = str_replace('`', '', mysqli_real_escape_string($link, $table));
    return mysqli_query($link, "SHOW COLUMNS FROM `$db`.`$table`");
}

function mysql_list_tables($db, $link=null) {
    $link = mysql_link($link);
    $db = str_replace('`', '', mysqli_real_escape_string($link, $db));
    return mysqli_query($link, "SHOW TABLES FROM `$db`");
}

function mysql_db_query($db, $sql, $link=null) {
    $link = mysql_link($link);
    mysqli_select_db($link, $db);
    return mysqli_query($link, $sql);
}

function mysql_fetch_row($qlink) {
    return mysqli_fetch_row($qlink);
}

function mysql_fetch_assoc($qlink) {
    return mysqli_fetch_assoc($qlink);
}

function mysql_fetch_array($qlink, $result=MYSQLI_BOTH) {
    return mysqli_fetch_array($qlink, $result);
}

function mysql_fetch_lengths($qlink) {
    return mysqli_fetch_lengths($qlink);
}

function mysql_insert_id($qlink) {
    return mysqli_insert_id($qlink);
}

function mysql_num_rows($qlink) {
    return mysqli_num_rows($qlink);
}

function mysql_num_fields($qlink) {
    return mysqli_num_fields($qlink);
}

function mysql_data_seek($qlink, $row) {
    return mysqli_data_seek($qlink, $row);
}

function mysql_field_seek($qlink, $offset) {
    return mysqli_field_seek($qlink, $offset);
}

function mysql_fetch_object($qlink, $class="stdClass", array $params=null) {
    return ($params === null)
        ? mysqli_fetch_object($qlink, $class)
        : mysqli_fetch_object($qlink, $class, $params);
}

function mysql_db_name($qlink, $row, $field='Database') {
    mysqli_data_seek($qlink, $row);
    $db = mysqli_fetch_assoc($qlink);
    return $db[$field];
}

function mysql_fetch_field($qlink, $offset=null) {
    if ($offset !== null)
        mysqli_field_seek($qlink, $offset);
    return mysqli_fetch_field($qlink);
}

function mysql_result($qlink, $offset, $field=0) {
    if ($offset !== null)
        mysqli_field_seek($qlink, $offset);
    $row = mysqli_fetch_array($qlink);
    return (!is_array($row) || !isset($row[$field]))
        ? false
        : $row[$field];
}

function mysql_field_len($qlink, $offset) {
    $field = mysqli_fetch_field_direct($qlink, $offset);
    return is_object($field) ? $field->length : false;
}

function mysql_field_name($qlink, $offset) {
    $field = mysqli_fetch_field_direct($qlink, $offset);
    if (!is_object($field))
        return false;
    return empty($field->orgname) ? $field->name : $field->orgname;
}

function mysql_field_table($qlink, $offset) {
    $field = mysqli_fetch_field_direct($qlink, $offset);
    if (!is_object($field))
        return false;
    return empty($field->orgtable) ? $field->table : $field->orgtable;
}

function mysql_field_type($qlink, $offset) {
    $field = mysqli_fetch_field_direct($qlink, $offset);
    return is_object($field) ? $field->type : false;
}

function mysql_free_result($qlink) {
    try {
        mysqli_free_result($qlink);
    } catch (Exception $e) {
        return false;
    }
    return true;
}

ContentLicense: CC BY-SA 4.0


问:
When do you have to worry about thread safety?
What are some situations where you need to worry about whether a static method is thread safe?

For example, if I have static utility function that doesn't touch any static class level variables, is that method already thread safe? If I have a static method that does touch static class variables, is that method potentially not thread safe?

Thanks in advance.

答:
You have to worry about thread safety whenever you have more than one thread accessing the same resources.

Your static method might be unsafe if it is using the same resources as other threads -- directly or indirectly -- even if those resources are not static class variables.


问:
How to convert this LINQ query syntax that connects two objects to method syntax?
How to do this in method syntax form:

```<code>foreach (var o in from o in orders
                  from oi in o.OrderItems
                  where oi.ProductName == "Widgets"
                  select o.OrderID)
    Console.WriteLine("{0}", o);
</code>```

tried this but not working:

```<code>foreach (var o in orders
    .SelectMany(o => o.OrderItems, (o, oi) => new {<<idk what to put here>> })
    .Where(oi => oi.ProductName == "Widget"))
{
    Console.WriteLine("WIDGET: {0}", o.OrderID);
}
</code>```

Finally I used this code and it worked!

```<code>foreach (var o in orders
    .SelectMany(o => o.OrderItems, (o, oi) => new { o.OrderID, oi.ProductName })
    .Where(oi => oi.ProductName == "Widgets"))
{
    Console.WriteLine("{0}", o.OrderID);
}
</code>```

答:
Method syntax will be like that:</p>

```<code>orders.Where(o=>o.OrderItems.Any(oi=>oi.ProductName == "Widgets")).Select(o=>o.OrderID)
</code>```

Body:
How to do this in method syntax form:

foreach (var o in from o in orders
                  from oi in o.OrderItems
                  where oi.ProductName == "Widgets"
                  select o.OrderID)
    Console.WriteLine("{0}", o);

tried this but not working:

foreach (var o in orders
    .SelectMany(o => o.OrderItems, (o, oi) => new {<<idk what to put here>> })
    .Where(oi => oi.ProductName == "Widget"))
{
    Console.WriteLine("WIDGET: {0}", o.OrderID);
}

Finally I used this code and it worked!

foreach (var o in orders
    .SelectMany(o => o.OrderItems, (o, oi) => new { o.OrderID, oi.ProductName })
    .Where(oi => oi.ProductName == "Widgets"))
{
    Console.WriteLine("{0}", o.OrderID);
}

Body:
Method syntax will be like that:

orders.Where(o=>o.OrderItems.Any(oi=>oi.ProductName == "Widgets")).Select(o=>o.OrderID)


问:
solution of recurrence relations of a program
I have a quiz which asked me to work out the solution of a recurrence relation of a program:

The amount of time,T(n) taken by an algorithm is typically a function of the size,
n, of the input data. Assume that you wrote a program that shows the following time recurrence:

T(n) = T(n/2) + a , if n > 1

T(n) = b, if n= 1

Here is what I have tried:

T(n/2) = T(n/4) + a
  T(n/4) = T(n/8) + a

So:

T(n) = T(n/4) + 2*a = T(n/8) + 3*a = T(n/K) + 3*a

Up to here, I want to make T(n) = 1 which the program should be terminated, so I make

n/K = 1 -> K = n

And i get:

T(n/n) + 3*a = b + 3a

However the answer shows this program have a Logarithmic complexity and the solution should be T(n) = a ∗ log2(n) + b

I do not understand how to get the above solution, can anyone help me?
Thank you!

答:
Think about it like this. At each iteration you halve you problem size n: from n to n/2 to n/4 and so on. You can imagine a "tree", normally you have a formula like T(n) = a * T(n/b) + f(n) then in your tree every node has degree a and the problem size at each node is divided by b. In your case the tree has half the problem size at each level but the degree of the tree nodes stays one.

```<code>n/2: a
     \
n/4:  a
      \
n/8:   a
       \
        ...
        \
n/n:     b + a
</code>```

I assume you see how deep this tree is, and how to arrive at the given complexity you described as solution.

Another way to look at it, closer to your specific exercise: At each iteration you add an a right? How often do you add such an a?

Body:
Think about it like this. At each iteration you halve you problem size n: from n to n/2 to n/4 and so on. You can imagine a "tree", normally you have a formula like T(n) = a * T(n/b) + f(n) then in your tree every node has degree a and the problem size at each node is divided by b. In your case the tree has half the problem size at each level but the degree of the tree nodes stays one.

n/2: a
     \
n/4:  a
      \
n/8:   a
       \
        ...
        \
n/n:     b + a

I assume you see how deep this tree is, and how to arrive at the given complexity you described as solution.

Another way to look at it, closer to your specific exercise: At each iteration you add an a right? How often do you add such an a?


问:
Cursor not displaying in UISearchBar for our app
For the UISearchBars in our app, there's no cursor shown in the bar with focus when running under iOS 7.  How do we make that show?

We are using the SDK 7, with a minimum target of 6.  We do have the translucency off for the navigation bars, and set the color at runtime.  I can't think of anything else we are doing differently.

答:
```<code>searchBar.tintColor = view.tintColor  // self.view usually has the proper tintColor
</code>```

Better than .blue or whatever.

Body:
searchBar.tintColor = view.tintColor  // self.view usually has the proper tintColor

Better than .blue or whatever.


问:
How to use a reset button Java arkanoid game
So  this is part of my game panel for my game. I got my start button to work, and created a reset button but I don't know how to reset the game every single time it is pressed. Does anyone know how to reset the game to its original position after you press "Reset"? Right now it will display the words "You have died", but it doesn't do anything when I press Reset.

```<code>import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;

public class GamePanel extends JPanel
{
   private Brick[][] bary;
   private static final Color BACKGROUND = Color.black;
   private BufferedImage myImage;
   private Graphics myBuffer;
   private Ball ball = new Ball();
   public Bumper bumper;
   private Timer t;
   private int hits = 0;
   private boolean isPlayingGame = false;

   public GamePanel()
   {
      myImage =  new BufferedImage(600, 800, BufferedImage.TYPE_INT_RGB);
      myBuffer = myImage.getGraphics();
      myBuffer.setColor(BACKGROUND);
      myBuffer.fillRect(0, 0, 600,800);

      JButton sbutton = new JButton("Start");
      sbutton.setFocusable(false);
      sbutton.addActionListener(new Listener());
      add(sbutton);
      JButton rbutton = new JButton("Reset");
      rbutton.setFocusable(false);
      rbutton.addActionListener(new Listener());
      add(rbutton);

      bary = new Brick[5][14];

      bumper = new Bumper(270, 775, 60, 10, Color.BLUE);
      ball = new Ball(300, 400, 10, Color.RED);

      t = new Timer(5, new Listener());

      setFocusable(true);
      //addKeyListener(new Key());
   }

   // tick method is called every 10ms by Arkanoid.java
   // only does stuff if game is actually being played
   public void tick()
   {
      if(isPlayingGame)
      {
         ball.move(600,800, 600, 800);
         death(ball);
      }
   }

   // these get called by the BumperLitsener, which is added to the whole frame
   public void moveBumperLeft()
   {
      bumper.setX(bumper.getX()-20);
      //System.out.println("moving bumper left");
   }

   public void moveBumperRight()
   {
      bumper.setX(bumper.getX()+20);
      //System.out.println("moving bumper right");
   }
   /*

   public class Key extends KeyAdapter
   {
      public void keyPressed(KeyEvent e)
      {
         if(e.getKeyCode() == KeyEvent.VK_A)
            bumper.setX(bumper.getX()+10 );
         if(e.getKeyCode() == KeyEvent.VK_S)
            bumper.setX(bumper.getX()-10 );
      }
   }
   */

   public void startGame()
   {
      isPlayingGame = true;
   }

   public void paintComponent(Graphics g)
   {
      // draw myBuffer, then draw that onto g
         myBuffer.setColor(BACKGROUND);
         myBuffer.fillRect(0,0,600,800);
         setLayout(new GridLayout(5, 14));
         myBuffer.setColor(Color.WHITE);

         int b=1;
         int d=40;
         for(int r = 0; r < bary.length; r++)
         {
            for(int c = 0; c < bary[0].length; c++)
            {

               bary[r][c] = new Brick(b, d,40,20, Color.BLUE);
               b=b+43;
               bary[r][c].draw(myBuffer);

            }
            d=d+23;
            b=1;
         }
         ball.draw(myBuffer);
         bumper.draw(myBuffer);
         repaint();
         if(ball.getColor()==Color.BLACK)
         {
         myBuffer.setFont(new Font("MS Comic Sans", Font.ITALIC, 45));
         myBuffer.drawString("GAME OVER!", 168, 300);
         ball.move(0, 0, 0, 0);
         }
      g.drawImage(myImage, 0, 0, getWidth(), getHeight(), null);
   }

   private class Listener implements ActionListener
   {
      public void actionPerformed(ActionEvent e)
      {
         GamePanel.this.getTopLevelAncestor().requestFocus();
         startGame(); // starts game when button is pressed
         System.out.println("Game is starting!");
      }
   }

   private void death(Ball ball)
   {
      double d = ball.getY() + ball.getRadius();

      if(d>800.0)
      {
         ball.setX(300);
         ball.setY(400);
         ball.setdx(ball.getdx()*-1);
         ball.setdy(ball.getdy()*-1);
         ball.setColor(Color.BLACK);
      }
   }

    /* private void collide(Ball ball, Bumper b)
   {
      double d = distance(ball.getX(), ball.getY(), b.getX(), b.getY());
      if(d <= 37.5)
      {
        ball.move();
         hits++;
      }
   }*/
  // private double distance(double x1, double y1, double x2, double y2)
 //  {
   //   return(Math.sqrt(Math.pow(x2 - x1, 2.0) +  Math.pow(y2 - y1, 2.0)));     // enter the calculation here.
   //}

}
</code>```

Thank you so much!!!

答:
Right now, you have a single Listener class and two buttons that have registered against the listener (sbutton and rbutton). It'd be easier if you had different classes that implemented ActionListener, but let's move past that for now.

You need to make modifications to your actionPerformed method such that:

You can differentiate the source of the action - i.e. which button was pressed - Reset or the Start? Hint: use the getSource() method from ActionEvent

If the button pressed was the Reset button, you need to reset the GUI to its initial state

Body:
So  this is part of my game panel for my game. I got my start button to work, and created a reset button but I don't know how to reset the game every single time it is pressed. Does anyone know how to reset the game to its original position after you press "Reset"? Right now it will display the words "You have died", but it doesn't do anything when I press Reset.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;

public class GamePanel extends JPanel
{
   private Brick[][] bary;
   private static final Color BACKGROUND = Color.black;
   private BufferedImage myImage;
   private Graphics myBuffer;
   private Ball ball = new Ball();
   public Bumper bumper;
   private Timer t;
   private int hits = 0;
   private boolean isPlayingGame = false;

   public GamePanel()
   {
      myImage =  new BufferedImage(600, 800, BufferedImage.TYPE_INT_RGB);
      myBuffer = myImage.getGraphics();
      myBuffer.setColor(BACKGROUND);
      myBuffer.fillRect(0, 0, 600,800);

      JButton sbutton = new JButton("Start");
      sbutton.setFocusable(false);
      sbutton.addActionListener(new Listener());
      add(sbutton);
      JButton rbutton = new JButton("Reset");
      rbutton.setFocusable(false);
      rbutton.addActionListener(new Listener());
      add(rbutton);

      bary = new Brick[5][14];

      bumper = new Bumper(270, 775, 60, 10, Color.BLUE);
      ball = new Ball(300, 400, 10, Color.RED);

      t = new Timer(5, new Listener());

      setFocusable(true);
      //addKeyListener(new Key());
   }

   // tick method is called every 10ms by Arkanoid.java
   // only does stuff if game is actually being played
   public void tick()
   {
      if(isPlayingGame)
      {
         ball.move(600,800, 600, 800);
         death(ball);
      }
   }

   // these get called by the BumperLitsener, which is added to the whole frame
   public void moveBumperLeft()
   {
      bumper.setX(bumper.getX()-20);
      //System.out.println("moving bumper left");
   }

   public void moveBumperRight()
   {
      bumper.setX(bumper.getX()+20);
      //System.out.println("moving bumper right");
   }
   /*

   public class Key extends KeyAdapter
   {
      public void keyPressed(KeyEvent e)
      {
         if(e.getKeyCode() == KeyEvent.VK_A)
            bumper.setX(bumper.getX()+10 );
         if(e.getKeyCode() == KeyEvent.VK_S)
            bumper.setX(bumper.getX()-10 );
      }
   }
   */

   public void startGame()
   {
      isPlayingGame = true;
   }

   public void paintComponent(Graphics g)
   {
      // draw myBuffer, then draw that onto g
         myBuffer.setColor(BACKGROUND);
         myBuffer.fillRect(0,0,600,800);
         setLayout(new GridLayout(5, 14));
         myBuffer.setColor(Color.WHITE);

         int b=1;
         int d=40;
         for(int r = 0; r < bary.length; r++)
         {
            for(int c = 0; c < bary[0].length; c++)
            {

               bary[r][c] = new Brick(b, d,40,20, Color.BLUE);
               b=b+43;
               bary[r][c].draw(myBuffer);

            }
            d=d+23;
            b=1;
         }
         ball.draw(myBuffer);
         bumper.draw(myBuffer);
         repaint();
         if(ball.getColor()==Color.BLACK)
         {
         myBuffer.setFont(new Font("MS Comic Sans", Font.ITALIC, 45));
         myBuffer.drawString("GAME OVER!", 168, 300);
         ball.move(0, 0, 0, 0);
         }
      g.drawImage(myImage, 0, 0, getWidth(), getHeight(), null);
   }

   private class Listener implements ActionListener
   {
      public void actionPerformed(ActionEvent e)
      {
         GamePanel.this.getTopLevelAncestor().requestFocus();
         startGame(); // starts game when button is pressed
         System.out.println("Game is starting!");
      }
   }

   private void death(Ball ball)
   {
      double d = ball.getY() + ball.getRadius();

      if(d>800.0)
      {
         ball.setX(300);
         ball.setY(400);
         ball.setdx(ball.getdx()*-1);
         ball.setdy(ball.getdy()*-1);
         ball.setColor(Color.BLACK);
      }
   }

    /* private void collide(Ball ball, Bumper b)
   {
      double d = distance(ball.getX(), ball.getY(), b.getX(), b.getY());
      if(d <= 37.5)
      {
        ball.move();
         hits++;
      }
   }*/
  // private double distance(double x1, double y1, double x2, double y2)
 //  {
   //   return(Math.sqrt(Math.pow(x2 - x1, 2.0) +  Math.pow(y2 - y1, 2.0)));     // enter the calculation here.
   //}

}

Thank you so much!!!


问:
EMDK installation does not see Android Studio
I downloaded Android Studio 2.3.2 and am trying to install the EMDK v6.3 (problem is for other versions as well) and the install wizard is telling me that Android Studio has not been installed on this computer. I am trying to figure out why this is so.</p>

答: That is a known issue with EMDK and Android Studio 2.3 unfortunately.  There is a patch available at https://developer.zebra.com/community/android/android-forums/android-blogs/blog/2017/03/15/android-studio-23-emdk-for-android-beta-fix for EMDK 6.3</p>


问:
Camel AQ routing error TypeConversionException at Xpath
I am using Apache Camel to read messages from Oracle AQ. I am using Camel version 2.19.0, Spring 4 with XML configurations for Camel Routes. While running the application I am getting "Error during type conversion from type: java.lang.String to the required type: org.w3c.dom.Document with value ??? due org.xml.sax.SAXParseException". Can someone please let me know what could be the issue and how to fix it in XML camel configuration.

Here is relevant XML content.

```<code><camelContext id="moveId" shutdownRunningTask="CompleteCurrentTaskOnly" xmlns="http://camel.apache.org/schema/spring" xmlns:dret="http://mycompany.com/data/user">
<route id="dataRoute" errorHandlerRef="transactionErrorHandler">
     <from uri="myAQ:MYDB.AQ_MYQ_Q"/>
        <setHeader headerName="userId">
            <xpath resultType="java.lang.String">//dret:userId</xpath>
        </setHeader>
        <policy ref="PROPAGATION_REQUIRED_MY_AQ">
                <process ref="myEventProcessor"/>
        </policy>
</route>
</code>```

Below is the stack trace.

org.apache.camel.TypeConversionException: Error during type conversion
  from type: java.lang.String to the required type: org.w3c.dom.Document
  with value ??? due org.xml.sax.SAXParseException; lineNumber: 1;
  columnNumber: 1; Content is not allowed in prolog.
                    at org.apache.camel.impl.converter.BaseTypeConverterRegistry.createTypeConversionException(BaseTypeConverterRegistry.java:629)
                    at org.apache.camel.impl.converter.BaseTypeConverterRegistry.convertTo(BaseTypeConverterRegistry.java:150)
                    at org.apache.camel.builder.xml.XPathBuilder.doGetDocument(XPathBuilder.java:1144)
                    at org.apache.camel.builder.xml.XPathBuilder.getDocument(XPathBuilder.java:1123)
                    at org.apache.camel.builder.xml.XPathBuilder.doInEvaluateAs(XPathBuilder.java:915)
                    at org.apache.camel.builder.xml.XPathBuilder.evaluateAs(XPathBuilder.java:809)
                    at org.apache.camel.builder.xml.XPathBuilder.evaluate(XPathBuilder.java:779)
                    at org.apache.camel.builder.xml.XPathBuilder.evaluate(XPathBuilder.java:167)

答: It looks like Oracle AQ Messages are not getting dequeued properly and xml payload is being read as ???. Can you try adding orai18n.jar to the classpath of your application and see if it resolves the issue.

Body:
I am using Apache Camel to read messages from Oracle AQ. I am using Camel version 2.19.0, Spring 4 with XML configurations for Camel Routes. While running the application I am getting "Error during type conversion from type: java.lang.String to the required type: org.w3c.dom.Document with value ??? due org.xml.sax.SAXParseException". Can someone please let me know what could be the issue and how to fix it in XML camel configuration.

Here is relevant XML content.

<camelContext id="moveId" shutdownRunningTask="CompleteCurrentTaskOnly" xmlns="http://camel.apache.org/schema/spring" xmlns:dret="http://mycompany.com/data/user">
<route id="dataRoute" errorHandlerRef="transactionErrorHandler">
     <from uri="myAQ:MYDB.AQ_MYQ_Q"/>
        <setHeader headerName="userId">
            <xpath resultType="java.lang.String">//dret:userId</xpath>
        </setHeader>
        <policy ref="PROPAGATION_REQUIRED_MY_AQ">
                <process ref="myEventProcessor"/>
        </policy>
</route>

Below is the stack trace.

org.apache.camel.TypeConversionException: Error during type conversion
  from type: java.lang.String to the required type: org.w3c.dom.Document
  with value ??? due org.xml.sax.SAXParseException; lineNumber: 1;
  columnNumber: 1; Content is not allowed in prolog.
                    at org.apache.camel.impl.converter.BaseTypeConverterRegistry.createTypeConversionException(BaseTypeConverterRegistry.java:629)
                    at org.apache.camel.impl.converter.BaseTypeConverterRegistry.convertTo(BaseTypeConverterRegistry.java:150)
                    at org.apache.camel.builder.xml.XPathBuilder.doGetDocument(XPathBuilder.java:1144)
                    at org.apache.camel.builder.xml.XPathBuilder.getDocument(XPathBuilder.java:1123)
                    at org.apache.camel.builder.xml.XPathBuilder.doInEvaluateAs(XPathBuilder.java:915)
                    at org.apache.camel.builder.xml.XPathBuilder.evaluateAs(XPathBuilder.java:809)
                    at org.apache.camel.builder.xml.XPathBuilder.evaluate(XPathBuilder.java:779)
                    at org.apache.camel.builder.xml.XPathBuilder.evaluate(XPathBuilder.java:167)


问:
Is there something in WPF similar to Style.BasedOn for DataTemplate?
At the moment, I have two very large DataTemplate objects to display two sets of items in two ListBoxes. The DataTemplates are referenced in the ContentTemplate property in two Styles that are set in the ItemContainerStyle properties of the two ListBoxes. The items are of the same type and the DataTemplates are identical except for the following control:

From DataTemplate1

```<code><TextBlock Style="{StaticResource TextStyle}" FontSize="20" Foreground="White"
HorizontalAlignment="Left" Panel.ZIndex="2" Text="{Binding RemainingTime.TotalHours,
Converter={StaticResource DoubleToIntegerConverter}, StringFormat={}{0:#00}}" />
</code>```

From DataTemplate2

```<code><TextBlock Style="{StaticResource TextStyle}" FontSize="20" Foreground="White"
HorizontalAlignment="Left" Panel.ZIndex="2" Text="{Binding ElapsedTime.TotalHours,
Converter={StaticResource DoubleToIntegerConverter}, StringFormat={}{0:#00}}" />
</code>```

Is there some way to avoid duplicating the whole Dataemplate but still have this one difference in the text binding of this TextBlock in the second template?

答:
I got an answer to this from another post (by Liz). Basically, you can put all common controls into one DataTemplate and then create two more DataTemplates that each use the first one as a ContentTemplate in a ContentPresenter. Then, you can add different controls into one or both of the latter DataTemplates. Liz provided a code example.

```<code><DataTemplate x:Key="UserTemplate">
  <!-- show all the properties of the user class here -->
</DataTemplate>
<DataTemplate DataType="{x:Type local:User}">
  <ContentPresenter Content="{Binding}" ContentTemplate="{StaticResource UserTemplate}"/>
</DataTemplate>
<DataTemplate DataType="{x:Type local:Author}">
  <StackPanel>
    <ContentPresenter Content="{Binding}" ContentTemplate="{StaticResource UserTemplate}"/>
    <!-- show all the additional Author properties here -->
  </StackPanel>
</DataTemplate>
</code>```

Thanks once again Liz.

Body:
At the moment, I have two very large DataTemplate objects to display two sets of items in two ListBoxes. The DataTemplates are referenced in the ContentTemplate property in two Styles that are set in the ItemContainerStyle properties of the two ListBoxes. The items are of the same type and the DataTemplates are identical except for the following control:

From DataTemplate1

<TextBlock Style="{StaticResource TextStyle}" FontSize="20" Foreground="White"
HorizontalAlignment="Left" Panel.ZIndex="2" Text="{Binding RemainingTime.TotalHours,
Converter={StaticResource DoubleToIntegerConverter}, StringFormat={}{0:#00}}" />

From DataTemplate2

<TextBlock Style="{StaticResource TextStyle}" FontSize="20" Foreground="White"
HorizontalAlignment="Left" Panel.ZIndex="2" Text="{Binding ElapsedTime.TotalHours,
Converter={StaticResource DoubleToIntegerConverter}, StringFormat={}{0:#00}}" />

Is there some way to avoid duplicating the whole Dataemplate but still have this one difference in the text binding of this TextBlock in the second template?

Body:
I got an answer to this from another post (by Liz). Basically, you can put all common controls into one DataTemplate and then create two more DataTemplates that each use the first one as a ContentTemplate in a ContentPresenter. Then, you can add different controls into one or both of the latter DataTemplates. Liz provided a code example.

<DataTemplate x:Key="UserTemplate">
  <!-- show all the properties of the user class here -->
</DataTemplate>
<DataTemplate DataType="{x:Type local:User}">
  <ContentPresenter Content="{Binding}" ContentTemplate="{StaticResource UserTemplate}"/>
</DataTemplate>
<DataTemplate DataType="{x:Type local:Author}">
  <StackPanel>
    <ContentPresenter Content="{Binding}" ContentTemplate="{StaticResource UserTemplate}"/>
    <!-- show all the additional Author properties here -->
  </StackPanel>
</DataTemplate>

Thanks once again Liz.


问:
Django migration strategy for renaming a model and relationship fields
I'm planning to rename several models in an existing Django project where there are many other models that have foreign key relationships to the models I would like to rename. I'm fairly certain this will require multiple migrations, but I'm not sure of the exact procedure.

Let's say I start out with the following models within a Django app called myapp:

```<code>class Foo(models.Model):
    name = models.CharField(unique=True, max_length=32)
    description = models.TextField(null=True, blank=True)

class AnotherModel(models.Model):
    foo = models.ForeignKey(Foo)
    is_awesome = models.BooleanField()

class YetAnotherModel(models.Model):
    foo = models.ForeignKey(Foo)
    is_ridonkulous = models.BooleanField()
</code>```

I want to rename the Foo model because the name doesn't really make sense and is causing confusion in the code, and Bar would make for a much clearer name.

From what I have read in the Django development documentation, I'm assuming the following migration strategy:

Step 1

Modify models.py:

```<code>class Bar(models.Model):  # <-- changed model name
    name = models.CharField(unique=True, max_length=32)
    description = models.TextField(null=True, blank=True)

class AnotherModel(models.Model):
    foo = models.ForeignKey(Bar)  # <-- changed relation, but not field name
    is_awesome = models.BooleanField()

class YetAnotherModel(models.Model):
    foo = models.ForeignKey(Bar)  # <-- changed relation, but not field name
    is_ridonkulous = models.BooleanField()
</code>```

Note the AnotherModel field name for foo doesn't change, but the relation is updated to the Bar model. My reasoning is that I shouldn't change too much at once and that if I changed this field name to bar I would risk losing the data in that column.

Step 2

Create an empty migration:

```<code>python manage.py makemigrations --empty myapp
</code>```

Step 3

Edit the Migration class in the migration file created in step 2 to add the RenameModel operation to the operations list:

```<code>class Migration(migrations.Migration):

    dependencies = [
        ('myapp', '0001_initial'),
    ]

    operations = [
        migrations.RenameModel('Foo', 'Bar')
    ]
</code>```

Step 4

Apply the migration:

```<code>python manage.py migrate
</code>```

Step 5

Edit the related field names in models.py:

```<code>class Bar(models.Model):
    name = models.CharField(unique=True, max_length=32)
    description = models.TextField(null=True, blank=True)

class AnotherModel(models.Model):
    bar = models.ForeignKey(Bar)  # <-- changed field name
    is_awesome = models.BooleanField()

class YetAnotherModel(models.Model):
    bar = models.ForeignKey(Bar)  # <-- changed field name
    is_ridonkulous = models.BooleanField()
</code>```

Step 6

Create another empty migration:

```<code>python manage.py makemigrations --empty myapp
</code>```

Step 7

Edit the Migration class in the migration file created in step 6 to add the RenameField operation(s) for any related field names to the operations list:

```<code>class Migration(migrations.Migration):

    dependencies = [
        ('myapp', '0002_rename_fields'),  # <-- is this okay?
    ]

    operations = [
        migrations.RenameField('AnotherModel', 'foo', 'bar'),
        migrations.RenameField('YetAnotherModel', 'foo', 'bar')
    ]
</code>```

Step 8

Apply the 2nd migration:

```<code>python manage.py migrate
</code>```

Aside from updating the rest of the code (views, forms, etc.) to reflect the new variable names, is this basically how the new migration functionality would work?

Also, this seems like a lot of steps. Can the migration operations be condensed in some way?

Thanks!

答:
For Django 1.10, I managed to change two model class names (including a ForeignKey, and with data) by simply running Makemigrations, and then Migrate for the app.  For the Makemigrations step, I had to confirm that I wanted to change the table names.  Migrate changed the names of the tables without a problem.

Then I changed the name of the ForeignKey field to match, and again was asked by Makemigrations to confirm that I wanted to change the name.  Migrate than made the change.

So I took this in two steps without any special file editing.  I did get errors at first because I forgot to change the admin.py file, as mentioned by @wasibigeek.

Body:
I'm planning to rename several models in an existing Django project where there are many other models that have foreign key relationships to the models I would like to rename. I'm fairly certain this will require multiple migrations, but I'm not sure of the exact procedure.

Let's say I start out with the following models within a Django app called myapp:

class Foo(models.Model):
    name = models.CharField(unique=True, max_length=32)
    description = models.TextField(null=True, blank=True)

class AnotherModel(models.Model):
    foo = models.ForeignKey(Foo)
    is_awesome = models.BooleanField()

class YetAnotherModel(models.Model):
    foo = models.ForeignKey(Foo)
    is_ridonkulous = models.BooleanField()

I want to rename the Foo model because the name doesn't really make sense and is causing confusion in the code, and Bar would make for a much clearer name.

From what I have read in the Django development documentation, I'm assuming the following migration strategy:

Step 1

Modify models.py:

class Bar(models.Model):  # <-- changed model name
    name = models.CharField(unique=True, max_length=32)
    description = models.TextField(null=True, blank=True)

class AnotherModel(models.Model):
    foo = models.ForeignKey(Bar)  # <-- changed relation, but not field name
    is_awesome = models.BooleanField()

class YetAnotherModel(models.Model):
    foo = models.ForeignKey(Bar)  # <-- changed relation, but not field name
    is_ridonkulous = models.BooleanField()

Note the AnotherModel field name for foo doesn't change, but the relation is updated to the Bar model. My reasoning is that I shouldn't change too much at once and that if I changed this field name to bar I would risk losing the data in that column.

Step 2

Create an empty migration:

python manage.py makemigrations --empty myapp

Step 3

Edit the Migration class in the migration file created in step 2 to add the RenameModel operation to the operations list:

class Migration(migrations.Migration):

    dependencies = [
        ('myapp', '0001_initial'),
    ]

    operations = [
        migrations.RenameModel('Foo', 'Bar')
    ]

Step 4

Apply the migration:

python manage.py migrate

Step 5

Edit the related field names in models.py:

class Bar(models.Model):
    name = models.CharField(unique=True, max_length=32)
    description = models.TextField(null=True, blank=True)

class AnotherModel(models.Model):
    bar = models.ForeignKey(Bar)  # <-- changed field name
    is_awesome = models.BooleanField()

class YetAnotherModel(models.Model):
    bar = models.ForeignKey(Bar)  # <-- changed field name
    is_ridonkulous = models.BooleanField()

Step 6

Create another empty migration:

python manage.py makemigrations --empty myapp

Step 7

Edit the Migration class in the migration file created in step 6 to add the RenameField operation(s) for any related field names to the operations list:

class Migration(migrations.Migration):

    dependencies = [
        ('myapp', '0002_rename_fields'),  # <-- is this okay?
    ]

    operations = [
        migrations.RenameField('AnotherModel', 'foo', 'bar'),
        migrations.RenameField('YetAnotherModel', 'foo', 'bar')
    ]

Step 8

Apply the 2nd migration:

python manage.py migrate

Aside from updating the rest of the code (views, forms, etc.) to reflect the new variable names, is this basically how the new migration functionality would work?

Also, this seems like a lot of steps. Can the migration operations be condensed in some way?

Thanks!


问:
JavaScript and AJAX not working as expected
I'm using the JavaScript and AJAX for signup form.

I want to post all textboxes in signup form through AJAX but am failing to do so.

signup.php

$(document).ready(function() {
  $('submit').click(function() {
    var first = $('#firstname').val();
    var last = $('#lastname').val();
    var Email = $('#email').val();
    var pass = $('#password').val();
    var confirm = $('#confirmpassword').val();
    var phone = $('#phoneno').val();

    $.ajax({
      type: "POST",
      url: "register.php",
      data: {
        (

          firstname: first,
          lastname: last,
          email: Email,
          password: pass,
          confirmpassword: confirm,
          phoneno: phone,

        )
      },
      success: function(data) {
        alert('passed');
      },
      error: function() {
        alert("error");
      }

    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="jquery-3.2.0.min.js"></script>
<title>
</title>

<div align="right">
</div>
<div id="div">
  <center>
    <h3>REGISTER</h3>
  </center>
  <table>
    <thead>
    </thead>
    <tbody>
      <tr>
        <td>
          <label>Firstname</label>
          <td>
            <input type="text" name="firstname" id="firstname" required="">
          </td>
      </tr>
      <tr>
        <td>
          <label>Lastname</label>
        </td>
        <td>
          <input type="text" name="lastname" id="lastname" required="">
        </td>
      </tr>
      <tr>
        <td>
          <label>Email</label>
        </td>
        <td>
          <input type="text" name="email" id="email" required="">
        </td>
      </tr>
      <tr>
        <td>
          <label>Password</label>
        </td>
        <td>
          <input type="password" name="password" id="password" required="">
        </td>
      </tr>
      <tr>
        <td>
          <label>Confirm password</label>
        </td>
        <td>
          <input type="password" name="confirmpassword" id="confirmpassword" required="">
        </td>
      </tr>
      <tr>
        <td>
          <label>Phone no</label>
        </td>
        <td>
          <input type="text" name="phoneno" id="phoneno" required="">
        </td>
      </tr>
      <tr>
        <td>
        </td>
        <td>
          <input type="button" name="submit" value="submit" id="submit" />
        </td>
      </tr>
      <tr>
        <td>
        </td>
        <td>
        </td>
        <td>
          Login?
        </td>
      </tr>
    </tbody>
  </table>
</div></code>```

register.php

```<code><?php
include 'config.php';
 $firstname=$_POST['firstname'];
 $lastname= $_POST['lastname'];
 $email=$_POST['email'];
 $password=$_POST['password'];
 $confirmpassword=$_POST['confirmpassword'];
 $phoneno=$_POST['phoneno'];
if($password==$confirmpassword)
{
$insertuser=mysql_query("insert into register(firstname,lastname,email,password,confirmpassword,phoneno) values('$firstname','$lastname','$email','$password','$confirmpassword','$phoneno')",$conn)or die(mysql_error());
echo "success";

}
else
{
  echo "failure";

 }
?>
</code>```

答:
hey please replace your jquery code's 2nd line to </p>

```<code>$('#submit').click(function(e){
                e.preventDefault();
</code>```

Body:
I'm using the JavaScript and AJAX for signup form.

I want to post all textboxes in signup form through AJAX but am failing to do so.

signup.php

$(document).ready(function() {
  $('submit').click(function() {
    var first = $('#firstname').val();
    var last = $('#lastname').val();
    var Email = $('#email').val();
    var pass = $('#password').val();
    var confirm = $('#confirmpassword').val();
    var phone = $('#phoneno').val();

    $.ajax({
      type: "POST",
      url: "register.php",
      data: {
        (

          firstname: first,
          lastname: last,
          email: Email,
          password: pass,
          confirmpassword: confirm,
          phoneno: phone,

        )
      },
      success: function(data) {
        alert('passed');
      },
      error: function() {
        alert("error");
      }

    });
  });
});

<title>
</title>

REGISTER

          Firstname

            <input type="text" name="firstname" id="firstname" required="">

          Lastname

          <input type="text" name="lastname" id="lastname" required="">

          Email

          <input type="text" name="email" id="email" required="">

          Password

          <input type="password" name="password" id="password" required="">

          Confirm password

          <input type="password" name="confirmpassword" id="confirmpassword" required="">

          Phone no

          <input type="text" name="phoneno" id="phoneno" required="">

          <input type="button" name="submit" value="submit" id="submit" />

          Login?

register.php

<?php
include 'config.php';
 $firstname=$_POST['firstname'];
 $lastname= $_POST['lastname'];
 $email=$_POST['email'];
 $password=$_POST['password'];
 $confirmpassword=$_POST['confirmpassword'];
 $phoneno=$_POST['phoneno'];
if($password==$confirmpassword)
{
$insertuser=mysql_query("insert into register(firstname,lastname,email,password,confirmpassword,phoneno) values('$firstname','$lastname','$email','$password','$confirmpassword','$phoneno')",$conn)or die(mysql_error());
echo "success";

}
else
{
  echo "failure";

 }
?>

Body:
hey please replace your jquery code's 2nd line to

$('#submit').click(function(e){
                e.preventDefault();


问:
git clone connection refused
I'm pretty new and trying to set up an environment for my Econotag.
Using this guide
https://github.com/malvira/libmc1322x/wiki/libmc1322x
I am getting an error message .

```<code>user@instant-contiki:~$ git clone git://git.devl.org/git/malvira/libmc1322x.git
Cloning into 'libmc1322x'...
fatal: unable to connect to git.devl.org:
git.devl.org[0: 209.208.78.21]: errno=Connection refused
</code>```

How to get around this

答:
I also faced same problem I tried all nothing worked later on I come to know there is problem on server.
Please check basic things before trying other experiments that might save your time.</p>

Title: git clone connection refused

Body:
I'm pretty new and trying to set up an environment for my Econotag.
Using this guide
https://github.com/malvira/libmc1322x/wiki/libmc1322x
I am getting an error message .

user@instant-contiki:~$ git clone git://git.devl.org/git/malvira/libmc1322x.git
Cloning into 'libmc1322x'...
fatal: unable to connect to git.devl.org:
git.devl.org[0: 209.208.78.21]: errno=Connection refused

How to get around this


问:
Azure App hosted docker port 25
When creating an Azure App Service with a Docker image. Is it possible to listen on other ports than 80 and 443 from the Docker image?

My requirement is that TCP port 25 from the Docker image is externally reachable.

答:
As Azure Web App sandbox states about Networking Restrictions/Considerations:

Network endpoint listening

The only way an application can be accessed via the internet is through the already-exposed HTTP (80) and HTTPS (443) TCP ports; applications may not listen on other ports for packets arriving from the internet.
However, applications may create a socket which can listen for connections from within the sandbox. For example, two processes within the same app may communicate with one another via TCP sockets; connection attempts incoming from outside the sandbox, albeit they be on the same machine, will fail. See the next topic for additional detail.

Title: Azure App hosted docker port 25


问:
Tab key is not working in firefox
I have the folling code, when it triggers the tab key is not working in firefox but works in chrome.

HTML:

```<code><input id="contactPhone" onkeypress="validationPhone(event)" data-bind='value: phone' type="text" class="form-control" maxlength='10'>
</code>```

Here is the JS code:

```<code>  validationPhone = function (x) {
      var evt = window.event || x;

      if ((evt.which > 46 && evt.which < 58) || evt.which == 8) {
          return true;
      }
      else {
          evt.preventDefault();
      }
  }
</code>```

答:
you are using Javascript Char Code , You can use char code 9 for tab and Instead of onkeypress use onkeydown event

Try With this :

HTML:

```<code><input id="contactPhone" onkeydown="validationPhone(event)" data-bind='value: phone' type="text" class="form-control" maxlength='10'>
</code>```

JS:

```<code>validationPhone = function (x) {
  var evt = window.event || x;

  if ((evt.which > 46 && evt.which < 58) || evt.which == 8 ||evt.which == 9) {
      return true;
  }
  else {
      evt.preventDefault();
  }
</code>```

}

Title: Tab key is not working in firefox

Body:
I have the folling code, when it triggers the tab key is not working in firefox but works in chrome.

HTML:

<input id="contactPhone" onkeypress="validationPhone(event)" data-bind='value: phone' type="text" class="form-control" maxlength='10'>

Here is the JS code:

  validationPhone = function (x) {
      var evt = window.event || x;

      if ((evt.which > 46 && evt.which < 58) || evt.which == 8) {
          return true;
      }
      else {
          evt.preventDefault();
      }
  }

Body:
you are using Javascript Char Code , You can use char code 9 for tab and Instead of onkeypress use onkeydown event

Try With this :

HTML:

<input id="contactPhone" onkeydown="validationPhone(event)" data-bind='value: phone' type="text" class="form-control" maxlength='10'>

JS:

validationPhone = function (x) {
  var evt = window.event || x;

  if ((evt.which > 46 && evt.which < 58) || evt.which == 8 ||evt.which == 9) {
      return true;
  }
  else {
      evt.preventDefault();
  }

}