问:
function used from within javascript dojo closure using "this"-notation is undefined
I have a Problem accessing an Object function using "this".
In case of the below example (which is simplified, because I cannot supply actual code due to various reasons) the function call this._getEntry() is "undefined" when calling
createList().

I would hope for some opinions on wether this is due to a misunderstanding of
javascript closures or rather a syntax error.

In the latter case I will have to find the error in the actual code myself.

If it is a misunderstanding of javascript or dojo concepts I would really appreciate
some help on how to correctly scope and access the below mentioned function (_getEntry()).

```<code>var OBJECT = {
  _getEntry : function(entry){
    var li = document.createElement('LI');
    li.appendChild(document.createTextNode(entry));
    return li;
  },
  createList : function(entryArray){
    var list = document.createElement('UL');
    dojo.forEach(entryArray,function(entry){
      list.appendChild(this._getEntry(entry));
    });
    dojo.body().appendChild(list);
  }
};
OBJECT.createList(["entry1","entry2"]);
</code>```

thanks!

答:
Firstly, I think your pasted code is missing ); to complete the forEach.

Secondly, forEach takes an optional third parameter which determines the context in which the passed function runs.  If not given, it defaults to the global scope, so yes this is your problem.  Assuming this already refers to what you need it to immediately outside the forEach, you should be able to just pass this in as the third argument to forEach and it should work, e.g.:

```<code>dojo.forEach(entryArray, function(entry){
  list.appendChild(this._getEntry(entry));
}, this);
</code>```

For more information: http://dojotoolkit.org/api/dojo/forEach - which is based on the API in JS 1.6 https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach

Body:
I have a Problem accessing an Object function using "this".
In case of the below example (which is simplified, because I cannot supply actual code due to various reasons) the function call this._getEntry() is "undefined" when calling
createList().

I would hope for some opinions on wether this is due to a misunderstanding of
javascript closures or rather a syntax error.

In the latter case I will have to find the error in the actual code myself.

If it is a misunderstanding of javascript or dojo concepts I would really appreciate
some help on how to correctly scope and access the below mentioned function (_getEntry()).

var OBJECT = {
  _getEntry : function(entry){
    var li = document.createElement('LI');
    li.appendChild(document.createTextNode(entry));
    return li;
  },
  createList : function(entryArray){
    var list = document.createElement('UL');
    dojo.forEach(entryArray,function(entry){
      list.appendChild(this._getEntry(entry));
    });
    dojo.body().appendChild(list);
  }
};
OBJECT.createList(["entry1","entry2"]);

thanks!

Body:
Firstly, I think your pasted code is missing ); to complete the forEach.

Secondly, forEach takes an optional third parameter which determines the context in which the passed function runs.  If not given, it defaults to the global scope, so yes this is your problem.  Assuming this already refers to what you need it to immediately outside the forEach, you should be able to just pass this in as the third argument to forEach and it should work, e.g.:

dojo.forEach(entryArray, function(entry){
  list.appendChild(this._getEntry(entry));
}, this);

For more information: http://dojotoolkit.org/api/dojo/forEach - which is based on the API in JS 1.6 https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach


来源: stackexchange

问:
serialize inputs inside element (not form)
I have a HTML like:

```<code><table>
    <tr id="01">
        <td><input name="x"></td>
        <td><input name="y"></td>
    </tr>
    <tr id="02">
        <td><input name="x"></td>
        <td><input name="y"></td>
    </tr>
</table>
</code>```

And I'm trying to make a JSON string of the inputs only on a specific row. Would there be a good solution for this? Something like:

```<code>json = $('#01').serialize();
</code>```

but I need a json instead of the URLEncode'd string the serialize() provides.

答:
serialize() won't give you the JSON you're after. It'll only give you a URLEncode'd string. Example:

//test all inputs on row #02
window.tester = function() {
 console.log($('#02 input').serialize());
};

//test all inputs
window.tester2 = function() {
 console.log($('input').serialize());
};

//test only "y" inputs
window.tester3 = function() {
 console.log($("input[name='y']").serialize());
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
    <tr id="01">
        <td><input name="x" value="1"></td>
        <td><input name="y" value="2"></td>
    </tr>
    <tr id="02">
        <td><input name="x" value="3"></td>
        <td><input name="y" value="4"></td>
    </tr>
</table>
<div>
  <input type="button" onclick="tester()" value="Test Row 02" /><br />
  <input type="button" onclick="tester2()" value="Test All Inputs" /><br />
  <input type="button" onclick="tester3()" value="Test Only 'y' Inputs" />
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script></code>```

Produces:

```<code>x=3&y=4
x=1&y=2&x=3&y=4
y=2&y=4
</code>```

If it's JSON you want, then you'll need to be specific about what format you're after. An array? A hash? In any case, the selectors above are what you'll want to start with, then at some point, you'll want to run the value through:

```<code>JSON.stringify(myResults);
</code>```

window.arrayIt = function () {
  var arrVal = $('#02 input').toArray();
  var arr = arrVal.map(function (i) {
    var x = {};
    x[i.name] = i.value;
    return x;
  });
  console.log(JSON.stringify(arr));
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
    <tr id="01">
        <td><input name="x" value="1"></td>
        <td><input name="y" value="2"></td>
    </tr>
    <tr id="02">
        <td><input name="x" value="3"></td>
        <td><input name="y" value="4"></td>
    </tr>
</table>
<button onclick="arrayIt()">Array It!</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script></code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a HTML like:

        <input name="x">
        <input name="y">

        <input name="x">
        <input name="y">

And I'm trying to make a JSON string of the inputs only on a specific row. Would there be a good solution for this? Something like:

json = $('#01').serialize();

but I need a json instead of the URLEncode'd string the serialize() provides.

Body:
serialize() won't give you the JSON you're after. It'll only give you a URLEncode'd string. Example:

//test all inputs on row #02
window.tester = function() {
 console.log($('#02 input').serialize());
};

//test all inputs
window.tester2 = function() {
 console.log($('input').serialize());
};

//test only "y" inputs
window.tester3 = function() {
 console.log($("input[name='y']").serialize());
};

<table>
    <tr id="01">
        <td><input name="x" value="1"></td>
        <td><input name="y" value="2"></td>
    </tr>
    <tr id="02">
        <td><input name="x" value="3"></td>
        <td><input name="y" value="4"></td>
    </tr>
</table>
<div>
  <input type="button" onclick="tester()" value="Test Row 02" /><br />
  <input type="button" onclick="tester2()" value="Test All Inputs" /><br />
  <input type="button" onclick="tester3()" value="Test Only 'y' Inputs" />
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

Produces:

x=3&y=4
x=1&y=2&x=3&y=4
y=2&y=4

If it's JSON you want, then you'll need to be specific about what format you're after. An array? A hash? In any case, the selectors above are what you'll want to start with, then at some point, you'll want to run the value through:

JSON.stringify(myResults);

window.arrayIt = function () {
  var arrVal = $('#02 input').toArray();
  var arr = arrVal.map(function (i) {
    var x = {};
    x[i.name] = i.value;
    return x;
  });
  console.log(JSON.stringify(arr));
}

<table>
    <tr id="01">
        <td><input name="x" value="1"></td>
        <td><input name="y" value="2"></td>
    </tr>
    <tr id="02">
        <td><input name="x" value="3"></td>
        <td><input name="y" value="4"></td>
    </tr>
</table>
<button onclick="arrayIt()">Array It!</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>


问:
How to import a Specific Contact's phone number?
I'm trying to Read Phone number of a Contact Selected using Contact Picker.
The Display Name works fine, But Phone number doesn't.
Code:

```<code>//calling Contact Picker
public void CPick(View v){
        Intent intent=new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
        startActivityForResult(intent, PICK_CONTACT);
    }
    @Override
//Contact Picker here:
    protected void onActivityResult(int reqCode, int resultCode, Intent data){
        super.onActivityResult(reqCode,resultCode, data);

        if (reqCode==PICK_CONTACT){
            if(resultCode==AppCompatActivity.RESULT_OK){
                Uri contatctData=data.getData();
                Cursor c=getContentResolver().query(contatctData,null,null,null,null);
                if (c.moveToFirst()){
                    //String name=c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
//Above line works Fine

                    String name=c.getString(c.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
//Above line gives error on runtime "invalid column"
                    Toast.makeText(this,"U have picked:"+name,Toast.LENGTH_SHORT).show();

                }
            }

        }
    }
</code>```

Anyhelp will be very Appreciated because I couldn't find relevant answer anywhere.

答:
Try this method:

```<code>private void retrieveContactNumber() {

  String contactNumber = null;

  // getting contacts ID
  Cursor cursorID = getContentResolver().query(uriContact,
        new String[]{ContactsContract.Contacts._ID},
        null, null, null);

  if (cursorID.moveToFirst()) {

    contactId = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID));
  }

  cursorID.close();

  Log.d(TAG, "Contact ID: " + contactId);

  // Using the contact ID now we will get contact phone number
  Cursor cursorPhone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
        new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},

        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
                ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
                ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,

        new String[]{contactId}, null);

  if (cursorPhone.moveToFirst()) {
    contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
  }

  cursorPhone.close();

  Log.d(TAG, "Contact Phone Number: " + contactNumber);
}
</code>```

You should see the contact number in your logcat.

Body:
I'm trying to Read Phone number of a Contact Selected using Contact Picker.
The Display Name works fine, But Phone number doesn't.
Code:

//calling Contact Picker
public void CPick(View v){
        Intent intent=new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
        startActivityForResult(intent, PICK_CONTACT);
    }
    @Override
//Contact Picker here:
    protected void onActivityResult(int reqCode, int resultCode, Intent data){
        super.onActivityResult(reqCode,resultCode, data);

        if (reqCode==PICK_CONTACT){
            if(resultCode==AppCompatActivity.RESULT_OK){
                Uri contatctData=data.getData();
                Cursor c=getContentResolver().query(contatctData,null,null,null,null);
                if (c.moveToFirst()){
                    //String name=c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
//Above line works Fine

                    String name=c.getString(c.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
//Above line gives error on runtime "invalid column"
                    Toast.makeText(this,"U have picked:"+name,Toast.LENGTH_SHORT).show();

                }
            }

        }
    }

Anyhelp will be very Appreciated because I couldn't find relevant answer anywhere.

Body:
Try this method:

private void retrieveContactNumber() {

  String contactNumber = null;

  // getting contacts ID
  Cursor cursorID = getContentResolver().query(uriContact,
        new String[]{ContactsContract.Contacts._ID},
        null, null, null);

  if (cursorID.moveToFirst()) {

    contactId = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID));
  }

  cursorID.close();

  Log.d(TAG, "Contact ID: " + contactId);

  // Using the contact ID now we will get contact phone number
  Cursor cursorPhone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
        new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},

        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
                ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
                ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,

        new String[]{contactId}, null);

  if (cursorPhone.moveToFirst()) {
    contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
  }

  cursorPhone.close();

  Log.d(TAG, "Contact Phone Number: " + contactNumber);
}

You should see the contact number in your logcat.


问:
How to stop JBehave from trimming multiline parameters?
I have a step where I need to check certain message. I used a multi-line parameter:

```<code>Then I see welcome message: 'Welcome to our site!
Some more text
Even more text'
</code>```

Problem is that message should have spaces at the end of first and second lines (IDK why, but it should). And JBehave trims spaces from each line. So test fails.

How can I set it not to trim this parameter?

I've tried writing \n instead of actual line-breaks, but it wasn't replaced with line-breaks

Also tried adding {trim=false} in the beginning of parameter, but it reads it as part of the parameter.

Made some experiments with quotation marks (used ", ', none), it didn't help either...

答:
I have tested that and it seems that JBehave actually truncates spaces at the end of the test:

```<code>When some step with multitline parameter:first line has 10 spaces at the end
Second line has 6 spaces at the end
Third line has no spaces at the end, but fourth line has 8 spaces

Fifth line has 3 spaces, and Sixth line has only 7 spaces
</code>```

```<code>    @When("some step with multitline parameter:$lines")
    public void stepWithMultilneString(String s) {

        String lines [] = s.split("\\r?\\n");

        for(int i = 0; i < lines.length; i++) {
            System.out.format("Line %d is: >>%s<<\n", i+1, lines[i]);
        }
    }

Line 1 is: >>first line has 10 spaces at the end          <<
Line 2 is: >>Second line has 6 spaces at the end      <<
Line 3 is: >>Third line has no spaces at the end, but fourth line has 8 spaces<<
Line 4 is: >>        <<
Line 5 is: >>Fifth line has 3 spaces, and Sixth line has only 7 spaces<<
When some step with multitline parameter:first line has 10 spaces at the end
Second line has 6 spaces at the end
Third line has no spaces at the end, but fourth line has 8 spaces

Fifth line has 3 spaces, and Sixth line has only 7 spaces
</code>```

I suggest a bypass - a step with delimiters ! at the beginning and end of the text:

```<code>When step with multitline parameter surrounded by !:!first line has 10 spaces at the end
Second line has 6 spaces at the end
Third line has no spaces at the end, but fourth line has 8 spaces

Fifth line has 3 spaces, and Sixth line has only 7 spaces

!
</code>```

```<code>    @When("step with multitline parameter surrounded by !:$string")
    public void stepWithMultilneStringVersion2(String s) {

        if( s.startsWith("!")) {
            s = s.substring(1);
        }
        if( s.endsWith("!")) {
            s = s.substring(0, s.length()-1);
        }

        String lines [] = s.split("\\r?\\n");

        for(int i = 0; i < lines.length; i++) {
            System.out.format("Line %d is: >>%s<<\n", i+1, lines[i]);
        }
    }

Line 1 is: >>first line has 10 spaces at the end          <<
Line 2 is: >>Second line has 6 spaces at the end      <<
Line 3 is: >>Third line has no spaces at the end, but fourth line has 8 spaces<<
Line 4 is: >>        <<
Line 5 is: >>Fifth line has 3 spaces, and Sixth line has only 7 spaces   <<
Line 6 is: >>       <<
When step with multitline parameter surrounded by !:!first line has 10 spaces at the end
Second line has 6 spaces at the end
Third line has no spaces at the end, but fourth line has 8 spaces

Fifth line has 3 spaces, and Sixth line has only 7 spaces

!
</code>```

Body:
I have a step where I need to check certain message. I used a multi-line parameter:

Then I see welcome message: 'Welcome to our site!
Some more text
Even more text'

Problem is that message should have spaces at the end of first and second lines (IDK why, but it should). And JBehave trims spaces from each line. So test fails.

How can I set it not to trim this parameter?

I've tried writing \n instead of actual line-breaks, but it wasn't replaced with line-breaks

Also tried adding {trim=false} in the beginning of parameter, but it reads it as part of the parameter.

Made some experiments with quotation marks (used ", ', none), it didn't help either...

Body:
I have tested that and it seems that JBehave actually truncates spaces at the end of the test:

When some step with multitline parameter:first line has 10 spaces at the end
Second line has 6 spaces at the end
Third line has no spaces at the end, but fourth line has 8 spaces

Fifth line has 3 spaces, and Sixth line has only 7 spaces

    @When("some step with multitline parameter:$lines")
    public void stepWithMultilneString(String s) {

        String lines [] = s.split("\\r?\\n");

        for(int i = 0; i < lines.length; i++) {
            System.out.format("Line %d is: >>%s<<\n", i+1, lines[i]);
        }
    }

Line 1 is: >>first line has 10 spaces at the end          <<
Line 2 is: >>Second line has 6 spaces at the end      <<
Line 3 is: >>Third line has no spaces at the end, but fourth line has 8 spaces<<
Line 4 is: >>        <<
Line 5 is: >>Fifth line has 3 spaces, and Sixth line has only 7 spaces<<
When some step with multitline parameter:first line has 10 spaces at the end
Second line has 6 spaces at the end
Third line has no spaces at the end, but fourth line has 8 spaces

Fifth line has 3 spaces, and Sixth line has only 7 spaces

I suggest a bypass - a step with delimiters ! at the beginning and end of the text:

When step with multitline parameter surrounded by !:!first line has 10 spaces at the end
Second line has 6 spaces at the end
Third line has no spaces at the end, but fourth line has 8 spaces

Fifth line has 3 spaces, and Sixth line has only 7 spaces

!

    @When("step with multitline parameter surrounded by !:$string")
    public void stepWithMultilneStringVersion2(String s) {

        if( s.startsWith("!")) {
            s = s.substring(1);
        }
        if( s.endsWith("!")) {
            s = s.substring(0, s.length()-1);
        }

        String lines [] = s.split("\\r?\\n");

        for(int i = 0; i < lines.length; i++) {
            System.out.format("Line %d is: >>%s<<\n", i+1, lines[i]);
        }
    }

Line 1 is: >>first line has 10 spaces at the end          <<
Line 2 is: >>Second line has 6 spaces at the end      <<
Line 3 is: >>Third line has no spaces at the end, but fourth line has 8 spaces<<
Line 4 is: >>        <<
Line 5 is: >>Fifth line has 3 spaces, and Sixth line has only 7 spaces   <<
Line 6 is: >>       <<
When step with multitline parameter surrounded by !:!first line has 10 spaces at the end
Second line has 6 spaces at the end
Third line has no spaces at the end, but fourth line has 8 spaces

Fifth line has 3 spaces, and Sixth line has only 7 spaces

!


问:
is there anyway to detect which part of hand is touching the object in interaction engine (Leap Motion & Unity3D)
I am trying to build a application which includes using leap motion interaction engine to move the object in unity 3d. However, i also need to find out which fingers are touching the object when interacting with object in unity. Is there anyway i can do that? Thanks in advance!!</p>

答:
Strictly speaking, the Grasping logic of the Interaction Engine has to check this very thing in order to initiate or release grasps, but it doesn't have a friendly API for accessing this information.

A more convenient way to express this, even though it's not the most efficient way, would be to detect when a hand is intersecting with the interaction object and checking the distance between each fingertip and the object.

All InteractionControllers that are intersecting with a given InteractionBehaviour can be accessed via its contactingControllers property; using the Query library included in Leap tools for Unity, you can convert a bunch of Interaction Controller references to a bunch of Leap Hands without too much effort, and then perform the check:

using Leap.Unity;
using Leap.Unity.Interaction;
using Leap.Unity.Query;
using UnityEngine;

public class QueryFingertips : MonoBehaviour {

  public InteractionBehaviour intObj;

  private Collider[] _collidersBuffer = new Collider[16];
  private float _fingertipRadius = 0.01f; // 1 cm

  void FixedUpdate() {
    foreach (var contactingHand in intObj.contactingControllers
                                         .Query()
                                         .Select(controller => controller.intHand)
                                         .Where(intHand => intHand != null)
                                         .Select(intHand => intHand.leapHand)) {

      foreach (var finger in contactingHand.Fingers) {
        var fingertipPosition = finger.TipPosition.ToVector3();

        // If the distance from the fingertip and the object is less
        // than the 'fingertip radius', the fingertip is touching the object.
        if (intObj.GetHoverDistance(fingertipPosition) < _fingertipRadius) {
          Debug.Log("Found collision for fingertip: " + finger.Type);
        }
      }
    }
  }

}
```


问:
how do I add openlayers as a library to my oracle jet project?
I created an oracle jet project using ojet create, build, serve commands. Alternatively, I have also created the project using NetBeans 8.2 IDE. I am not able to add open layers as a library. I want to create a web application which would consist of maps.</p>

答:
Not sure why you are not able to add the library, as you haven't specified how
you tried to add it and what was the error, if any.

This is what I would do:

After ojet create run the command npm install --save ol. This adds the library in your node_modules folder and also adds it to your package.json. If you don't want to add it to your package.json use only npm install ol.

Navigate to scripts folder -> config folder -> oraclejet-build.js. See the commented lines 37 to 45? Uncomment those lines and add your own library paths, like this:

```<code>copyCustomLibsToStaging: {
  fileList: [
   {
     cwd:'node_modules/ol/',
     src: ['*'],
     dest: 'web/js/libs/ol'
   }
  ]
 },
</code>```

You can now access your library by using the require module. Assuming you created an ojet project using a template, you can provide access to this library from the 'main.js' file.

Body:
Not sure why you are not able to add the library, as you haven't specified how
you tried to add it and what was the error, if any.

This is what I would do:

After ojet create run the command npm install --save ol. This adds the library in your node_modules folder and also adds it to your package.json. If you don't want to add it to your package.json use only npm install ol.

Navigate to scripts folder -> config folder -> oraclejet-build.js. See the commented lines 37 to 45? Uncomment those lines and add your own library paths, like this:

copyCustomLibsToStaging: {
  fileList: [
   {
     cwd:'node_modules/ol/',
     src: ['*'],
     dest: 'web/js/libs/ol'
   }
  ]
 },

You can now access your library by using the require module. Assuming you created an ojet project using a template, you can provide access to this library from the 'main.js' file.


问:
box2d collision groups
does anyone know whether bodies only collide when (body1.categoryBits & body2.maskBits) && (body1.maskBits & body2.categoryBits) ?
 or do they already collide when (body1.categoryBits & body2.maskBits) || (body1.maskBits & body2.categoryBits) ?</p>

答:
Looking at the source of Box2d, it shows that if the fixtures belong to different groups (or the groups are 0) then the catgory and masks are compared as follows:

```<code>    bool collide = (filterA.maskBits & filterB.categoryBits) != 0 &&
                   (filterA.categoryBits & filterB.maskBits) != 0;
</code>```

So it looks like fixture only collide if the collision is allowed by both fixtures' masks.  (IE: AND logic)

OwnerDisplayName: boscop

ContentLicense: CC BY-SA 2.5

Title: box2d collision groups

Body:
Looking at the source of Box2d, it shows that if the fixtures belong to different groups (or the groups are 0) then the catgory and masks are compared as follows:

    bool collide = (filterA.maskBits & filterB.categoryBits) != 0 &&
                   (filterA.categoryBits & filterB.maskBits) != 0;

So it looks like fixture only collide if the collision is allowed by both fixtures' masks.  (IE: AND logic)


问:
Why is apiKeyRequired = AnnotationBoolean.TRUE not enforced?
I am building GAE standard endpoint with Java using Maven dependency:

```<code>    <dependency>
        <groupId>com.google.endpoints</groupId>
        <artifactId>endpoints-framework</artifactId>
        <version>${endpoints.framework.version}</version>
    </dependency>
</code>```

where

```<code>    <endpoints.framework.version>2.0.9</endpoints.framework.version>
</code>```

Annotating API with:

```<code> @Api( name = "blah",
       version = "v1",
       apiKeyRequired = AnnotationBoolean.TRUE,

 @ApiMethod( name = "taxdocument.store",
             path = "taxdoc/store",
             httpMethod = HttpMethod.POST )
</code>```

But API is not enforcing API keys.

Perhaps I am not understanding. I am expecting that POST to this would work.

```<code>https://blah.appspot.com/_ah/api/blah/v1/taxdoc/store?key=valid-key
</code>```

But this would fail

```<code>https://blah.appspot.com/_ah/api/blah/v1/taxdoc/store?key=invalid-key
https://blah.appspot.com/_ah/api/blah/v1/taxdoc/store
</code>```

But ALL succeed with no errors.

Can anyone steer me in the right direction? Thanks.

答: You need to include the API management library and filters.</p>

Body:
I am building GAE standard endpoint with Java using Maven dependency:

    <dependency>
        <groupId>com.google.endpoints</groupId>
        <artifactId>endpoints-framework</artifactId>
        <version>${endpoints.framework.version}</version>
    </dependency>

where

    <endpoints.framework.version>2.0.9</endpoints.framework.version>

Annotating API with:

 @Api( name = "blah",
       version = "v1",
       apiKeyRequired = AnnotationBoolean.TRUE,

 @ApiMethod( name = "taxdocument.store",
             path = "taxdoc/store",
             httpMethod = HttpMethod.POST )

But API is not enforcing API keys.

Perhaps I am not understanding. I am expecting that POST to this would work.

https://blah.appspot.com/_ah/api/blah/v1/taxdoc/store?key=valid-key

But this would fail

https://blah.appspot.com/_ah/api/blah/v1/taxdoc/store?key=invalid-key
https://blah.appspot.com/_ah/api/blah/v1/taxdoc/store

But ALL succeed with no errors.

Can anyone steer me in the right direction? Thanks.


问:
clojure jdbc -> async channel -> csv file... why am i not lazy?
I'm trying to get a better understanding of core.async and channels and such.

My task at hand is to issue a jdbc select statement on a database and stream the results onto an async channel.

I want to have a mutually exclusive thread take from this channel and write to a csv file using clojure.data.csv.

When running the program below, it appears it's not happening lazily... I'm getting no output to the terminal and then everything appears at once, and my csv file has 50 rows.  I hoping someone can help me understand as to why.

Thanks in advance,

```<code>(ns db-async-test.core-test
  (:require [clojure.java.jdbc  :as j]
            [clojure.java.io    :as io]
            [clojure.data.csv   :as csv]
            [clojure.core.async :as async :refer [>! <! >!! <!!  chan thread]]
            [clojure.string     :as str]
            [while-let.core     :refer [while-let]]))

(defn db->chan [ch {:keys [sql db-spec]} ]
  "Given input channel ch, sql select, and db-spec connection info, put db
  hash-maps onto ch in a separate thread. Through back pressure I'm hoping to
  populate channel lazily as a consumer does downstream processing."
  (println "starting fetch...")
  (let [
        row-count           (atom 0)  ; For state on rows
        db-connection       (j/get-connection db-spec)
        statement (j/prepare-statement
                   db-connection
                   sql {
                        :result-type :forward-only  ;; you need this to be lazy
                        :fetch-size 3               ;; also this
                        :max-rows   0
                        :concurrency :read-only})
        row-fn (fn[d] (do
                       (>!! ch d)
                       ;; everything below is just for printing to stdout and
                       ;; trying to understand where my non-lazy bottleneck is.
                       (swap! row-count inc)
                       (when (zero? (mod @row-count 5))
                         (do
                           #_(Thread/sleep 2000 )
                           (println "\tFetched " @row-count " rows.")
                           (flush)
                           ))))]
    (thread
      (j/query db-connection [statement]
               {:as-arrays?    false
                :result-set-fn vec
                :row-fn row-fn
                })
      ;; as producer we finished popluting the chan, now close in this same
      ;; thread.
      (println "producer closing channel... (hopefully you have written rows by now...")
      (async/close! ch))))

(defn chan->csv [ch csv-file ]
  "With input channel ch and output file csv-file, read values off ch and write
  to csv file in a separate thread."
  (thread
    (println "starting csv write...")
    (def row-count (atom 0))
    (with-open [^java.io.Writer writer (io/writer csv-file :append false :encoding "UTF-8")]
      (while-let [data (<!! ch)]
        (swap! row-count inc)
        (csv/write-csv writer [data] :quote? (fn[x] false) )
        (when (zero? (mod @row-count 2))
          (do
            #_(Thread/sleep 2000 )
            (println "Wrote " @row-count " rows.")
            (.flush writer)
            (flush)))
        ))))

(def config {:db-spec {:classname "org.postgres.Driver"
                       :subprotocol "postgres"
                       :subname "//my-database-host:5432/mydb"
                       :user "me"
                       :password "****"}
             :sql "select row_id, giant_xml_column::text as xml_column from public.big_toasty_table limit 50"})

;; main sorta thing
(do
  (def ch (chan 1))
  (db->chan ch config)
  ;; could pipeline with transducers/etc at some point.
  (chan->csv ch "./test.csv"))
</code>```

Heres some output with my comments explaining when/how it comes out:

```<code>db-async-test.core-test>
;; this happens pretty quick when i run:
starting fetch...
starting csv write...

;; then it waits 30 seconds, and spits out all the output below... it's not
;; "streaming" through lazily?
Wrote  2  rows.
    Fetched  5  rows.
Wrote  4  rows.
Wrote  6  rows.
Wrote  8  rows.
...clip...
Wrote  44  rows.
Wrote  46  rows.
Wrote  48  rows.
    Fetched  50  rows.
producer closing channel... (hopefully you have written rows by now...
Wrote  50  rows.
</code>```

答:
Ok, I think I have something that works for me.

The main fix I've had was to swap out org.clojure.java/jdbc and
replaced it with funcool/clojure.jdbc in my project.clj.

What funcool/clojure.jdbc gives me is access to result-set->lazy-seq.

New ns :

```<code>(ns db-async-test.core-test
  (:require [jdbc.core :as j]
            [while-let.core :refer [while-let]]
            [clojure.java.io :as io]
            [clojure.data.csv :as csv]
            [clojure.core.async :as a :refer [>!! <!! chan thread]]
            [clojure.string :as str]))
</code>```

Below is the the relevent code.  Based on what I can tell this streams things through with async channels. I should be able to play around with async reducers/transducers using this, and hopefully over pretty large volumes (especially with map like functions) If I'm patient.

Function for reader thread:

```<code>(defn db->chan [ch {:keys [sql db-spec]} ]
  "Put db hash-maps onto ch."
  (println "starting reader thread...")
  (let [
        row-count           (atom 0)  ; For state on rows
        row-fn (fn[r] (do (>!! ch r)
                         ;; everything below is just for printing to stdout
                         (swap! row-count inc)
                         (when (zero? (mod @row-count 100))
                           (println "Fetched " @row-count " rows."))))]
    (with-open [conn (j/connection db-spec)]
      (j/atomic conn
                (with-open [cursor (j/fetch-lazy conn sql)]
                  (doseq [row (j/cursor->lazyseq cursor)]
                    (row-fn row)))))
      (a/close! ch)))
</code>```

Function for writer thread:

```<code>(defn chan->csv [ch csv-file ]
  "Read values off ch and write to csv file."
  (println "starting writer thread...")
  (def row-count (atom 0))
  (with-open [^java.io.Writer writer (io/writer csv-file
                                      :append false :encoding "UTF-8")]
    (while-let [data (<!! ch)]
      (swap! row-count inc)
      (csv/write-csv writer [data] :quote? (fn[x] false) )
      (when (zero? (mod @row-count 100))
        (println "Wrote " @row-count " rows.")))))
</code>```

I put the thread parts in below rather than in the individual functions:

```<code>(def config {:db-spec {:subprotocol "postgresql"
                       :subname "//mydbhost:5432/mydb"
                       :user "me"
                       :password "*****"}
             :sql "select row_id, giant_xml_value::text from some_table"})

(do
  (def ch (chan 1))
  (thread (db->chan ch config))
  (thread (chan->csv ch "./test.csv")))
</code>```

Output below, looks like both threads are working at the same time, streaming data out onto the channel, and popping from that channel to the csv.

Also, even with giant_xml_column my system still isn't using a huge amount of memory.

```<code>starting fetch...
starting csv write...
Fetched  100 Wrote  rows.
100
  rows.
Fetched  200Wrote    rows.200

 rows.
Fetched  300  rows.
Wrote
...clip....
6000  rows.
Fetched  6100  rows.
Wrote  6100  rows.
Fetched  6200  rows.
Wrote  6200  rows.
Fetched  6300  rows.
Wrote
 6300  rows.
Fetched  6400Wrote    rows.6400

 rows.
Fetched  6500  rows.Wrote

6500  rows.
</code>```

Body:
I'm trying to get a better understanding of core.async and channels and such.

My task at hand is to issue a jdbc select statement on a database and stream the results onto an async channel.

I want to have a mutually exclusive thread take from this channel and write to a csv file using clojure.data.csv.

When running the program below, it appears it's not happening lazily... I'm getting no output to the terminal and then everything appears at once, and my csv file has 50 rows.  I hoping someone can help me understand as to why.

Thanks in advance,

(ns db-async-test.core-test
  (:require [clojure.java.jdbc  :as j]
            [clojure.java.io    :as io]
            [clojure.data.csv   :as csv]
            [clojure.core.async :as async :refer [>! <! >!! <!!  chan thread]]
            [clojure.string     :as str]
            [while-let.core     :refer [while-let]]))

(defn db->chan [ch {:keys [sql db-spec]} ]
  "Given input channel ch, sql select, and db-spec connection info, put db
  hash-maps onto ch in a separate thread. Through back pressure I'm hoping to
  populate channel lazily as a consumer does downstream processing."
  (println "starting fetch...")
  (let [
        row-count           (atom 0)  ; For state on rows
        db-connection       (j/get-connection db-spec)
        statement (j/prepare-statement
                   db-connection
                   sql {
                        :result-type :forward-only  ;; you need this to be lazy
                        :fetch-size 3               ;; also this
                        :max-rows   0
                        :concurrency :read-only})
        row-fn (fn[d] (do
                       (>!! ch d)
                       ;; everything below is just for printing to stdout and
                       ;; trying to understand where my non-lazy bottleneck is.
                       (swap! row-count inc)
                       (when (zero? (mod @row-count 5))
                         (do
                           #_(Thread/sleep 2000 )
                           (println "\tFetched " @row-count " rows.")
                           (flush)
                           ))))]
    (thread
      (j/query db-connection [statement]
               {:as-arrays?    false
                :result-set-fn vec
                :row-fn row-fn
                })
      ;; as producer we finished popluting the chan, now close in this same
      ;; thread.
      (println "producer closing channel... (hopefully you have written rows by now...")
      (async/close! ch))))

(defn chan->csv [ch csv-file ]
  "With input channel ch and output file csv-file, read values off ch and write
  to csv file in a separate thread."
  (thread
    (println "starting csv write...")
    (def row-count (atom 0))
    (with-open [^java.io.Writer writer (io/writer csv-file :append false :encoding "UTF-8")]
      (while-let [data (<!! ch)]
        (swap! row-count inc)
        (csv/write-csv writer [data] :quote? (fn[x] false) )
        (when (zero? (mod @row-count 2))
          (do
            #_(Thread/sleep 2000 )
            (println "Wrote " @row-count " rows.")
            (.flush writer)
            (flush)))
        ))))

(def config {:db-spec {:classname "org.postgres.Driver"
                       :subprotocol "postgres"
                       :subname "//my-database-host:5432/mydb"
                       :user "me"
                       :password "****"}
             :sql "select row_id, giant_xml_column::text as xml_column from public.big_toasty_table limit 50"})

;; main sorta thing
(do
  (def ch (chan 1))
  (db->chan ch config)
  ;; could pipeline with transducers/etc at some point.
  (chan->csv ch "./test.csv"))

Heres some output with my comments explaining when/how it comes out:

db-async-test.core-test>
;; this happens pretty quick when i run:
starting fetch...
starting csv write...

;; then it waits 30 seconds, and spits out all the output below... it's not
;; "streaming" through lazily?
Wrote  2  rows.
    Fetched  5  rows.
Wrote  4  rows.
Wrote  6  rows.
Wrote  8  rows.
...clip...
Wrote  44  rows.
Wrote  46  rows.
Wrote  48  rows.
    Fetched  50  rows.
producer closing channel... (hopefully you have written rows by now...
Wrote  50  rows.

Body:
Ok, I think I have something that works for me.

The main fix I've had was to swap out org.clojure.java/jdbc and
replaced it with funcool/clojure.jdbc in my project.clj.

What funcool/clojure.jdbc gives me is access to result-set->lazy-seq.

New ns :

(ns db-async-test.core-test
  (:require [jdbc.core :as j]
            [while-let.core :refer [while-let]]
            [clojure.java.io :as io]
            [clojure.data.csv :as csv]
            [clojure.core.async :as a :refer [>!! <!! chan thread]]
            [clojure.string :as str]))

Below is the the relevent code.  Based on what I can tell this streams things through with async channels. I should be able to play around with async reducers/transducers using this, and hopefully over pretty large volumes (especially with map like functions) If I'm patient.

Function for reader thread:

(defn db->chan [ch {:keys [sql db-spec]} ]
  "Put db hash-maps onto ch."
  (println "starting reader thread...")
  (let [
        row-count           (atom 0)  ; For state on rows
        row-fn (fn[r] (do (>!! ch r)
                         ;; everything below is just for printing to stdout
                         (swap! row-count inc)
                         (when (zero? (mod @row-count 100))
                           (println "Fetched " @row-count " rows."))))]
    (with-open [conn (j/connection db-spec)]
      (j/atomic conn
                (with-open [cursor (j/fetch-lazy conn sql)]
                  (doseq [row (j/cursor->lazyseq cursor)]
                    (row-fn row)))))
      (a/close! ch)))

Function for writer thread:

(defn chan->csv [ch csv-file ]
  "Read values off ch and write to csv file."
  (println "starting writer thread...")
  (def row-count (atom 0))
  (with-open [^java.io.Writer writer (io/writer csv-file
                                      :append false :encoding "UTF-8")]
    (while-let [data (<!! ch)]
      (swap! row-count inc)
      (csv/write-csv writer [data] :quote? (fn[x] false) )
      (when (zero? (mod @row-count 100))
        (println "Wrote " @row-count " rows.")))))

I put the thread parts in below rather than in the individual functions:

(def config {:db-spec {:subprotocol "postgresql"
                       :subname "//mydbhost:5432/mydb"
                       :user "me"
                       :password "*****"}
             :sql "select row_id, giant_xml_value::text from some_table"})

(do
  (def ch (chan 1))
  (thread (db->chan ch config))
  (thread (chan->csv ch "./test.csv")))

Output below, looks like both threads are working at the same time, streaming data out onto the channel, and popping from that channel to the csv.

Also, even with giant_xml_column my system still isn't using a huge amount of memory.

starting fetch...
starting csv write...
Fetched  100 Wrote  rows.
100
  rows.
Fetched  200Wrote    rows.200

 rows.
Fetched  300  rows.
Wrote
...clip....
6000  rows.
Fetched  6100  rows.
Wrote  6100  rows.
Fetched  6200  rows.
Wrote  6200  rows.
Fetched  6300  rows.
Wrote
 6300  rows.
Fetched  6400Wrote    rows.6400

 rows.
Fetched  6500  rows.Wrote

6500  rows.


问:
C++ C2466 error
Why we can do something like

```<code>        for(int i = 0; i < destination->imageSize; i=i+3)
        {

            buffer[2] = destination->imageData[i];
            buffer[1] = destination->imageData[i+1];
            buffer[0] = destination->imageData[i+2];
            buffer+=3;
        }
</code>```

but we can not do

```<code>                               char buffer[destination->imageSize];
</code>```

And how to such thing?

Sorry - I am quite new to C++...

BTW: my point is to create a function that would return a char with an image. If I'd use mem copy how do I delete returned value?

答:
char buffer[destination->imageSize]; declares a variable at compile time. At that time, the value of destination->imageSize is not yet known, which is why it doesn't work.

The expression buffer[2] = destination->imageData[i]; (or rather the buffer[2] thereof) is evaluated at run time.

Title: C++ C2466 error

Body:
Why we can do something like

        for(int i = 0; i < destination->imageSize; i=i+3)
        {

            buffer[2] = destination->imageData[i];
            buffer[1] = destination->imageData[i+1];
            buffer[0] = destination->imageData[i+2];
            buffer+=3;
        }

but we can not do

                               char buffer[destination->imageSize];

And how to such thing?

Sorry - I am quite new to C++...

BTW: my point is to create a function that would return a char with an image. If I'd use mem copy how do I delete returned value?


问:
How to assign a value to a TensorFlow variable?
I am trying to assign a new value to a tensorflow variable in python.

```<code>import tensorflow as tf
import numpy as np

x = tf.Variable(0)
init = tf.initialize_all_variables()
sess = tf.InteractiveSession()
sess.run(init)

print(x.eval())

x.assign(1)
print(x.eval())
</code>```

But the output I get is

```<code>0
0
</code>```

So the value has not changed. What am I missing?

答:
Also, it has to be noted that if you're using your_tensor.assign(), then the tf.global_variables_initializer need not be called explicitly since the assign operation does it for you in the background.

Example:

```<code>In [212]: w = tf.Variable(12)
In [213]: w_new = w.assign(34)

In [214]: with tf.Session() as sess:
     ...:     sess.run(w_new)
     ...:     print(w_new.eval())

# output
34
</code>```

However, this will not initialize all variables, but it will only initialize the variable on which assign was executed on.

Body:
I am trying to assign a new value to a tensorflow variable in python.

import tensorflow as tf
import numpy as np

x = tf.Variable(0)
init = tf.initialize_all_variables()
sess = tf.InteractiveSession()
sess.run(init)

print(x.eval())

x.assign(1)
print(x.eval())

But the output I get is

0
0

So the value has not changed. What am I missing?

Body:
Also, it has to be noted that if you're using your_tensor.assign(), then the tf.global_variables_initializer need not be called explicitly since the assign operation does it for you in the background.

Example:

In [212]: w = tf.Variable(12)
In [213]: w_new = w.assign(34)

In [214]: with tf.Session() as sess:
     ...:     sess.run(w_new)
     ...:     print(w_new.eval())

# output
34

However, this will not initialize all variables, but it will only initialize the variable on which assign was executed on.


问:
Finding it difficult to pass data to separate viewController
I have searched through the net for couple of hours now thought this would be an easy task, but things are not going as planned. This question is edited, some of great fella has given great answer but I am still struggling.

Here is the scenario, I have a viewControllerA which is always visible. There is a small button on top of this view, when I click it there comes viewControllerB as a static tableViewController. Its a slide view from left to right to be honest like other apps.

There is one section and couple of rows in the tableView, when I tap 4th row I present viewControllerC, there is a UISwitch button there. When I dismiss the viewControllerC, viewControllerA appear again. viewControllerB is my menu controller therefore its not my greater concern .Now I want to pass data from viewControllerC to viewControllerA. Here is my broken code:

for viewControllerC :

```<code>class viewControllerC: UIViewController {
 ..//
 @IBAction func switchTapped(_ sender: UISwitch) {
     let vc = viewControllerA()
     if sender.isOn == true {
         vc.state = true
     } else if sender.isOn == false {
         vc.state = false
     }
  }
 ..//
}
</code>```

for viewControllerA :

```<code>class viewControllerA: UIViewController, GMSMapViewDelegate {
  var state:Bool?
  ...//
  if self.state == true {
      self.mapView.isTrafficEnabled = true
    } else {
      self.mapView.isTrafficEnabled = false
   }
}
</code>```

But its not working an I know I am not heading to the right direction. As you can see from the example I want to send ture when UISwitch is on and false when its off from viewControllerC to viewControllerA. Some of the folks have suggested delegate method but I am still struggling. I was following this link , I think "Passing data backwards through the shared state of the app" section meets my criteria. Although I need help. Thanks in advance.

答:
First of all when you initiate viewControllerA :

let vc = viewControllerA()

You are creating new instance of viewcontrol which doesn’t reference to your first view control.

You can pass data to viewcontrollers in different ways.
You can use delage pattern or you can use unwind.

In delegate method first you define a class type protocol with a function definition for changing something in viewControllerA.

```<code>protocol ViewControllerBDelegate: class {
    func changeSwitch(toValue: Boolean)
}
</code>```

Then in ViewControllerB you define a weak reference to delegate

```<code>weak var delegate: ViewControllerBDelegate?
</code>```

Then you adopt this protocol on ViewControlA:

```<code>extension ViewControllerA: ViewControllerBDelegate {
    func changeSwitch(toValue: Boolean) {
         state = toValue
     }
}
</code>```

When you want to present or push to ViewControllerB you should set this variable to self

```<code>let vc = ViewControllerB()
vc.delegate = self
present(vc, animated: true, completion: nil)
// or navigationController. pushViewController(vc, animated: true)
</code>```

if you are using segue to navigate from one viewcontroller to another, you should set delegate variable in prepare(for segue, sender). Override this function in ViewControllerA

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "mySegue" ,
       let vc = segue.destination as? ViewControllerB {
        vc.delegate = self
    }
}
</code>```

Then when switch value changed you can use delegate to change value in ViewControllerA

```<code>delegate?.changeSwitch(toValue: sender.isOn)
</code>```

on wind let you pop or dismiss child viewcontrollers to a certain parent and then do something. You can read a full tutorial here

EDIT

for chain delegates you can pass a delegate to ViewController B, then pass the same delegate to ViewController C.

in view controller C you define the same type delegate

```<code>weak var delegate: ViewControllerBDelegate?
</code>```

then in view controller B when you are navigating to view controller c you pass the same delegate

```<code>let vc = ViewControllerC()
vc.delegate = self.delegate
present(vc, animated: true, completion: nil)
</code>```

EDIT 2

SWRevealViewController is different scenario. revealController have an property named frontViewController. which can be your ViewControllerA if you dont push any other controllers on reveal. handling it with frontViewController is tricky you should be sure if frontController is ViewControllerA.

so i suggest you use another method to communicate with ViewControllerA. you can use NotificationCenter.

```<code>extension Notification.Name {
    static let updateMap = Notification.Name("updateMap")
}
</code>```

in ViewControllerA

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(updateMap(_:)), name: .updateMap, object: nil )
}

@objc func updateMap(notification: NSNotification) {
  if let state = notification.userInfo?["state"] as? Bool {
      // do something with state
  }
}
</code>```

and in ViewControllerC you post a notification when switch value is Changed:

```<code>weak var delegate: ViewControllerBDelegate?
</code>```0

if frontViewController in reveal is pushed again. reveal will initiate
  new ViewControllerA for frontViewController. in this scenario you have
  to set settings in UserDefault and in ViewControllerA read this
  settings.

using UserDefaults :

in ViewControllerC

```<code>weak var delegate: ViewControllerBDelegate?
</code>```1

in ViewControllerA

```<code>weak var delegate: ViewControllerBDelegate?
</code>```2

Body:
I have searched through the net for couple of hours now thought this would be an easy task, but things are not going as planned. This question is edited, some of great fella has given great answer but I am still struggling.

Here is the scenario, I have a viewControllerA which is always visible. There is a small button on top of this view, when I click it there comes viewControllerB as a static tableViewController. Its a slide view from left to right to be honest like other apps.

There is one section and couple of rows in the tableView, when I tap 4th row I present viewControllerC, there is a UISwitch button there. When I dismiss the viewControllerC, viewControllerA appear again. viewControllerB is my menu controller therefore its not my greater concern .Now I want to pass data from viewControllerC to viewControllerA. Here is my broken code:

for viewControllerC :

class viewControllerC: UIViewController {
 ..//
 @IBAction func switchTapped(_ sender: UISwitch) {
     let vc = viewControllerA()
     if sender.isOn == true {
         vc.state = true
     } else if sender.isOn == false {
         vc.state = false
     }
  }
 ..//
}

for viewControllerA :

class viewControllerA: UIViewController, GMSMapViewDelegate {
  var state:Bool?
  ...//
  if self.state == true {
      self.mapView.isTrafficEnabled = true
    } else {
      self.mapView.isTrafficEnabled = false
   }
}

But its not working an I know I am not heading to the right direction. As you can see from the example I want to send ture when UISwitch is on and false when its off from viewControllerC to viewControllerA. Some of the folks have suggested delegate method but I am still struggling. I was following this link , I think "Passing data backwards through the shared state of the app" section meets my criteria. Although I need help. Thanks in advance.

Body:
First of all when you initiate viewControllerA :

let vc = viewControllerA()

You are creating new instance of viewcontrol which doesn’t reference to your first view control.

You can pass data to viewcontrollers in different ways.
You can use delage pattern or you can use unwind.

In delegate method first you define a class type protocol with a function definition for changing something in viewControllerA.

protocol ViewControllerBDelegate: class {
    func changeSwitch(toValue: Boolean)
}

Then in ViewControllerB you define a weak reference to delegate

weak var delegate: ViewControllerBDelegate?

Then you adopt this protocol on ViewControlA:

extension ViewControllerA: ViewControllerBDelegate {
    func changeSwitch(toValue: Boolean) {
         state = toValue
     }
}

When you want to present or push to ViewControllerB you should set this variable to self

let vc = ViewControllerB()
vc.delegate = self
present(vc, animated: true, completion: nil)
// or navigationController. pushViewController(vc, animated: true)

if you are using segue to navigate from one viewcontroller to another, you should set delegate variable in prepare(for segue, sender). Override this function in ViewControllerA

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "mySegue" ,
       let vc = segue.destination as? ViewControllerB {
        vc.delegate = self
    }
}

Then when switch value changed you can use delegate to change value in ViewControllerA

delegate?.changeSwitch(toValue: sender.isOn)

on wind let you pop or dismiss child viewcontrollers to a certain parent and then do something. You can read a full tutorial here

EDIT

for chain delegates you can pass a delegate to ViewController B, then pass the same delegate to ViewController C.

in view controller C you define the same type delegate

weak var delegate: ViewControllerBDelegate?

then in view controller B when you are navigating to view controller c you pass the same delegate

let vc = ViewControllerC()
vc.delegate = self.delegate
present(vc, animated: true, completion: nil)

EDIT 2

SWRevealViewController is different scenario. revealController have an property named frontViewController. which can be your ViewControllerA if you dont push any other controllers on reveal. handling it with frontViewController is tricky you should be sure if frontController is ViewControllerA.

so i suggest you use another method to communicate with ViewControllerA. you can use NotificationCenter.

extension Notification.Name {
    static let updateMap = Notification.Name("updateMap")
}

in ViewControllerA

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(updateMap(_:)), name: .updateMap, object: nil )
}

@objc func updateMap(notification: NSNotification) {
  if let state = notification.userInfo?["state"] as? Bool {
      // do something with state
  }
}

and in ViewControllerC you post a notification when switch value is Changed:

let userInfoDic:[String: Bool] = ["state": sender.isOn]
  // post a notification
  NotificationCenter.default.post(name: .updateMap, object: nil, userInfo: userInfoDic)

if frontViewController in reveal is pushed again. reveal will initiate
  new ViewControllerA for frontViewController. in this scenario you have
  to set settings in UserDefault and in ViewControllerA read this
  settings.

using UserDefaults :

in ViewControllerC

UserDefaults.standard.setValue(sender.isOn, forKey: "mapState")

in ViewControllerA

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    let state = UserDefaults.standard.value(forKey: "mapState") ?? false
    self.mapView.isTrafficEnabled = state
}


问:
__init__() got an unexpected keyword argument 'lookup_type'
Please help me why this error coming on remote server but it was work fine on local machine, please find below error sample.

```<code>Request Method:     GET
Request URL:    https:***********.***?job_function=dir&job_type=parttime&max_experience=100&min_experience=3&name=test&owner_id=571&page_size=10
Django Version:     1.8.14
Exception Type:     TypeError
Exception Value:

__init__() got an unexpected keyword argument 'lookup_type'

Exception Location:     env/local/lib/python3.4/dist-packages/django/forms/fields.py in __init__, line 245
Python Executable:  env/bin/python3.4
Python Version:     3.4.3
Python Path:

 '/home/deployment/backend',
 '/home/deployment/backend/env/bin',
 '/home/deployment/backend',
 '',
 '/home/deployment/backend/env/local/lib64/python3.4/site-packages',
 '/home/deployment/backend/env/local/lib/python3.4/site-packages',
 '/home/deployment/backend/env/lib64/python3.4',
 '/home/deployment/backend/env/lib/python3.4',
 '/home/deployment/backend/env/lib64/python3.4/site-packages',
 '/home/deployment/backend/env/lib/python3.4/site-packages',
 '/home/deployment/backend/env/lib64/python3.4/plat-linux',
 '/home/deployment/backend/env/lib64/python3.4/lib-dynload',
 '/home/deployment/backend/env/local/lib/python3.4/dist-packages',
 '/usr/lib64/python3.4',
 '/usr/lib/python3.4'
</code>```

Code:

Please find the given code here, it's work on local machine fine but remote server through error, here two function defined in Jobviewsets class

def get_annotate_queryset(self, queryset):

```<code>#queryset = queryset.filter(Q(job_for='all') | Q(job_for=''))
queryset = queryset.annotate(
    all_applicant_count=Count('applicants', distinct=True),
    job_view_count=Count('job_views', distinct=True),
).extra(select={
    'voteup_count': get_voteup_count_query(queryset.model),
    'has_applied':
        """
        SELECT Sum(CASE WHEN {job_applicant}.user_id = {user_id} THEN 1 ELSE 0 END)
        FROM {job_applicant}
        WHERE job_id={job}.id
        """.format(user_id=self.request.user.id,
            job=Job._meta.db_table,
            job_applicant=Applicant._meta.db_table),
    'is_favourite':
        """
        SELECT Sum(CASE WHEN {favourite_job}.user_id = {user_id} THEN 1 ELSE 0 END)
        FROM {favourite_job}
        WHERE job_id={job}.id
        """.format(user_id=self.request.user.id,
            job=Job._meta.db_table,
            favourite_job=FavouriteJob._meta.db_table)
})
return queryset
</code>```

def get_queryset(self):

```<code>queryset = super().get_queryset()
queryset = self.get_annotate_queryset(queryset)
if self.action == 'discover':

    searchtype=self.request.GET.get('search_type')
    searchKeyword=self.request.GET.get('name')
    searchLocation=self.request.GET.get('location')

    job_status=self.request.GET.get('job_status')
    if(job_status =='' or job_status== None):
        job_status = 'active'

    job_type=self.request.GET.get('job_type')
    if (job_type =='' or job_type == None):
        job_type = 'fulltime'

    min_experience=self.request.GET.get('min_experience')
    if (min_experience =='' or min_experience == None):
        min_experience = 0

    max_experience=self.request.GET.get('max_experience')
    if (max_experience =='' or max_experience == None):
        max_experience = 100

    min_salary_compensation=self.request.GET.get('min_salary_compensation')
    if (min_salary_compensation == None):
        min_salary_compensation = 0

    max_salary_compensation=self.request.GET.get('max_salary_compensation')
    if (max_salary_compensation =='' or max_salary_compensation == None):
        max_salary_compensation = 500000

    salary_reccurence=self.request.GET.get('salary_reccurence')
    if (salary_reccurence =='' or salary_reccurence == None):
        salary_reccurence = 'hourly'

    if (searchtype == 'refine_search'):

        if (searchKeyword == '' or searchKeyword == None):
            searchKeyword = ''

        if (searchLocation == '' or searchLocation == None):
            searchLocation = ''

        min_experience = int(min_experience)
        max_experience = int(max_experience)
        min_salary_compensation = int(min_salary_compensation)
        max_salary_compensation = int(max_salary_compensation)

        queryset = queryset.filter(Q(job_title__icontains=searchKeyword) |
                                   Q(company_name__icontains=searchKeyword) |
                                   Q(location_id=searchLocation) |
                                   Q(status=job_status) |
                                   Q(employment_type__icontains=job_type) |
                                   Q(min_experience__gte=min_experience) &
                                   Q(max_experience__lte=max_experience) |

                                   Q(compensation__gte=min_salary_compensation) &
                                   Q(compensation__lte=max_salary_compensation) |
                                   Q(salary_reccurence__icontains=salary_reccurence)

                                   ).exclude(owner=self.request.user)

    if (searchtype != 'refine_search'):

        if (searchKeyword != None and searchLocation != None):

            queryset = queryset.filter(Q(job_title__icontains=searchKeyword) |
                                       Q(company_name__icontains=searchKeyword) |
                                       Q(location_id=searchLocation)).exclude(owner=self.request.user)

        elif (searchKeyword != None and searchLocation == None):
            queryset = queryset.filter(Q(job_title__icontains=searchKeyword) |
                                       Q(company_name__icontains=searchKeyword)).exclude(
                owner=self.request.user)

        elif (searchKeyword == None and searchLocation != None):
            queryset = queryset.filter(Q(location_id=searchLocation)).exclude(owner=self.request.user)

        else:
            queryset = queryset.exclude(owner=self.request.user)

return queryset
</code>```

答:
We will need to see the constructor method of the class that is being instantiated to figure out exactly what is going wrong.

However just from the error message it seems that there is an additional argument being passed to the constructor that is not recognized. Have a look at the formal parameters defined in the classes' constructor and compare that to the arguments being passed in.

Body:
Please help me why this error coming on remote server but it was work fine on local machine, please find below error sample.

Request Method:     GET
Request URL:    https:***********.***?job_function=dir&job_type=parttime&max_experience=100&min_experience=3&name=test&owner_id=571&page_size=10
Django Version:     1.8.14
Exception Type:     TypeError
Exception Value:

__init__() got an unexpected keyword argument 'lookup_type'

Exception Location:     env/local/lib/python3.4/dist-packages/django/forms/fields.py in __init__, line 245
Python Executable:  env/bin/python3.4
Python Version:     3.4.3
Python Path:

 '/home/deployment/backend',
 '/home/deployment/backend/env/bin',
 '/home/deployment/backend',
 '',
 '/home/deployment/backend/env/local/lib64/python3.4/site-packages',
 '/home/deployment/backend/env/local/lib/python3.4/site-packages',
 '/home/deployment/backend/env/lib64/python3.4',
 '/home/deployment/backend/env/lib/python3.4',
 '/home/deployment/backend/env/lib64/python3.4/site-packages',
 '/home/deployment/backend/env/lib/python3.4/site-packages',
 '/home/deployment/backend/env/lib64/python3.4/plat-linux',
 '/home/deployment/backend/env/lib64/python3.4/lib-dynload',
 '/home/deployment/backend/env/local/lib/python3.4/dist-packages',
 '/usr/lib64/python3.4',
 '/usr/lib/python3.4'

Code:

Please find the given code here, it's work on local machine fine but remote server through error, here two function defined in Jobviewsets class

def get_annotate_queryset(self, queryset):

#queryset = queryset.filter(Q(job_for='all') | Q(job_for=''))
queryset = queryset.annotate(
    all_applicant_count=Count('applicants', distinct=True),
    job_view_count=Count('job_views', distinct=True),
).extra(select={
    'voteup_count': get_voteup_count_query(queryset.model),
    'has_applied':
        """
        SELECT Sum(CASE WHEN {job_applicant}.user_id = {user_id} THEN 1 ELSE 0 END)
        FROM {job_applicant}
        WHERE job_id={job}.id
        """.format(user_id=self.request.user.id,
            job=Job._meta.db_table,
            job_applicant=Applicant._meta.db_table),
    'is_favourite':
        """
        SELECT Sum(CASE WHEN {favourite_job}.user_id = {user_id} THEN 1 ELSE 0 END)
        FROM {favourite_job}
        WHERE job_id={job}.id
        """.format(user_id=self.request.user.id,
            job=Job._meta.db_table,
            favourite_job=FavouriteJob._meta.db_table)
})
return queryset

def get_queryset(self):

queryset = super().get_queryset()
queryset = self.get_annotate_queryset(queryset)
if self.action == 'discover':

    searchtype=self.request.GET.get('search_type')
    searchKeyword=self.request.GET.get('name')
    searchLocation=self.request.GET.get('location')

    job_status=self.request.GET.get('job_status')
    if(job_status =='' or job_status== None):
        job_status = 'active'

    job_type=self.request.GET.get('job_type')
    if (job_type =='' or job_type == None):
        job_type = 'fulltime'

    min_experience=self.request.GET.get('min_experience')
    if (min_experience =='' or min_experience == None):
        min_experience = 0

    max_experience=self.request.GET.get('max_experience')
    if (max_experience =='' or max_experience == None):
        max_experience = 100

    min_salary_compensation=self.request.GET.get('min_salary_compensation')
    if (min_salary_compensation == None):
        min_salary_compensation = 0

    max_salary_compensation=self.request.GET.get('max_salary_compensation')
    if (max_salary_compensation =='' or max_salary_compensation == None):
        max_salary_compensation = 500000

    salary_reccurence=self.request.GET.get('salary_reccurence')
    if (salary_reccurence =='' or salary_reccurence == None):
        salary_reccurence = 'hourly'

    if (searchtype == 'refine_search'):

        if (searchKeyword == '' or searchKeyword == None):
            searchKeyword = ''

        if (searchLocation == '' or searchLocation == None):
            searchLocation = ''

        min_experience = int(min_experience)
        max_experience = int(max_experience)
        min_salary_compensation = int(min_salary_compensation)
        max_salary_compensation = int(max_salary_compensation)

        queryset = queryset.filter(Q(job_title__icontains=searchKeyword) |
                                   Q(company_name__icontains=searchKeyword) |
                                   Q(location_id=searchLocation) |
                                   Q(status=job_status) |
                                   Q(employment_type__icontains=job_type) |
                                   Q(min_experience__gte=min_experience) &
                                   Q(max_experience__lte=max_experience) |

                                   Q(compensation__gte=min_salary_compensation) &
                                   Q(compensation__lte=max_salary_compensation) |
                                   Q(salary_reccurence__icontains=salary_reccurence)

                                   ).exclude(owner=self.request.user)

    if (searchtype != 'refine_search'):

        if (searchKeyword != None and searchLocation != None):

            queryset = queryset.filter(Q(job_title__icontains=searchKeyword) |
                                       Q(company_name__icontains=searchKeyword) |
                                       Q(location_id=searchLocation)).exclude(owner=self.request.user)

        elif (searchKeyword != None and searchLocation == None):
            queryset = queryset.filter(Q(job_title__icontains=searchKeyword) |
                                       Q(company_name__icontains=searchKeyword)).exclude(
                owner=self.request.user)

        elif (searchKeyword == None and searchLocation != None):
            queryset = queryset.filter(Q(location_id=searchLocation)).exclude(owner=self.request.user)

        else:
            queryset = queryset.exclude(owner=self.request.user)

return queryset


问:
Back to top link flashes twice before dissappearing
As per the fiddle below I have a scroll back to top link, but upon clicking the link to scroll back to the top it flashes twice.

I have tried the usual suspects such as the $(body,html), but it still occurs even when I use one of those.

stop() before the fadeIn and fadeOut does help prevent this but causes the fadeIn to be incredibly slow.

Therefore, I was wondering if anyone could explain why this flash of the element is happening and how I could stop it from occurring?

jQuery(function() {
  jQuery(window).scroll(function() {
    if (jQuery(this).scrollTop() > 50) {
      jQuery('#back_top').fadeIn();
    } else {
      jQuery('#back_top').fadeOut();
    }
  });
  jQuery('#back_top').click(function() {
    jQuery('body,html').animate({
      scrollTop: 0
    }, 500);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#back_top {
  background-color: #447282;
  /* button color */
  color: white;
  /* text/arrow color */
  display: none;
  z-index: 999;
  /* float in bottom right corner */
  /* 20 pixels from edge */
  position: fixed;
  right: 10px;
  bottom: 10px;
  /* size of button is 50 pixels*/
  width: 54px;
  height: 54px;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  opacity: 0.9;
}

a#back_top {
  font-weight: 600;
  letter-spacing: 2px;
  font-size: 12px;
  text-transform: uppercase;
  text-align: center;
  line-height: 1.6;
  padding-left: 2px;
  padding-top: 8px;
}

a#back_top .arrow:before {
  content: "\e902";
  font-family: 'vishIcon';
  font-style: normal;
  font-weight: 600;
  font-size: 18px;
  line-height: 1;
  speak: none;
  -webkit-font-smoothing: antialiased;
  content: "\e902";
  text-align: center;
  display: block;
  vertical-align: middle;
  cursor: pointer;
  /*     margin-left: -4px; */
}</code>```

What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type
specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently
with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using
Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default
model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like). Where does it come from? Contrary
to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the
more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum"
(The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32. The
standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions
from the 1914 translation by H. Rackham. Where can I get some? There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly
believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this
the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition,
injected humour, or non-characteristic words etc.
Top```

答: Because you're triggering the function on (window).scroll() the function is being called multiple times. You'll have to find another way to call the scroll to top function without trigdering itself.</p>

Body:
As per the fiddle below I have a scroll back to top link, but upon clicking the link to scroll back to the top it flashes twice.

I have tried the usual suspects such as the $(body,html), but it still occurs even when I use one of those.

stop() before the fadeIn and fadeOut does help prevent this but causes the fadeIn to be incredibly slow.

Therefore, I was wondering if anyone could explain why this flash of the element is happening and how I could stop it from occurring?

jQuery(function() {
  jQuery(window).scroll(function() {
    if (jQuery(this).scrollTop() > 50) {
      jQuery('#back_top').fadeIn();
    } else {
      jQuery('#back_top').fadeOut();
    }
  });
  jQuery('#back_top').click(function() {
    jQuery('body,html').animate({
      scrollTop: 0
    }, 500);
  });
});

#back_top {
  background-color: #447282;
  /* button color */
  color: white;
  /* text/arrow color */
  display: none;
  z-index: 999;
  /* float in bottom right corner */
  /* 20 pixels from edge */
  position: fixed;
  right: 10px;
  bottom: 10px;
  /* size of button is 50 pixels*/
  width: 54px;
  height: 54px;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  opacity: 0.9;
}

a#back_top {
  font-weight: 600;
  letter-spacing: 2px;
  font-size: 12px;
  text-transform: uppercase;
  text-align: center;
  line-height: 1.6;
  padding-left: 2px;
  padding-top: 8px;
}

a#back_top .arrow:before {
  content: "\e902";
  font-family: 'vishIcon';
  font-style: normal;
  font-weight: 600;
  font-size: 18px;
  line-height: 1;
  speak: none;
  -webkit-font-smoothing: antialiased;
  content: "\e902";
  text-align: center;
  display: block;
  vertical-align: middle;
  cursor: pointer;
  /*     margin-left: -4px; */
}

What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type
specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently
with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using
Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default
model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like). Where does it come from? Contrary
to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the
more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum"
(The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32. The
standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions
from the 1914 translation by H. Rackham. Where can I get some? There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly
believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this
the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition,
injected humour, or non-characteristic words etc.
Top


问:
Acessing a variable being updated
I have a function that watches a csv file. It iterates through all the lines in a csv file and returns each line, waits for the file to be updated, and if it is, returns that new value. This is how it looks like:

```<code>def follow():
    file_path = filedialog.askopenfilename()
    with open(file_path) as csvDataFile:
        csvReader = csv.reader(csvDataFile)
        csvDataFile.seek(0,0)
        while True:
            line = csvDataFile.readline()
            if not line:
                time.sleep(0.5)
                continue
            yield line
</code>```

I am doing this for a gui. I have a button that, when pressed, loads the csv file and calls this function. It saves each line to a list that is a member variable.

```<code>def browseForFile(self):
        line = pull_csv_data.follow()
        for item in line:
            self.list.append(item)
</code>```

When another button is pressed, it iterates through that list and displays the information on the gui:

```<code>def listItems(self):
    for i in self.list:
        time.sleep(0.1)
        item = QListWidgetItem(i)
        self.prev_scenes.addItem(item)
</code>```

The problem is, whenever I click the button to display the data in the list, it stops responding until I kill the python script that has the follow() function. For clarification, the follow function is in a separate file that I include in my "main" file.

Essentially.. the follow function does not allow for other processes to run at the same time, I think. Is that true? is there a workaround? Or is there a better way to do this?

答:
The follow function is in the same process as your main function. Because of this, when your follow function sleeps, so does your entire program. If you want this to be run asynchronously, you'll have to make it do so explicitly.

You should probably use something like https://pythonhosted.org/watchdog/index.html or https://github.com/seb-m/pyinotify/wiki instead of trying to write your own file handling function.

Title: Acessing a variable being updated

Body:
I have a function that watches a csv file. It iterates through all the lines in a csv file and returns each line, waits for the file to be updated, and if it is, returns that new value. This is how it looks like:

def follow():
    file_path = filedialog.askopenfilename()
    with open(file_path) as csvDataFile:
        csvReader = csv.reader(csvDataFile)
        csvDataFile.seek(0,0)
        while True:
            line = csvDataFile.readline()
            if not line:
                time.sleep(0.5)
                continue
            yield line

I am doing this for a gui. I have a button that, when pressed, loads the csv file and calls this function. It saves each line to a list that is a member variable.

def browseForFile(self):
        line = pull_csv_data.follow()
        for item in line:
            self.list.append(item)

When another button is pressed, it iterates through that list and displays the information on the gui:

def listItems(self):
    for i in self.list:
        time.sleep(0.1)
        item = QListWidgetItem(i)
        self.prev_scenes.addItem(item)

The problem is, whenever I click the button to display the data in the list, it stops responding until I kill the python script that has the follow() function. For clarification, the follow function is in a separate file that I include in my "main" file.

Essentially.. the follow function does not allow for other processes to run at the same time, I think. Is that true? is there a workaround? Or is there a better way to do this?


问:
git log with square bracket in name
I'm trying to get the log for a file with square brackets in its name. In case it matters: the OS is Windows and i'm using git bash.

If you create a file with [] in its name like [Start_here].bat then git log will not work.

I tried:

```<code>git log '[Start_here].bat'

git log \[Start_here\].bat

git log '\[Start_here\].bat'

git log -- '[Start_here].bat'

git log -- \[Start_here\].bat

git log -- '\[Start_here\].bat'
</code>```

And none of them seemed to work. Either it did not display any commits or displayed a list of unrelated commits.

Does anybody have a solution that works?

Note:

```<code>git mv '[Start_here].bat' 'start_here.bat'

git log --follow start_here.bat
</code>```

does show me a history in which the file was changed.

Edit:

Using the following script executed in a new repo I can see git log behaving correctly untill you add a submodule. Then it starts listing all the commits that changed a submodule too...

```<code>#!/usr/bin/env bash

set -x

rm -rf test-repo
rm -rf test-submodule

mkdir test-submodule

pushd test-submodule

git init
git config --local user.name tester1
git config --local user.email test@here.com

echo "a single line" > file.txt
git add file.txt
git commit -m "first commit"

popd

mkdir test-repo
pushd test-repo

git init
git config --local user.name tester1
git config --local user.email test@here.com

git branch -m master

echo "first line" > somefile.txt
git add somefile.txt
git commit -m "First line"

echo "another line" >> somefile.txt
git add somefile.txt
git commit -a -m "Second line"

echo "A line" > "[__Odd__].txt"
git add "[__Odd__].txt"
git commit -m "Adding odd file"

echo "third line" >> somefile.txt
git commit -a -m "Another bold statement."

echo "2nd line" >> "[__Odd__].txt"
echo "more" >> somefile.txt
git add "[__Odd__].txt" somefile.txt
git commit -m "changed both in master1"

git checkout -b new_branch

echo "2nd line" >> "[__Odd__].txt"
echo "more" >> somefile.txt
git add "[__Odd__].txt" somefile.txt
git commit -m "changed both in new_branch"

git checkout master

echo "2nd line" >> "[__Odd__].txt"
echo "more" >> somefile.txt
git add "[__Odd__].txt" somefile.txt
git commit -m "changed both in master"

git submodule add -- ../test-submodule module
git commit -m "Added submodule"

git log -- "[__Odd__].txt"
</code>```

This outputs:

```<code>commit c3ebc7e0daf68543d761fc3b06c7ab35e014efaf (HEAD -> master)
Author: tester1 <test@here.com>
Date:   Fri Nov 17 13:06:07 2017 +0100

    Added submodule

commit 03a935df578a2eaf3f42789bd1e89e313224797a
Author: tester1 <test@here.com>
Date:   Fri Nov 17 13:06:06 2017 +0100

    changed both in master

commit d617db69dd9468e88587e2363050fdf57ac10756
Author: tester1 <test@here.com>
Date:   Fri Nov 17 13:06:06 2017 +0100

    changed both in master1

commit 88a07e5c887d63ead4e6cedd6349dfaf85ec1866
Author: tester1 <test@here.com>
Date:   Fri Nov 17 13:06:05 2017 +0100

    Adding odd file
</code>```

Notice the top entry, it should not be here. It is related only to the submodule not to the file i want the log for.

git log -- somefile.txt does not output changes related to the submodules

答:
I just tested, with Git 2.15 for Windows, the double-quotes.

It works with git bash:

```<code>vonc@VONCAVN7:/mnt/d/git/talks$ git log -- "[r].txt"
commit 7a698bf83cb55fa479200a3585b03ece1ee5db0a (HEAD -> 201710_docker)
Author: VonC <vonc@laposte.net>
Date:   Mon Nov 13 20:33:04 2017 +0100

    test
</code>```

Or directly from a CMD shell session:

```<code>vonc@VONCAVN7 D:\git\talks
> git log -- "[r].txt"
commit 7a698bf83cb55fa479200a3585b03ece1ee5db0a (HEAD -> 201710_docker)
Author: VonC <vonc@laposte.net>
Date:   Mon Nov 13 20:33:04 2017 +0100

    test
</code>```

To be sure you don't have any other program interfering with Git, try the same Git log after having set a simplified PATH.

Title: git log with square bracket in name

Body:
I'm trying to get the log for a file with square brackets in its name. In case it matters: the OS is Windows and i'm using git bash.

If you create a file with [] in its name like [Start_here].bat then git log will not work.

I tried:

git log '[Start_here].bat'

git log \[Start_here\].bat

git log '\[Start_here\].bat'

git log -- '[Start_here].bat'

git log -- \[Start_here\].bat

git log -- '\[Start_here\].bat'

And none of them seemed to work. Either it did not display any commits or displayed a list of unrelated commits.

Does anybody have a solution that works?

Note:

git mv '[Start_here].bat' 'start_here.bat'

git log --follow start_here.bat

does show me a history in which the file was changed.

Edit:

Using the following script executed in a new repo I can see git log behaving correctly untill you add a submodule. Then it starts listing all the commits that changed a submodule too...

#!/usr/bin/env bash

set -x

rm -rf test-repo
rm -rf test-submodule

mkdir test-submodule

pushd test-submodule

git init
git config --local user.name tester1
git config --local user.email test@here.com

echo "a single line" > file.txt
git add file.txt
git commit -m "first commit"

popd

mkdir test-repo
pushd test-repo

git init
git config --local user.name tester1
git config --local user.email test@here.com

git branch -m master

echo "first line" > somefile.txt
git add somefile.txt
git commit -m "First line"

echo "another line" >> somefile.txt
git add somefile.txt
git commit -a -m "Second line"

echo "A line" > "[__Odd__].txt"
git add "[__Odd__].txt"
git commit -m "Adding odd file"

echo "third line" >> somefile.txt
git commit -a -m "Another bold statement."

echo "2nd line" >> "[__Odd__].txt"
echo "more" >> somefile.txt
git add "[__Odd__].txt" somefile.txt
git commit -m "changed both in master1"

git checkout -b new_branch

echo "2nd line" >> "[__Odd__].txt"
echo "more" >> somefile.txt
git add "[__Odd__].txt" somefile.txt
git commit -m "changed both in new_branch"

git checkout master

echo "2nd line" >> "[__Odd__].txt"
echo "more" >> somefile.txt
git add "[__Odd__].txt" somefile.txt
git commit -m "changed both in master"

git submodule add -- ../test-submodule module
git commit -m "Added submodule"

git log -- "[__Odd__].txt"

This outputs:

commit c3ebc7e0daf68543d761fc3b06c7ab35e014efaf (HEAD -> master)
Author: tester1 <test@here.com>
Date:   Fri Nov 17 13:06:07 2017 +0100

    Added submodule

commit 03a935df578a2eaf3f42789bd1e89e313224797a
Author: tester1 <test@here.com>
Date:   Fri Nov 17 13:06:06 2017 +0100

    changed both in master

commit d617db69dd9468e88587e2363050fdf57ac10756
Author: tester1 <test@here.com>
Date:   Fri Nov 17 13:06:06 2017 +0100

    changed both in master1

commit 88a07e5c887d63ead4e6cedd6349dfaf85ec1866
Author: tester1 <test@here.com>
Date:   Fri Nov 17 13:06:05 2017 +0100

    Adding odd file

Notice the top entry, it should not be here. It is related only to the submodule not to the file i want the log for.

git log -- somefile.txt does not output changes related to the submodules

Body:
I just tested, with Git 2.15 for Windows, the double-quotes.

It works with git bash:

vonc@VONCAVN7:/mnt/d/git/talks$ git log -- "[r].txt"
commit 7a698bf83cb55fa479200a3585b03ece1ee5db0a (HEAD -> 201710_docker)
Author: VonC <vonc@laposte.net>
Date:   Mon Nov 13 20:33:04 2017 +0100

    test

Or directly from a CMD shell session:

vonc@VONCAVN7 D:\git\talks
> git log -- "[r].txt"
commit 7a698bf83cb55fa479200a3585b03ece1ee5db0a (HEAD -> 201710_docker)
Author: VonC <vonc@laposte.net>
Date:   Mon Nov 13 20:33:04 2017 +0100

    test

To be sure you don't have any other program interfering with Git, try the same Git log after having set a simplified PATH.


问:
No .bash_profile on my Mac
I'm trying to develop using Eclipse/Maven on my Mac and while setting environment variables there is no .bash_profile. I do ls -a and still not there. I see a .bash_history and .bash_sessions. Where am I supposed to set my JAVA_HOME and PATH?

Thank you!

答:
In your terminal:

```<code>touch ~/.bash_profile; open ~/.bash_profile
</code>```

Then make your edits and save. This is generic so make sure your path is correct in the above example.

Title: No .bash_profile on my Mac

Body:
In your terminal:

touch ~/.bash_profile; open ~/.bash_profile

Then make your edits and save. This is generic so make sure your path is correct in the above example.


问:
Programmatically generate script for all objects in a database
For an automated setup build that generates the setup for an application which uses Microsoft SQL Server, I am currently evaluating whether the following is possible:

I want to programmatically (CMD script or C# code) execute the function "Generate Scripts" on a database that is accessible from Microsoft SQL Server Management Studio 2008.

I.e. call some code and have all the objects (tables, SPs, constraints, etc.) of a specified database as an SQL script.

Currently, I only need the structure, not the data.

Question: Is it possible to achieve this goal?

答: Microsoft has also released a tool called 'mssql-scripter'.  It can be found here: mssql-scripter</p>


问:
How to set an Image Relative to another Image View
I want to set an image on another image .
The base image is of 3600px X 2400px (WxH)
The image I want to insert has these conditions:-
X: 471px
Y: 282px
W: 1053px
H: 936px
 X & Y are relative to the base image.
All coordinates are in px.</p>

答:
Using a RelativeLayout below one another and some margins (maybe padding will fit) I ommited the android: in all parameters.

```<code><RelativeLayout layout_width="wrap_content" layout_height="wrap_content">
   <ImageView
      id="@+id/firstOne"
      layout_width="360px" layout_height="240px" />
   <ImageView
      belowOf="@+id/firstOne"
      marginTop="28px"
      marginLeft="47px"
      layout_width="105px" layout_height="93px" />
 </RelativeLayout>
</code>```

I downsized all values by 10 so you can see the result, but you will need to find a relative solution with wrap_contents + adjustViewBounds and scaleMatrix = fitXY

Body:
Using a RelativeLayout below one another and some margins (maybe padding will fit) I ommited the android: in all parameters.

<RelativeLayout layout_width="wrap_content" layout_height="wrap_content">
   <ImageView
      id="@+id/firstOne"
      layout_width="360px" layout_height="240px" />
   <ImageView
      belowOf="@+id/firstOne"
      marginTop="28px"
      marginLeft="47px"
      layout_width="105px" layout_height="93px" />
 </RelativeLayout>

I downsized all values by 10 so you can see the result, but you will need to find a relative solution with wrap_contents + adjustViewBounds and scaleMatrix = fitXY


问:
Multiple enum implementing protocols questions
I defined enums as confirming to a protocol Eventable:

```<code>protocol Eventable {
    var name: String { get }
    static var all: [Eventable] { get }
}

enum MyEnum: String, Eventable {
    case bla = "bla"
    case blu = "blu"

    var name: String {
        return self.rawValue
    }

    static var all: [Eventable] {
        return [
            MyEnum.bla,
            MyEnum.blu
        ]
    }
}
</code>```

I have other enums like MyEnum also under the form:
    enum Bla: String, Eventable {
    }

I have two questions:

for the enums having a String data type, I would like to avoid duplicating the generation of the variable name:
var name: String
I am not sure how to write that in Swift. I tried to play around with the "where" clause but not success. How can I achieve that?

when I write my enums and conform to the protocol for that part:
static var all: [Eventable] { get }.
I would like that for the enum MyEnum, it constrains the variable to:
static var all: [MyEnum] { ... }
because for now I can put in the returned array any element being an Eventable and it's not what I need.
Amongst other things, I tried to define a generic constraint in the protocol for it, but I get the following error:

Protocol 'Eventable' can only be used as a generic constraint because
  it has Self or associated type requirements

Thank you very much for the help!

答:
For the part of the question we need to extend Eventable protocol where Self inherits RawRepresentable

```<code>protocol Eventable {
    var name: String { get }
    static var all: [Self] { get }
}

extension Eventable where Self: RawRepresentable {
    var name: Self.RawValue {
        return self.rawValue
    }
}

enum MyEnum: String, Eventable {
    case bla = "bla"
    case blu = "blu"

    static var all: [MyEnum] = [bla, blu]
}
</code>```

For the second part of your question we need to configure the function to handle a generic type

I would suggest making the function generic as well here is an example

```<code>func printEnum<T: Eventable>(_ event: T) {
    print(event.name)
}
</code>```

and we can use it for any object confirms to Eventable

```<code>printEnum(MyEnum.bla)
</code>```

Body:
I defined enums as confirming to a protocol Eventable:

protocol Eventable {
    var name: String { get }
    static var all: [Eventable] { get }
}

enum MyEnum: String, Eventable {
    case bla = "bla"
    case blu = "blu"

    var name: String {
        return self.rawValue
    }

    static var all: [Eventable] {
        return [
            MyEnum.bla,
            MyEnum.blu
        ]
    }
}

I have other enums like MyEnum also under the form:
    enum Bla: String, Eventable {
    }

I have two questions:

for the enums having a String data type, I would like to avoid duplicating the generation of the variable name:
var name: String
I am not sure how to write that in Swift. I tried to play around with the "where" clause but not success. How can I achieve that?

when I write my enums and conform to the protocol for that part:
static var all: [Eventable] { get }.
I would like that for the enum MyEnum, it constrains the variable to:
static var all: [MyEnum] { ... }
because for now I can put in the returned array any element being an Eventable and it's not what I need.
Amongst other things, I tried to define a generic constraint in the protocol for it, but I get the following error:

Protocol 'Eventable' can only be used as a generic constraint because
  it has Self or associated type requirements

Thank you very much for the help!

Body:
For the part of the question we need to extend Eventable protocol where Self inherits RawRepresentable

protocol Eventable {
    var name: String { get }
    static var all: [Self] { get }
}

extension Eventable where Self: RawRepresentable {
    var name: Self.RawValue {
        return self.rawValue
    }
}

enum MyEnum: String, Eventable {
    case bla = "bla"
    case blu = "blu"

    static var all: [MyEnum] = [bla, blu]
}

For the second part of your question we need to configure the function to handle a generic type

I would suggest making the function generic as well here is an example

func printEnum<T: Eventable>(_ event: T) {
    print(event.name)
}

and we can use it for any object confirms to Eventable

printEnum(MyEnum.bla)