问:
parse a list of objects in django
There is a list of objects which is printed like this:

```<code>[<Intermediate_table: Intermediate_table object>, <Intermediate_table: Intermediate_table object>, <Intermediate_table: Intermediate_table object>, <Intermediate_table: Intermediate_table object>]
</code>```

I want to extract the email attribute of an individual object for which I used json.loads(queryset),it shows an error:Expecting value: line 1 column 1 (char 0)

```<code>#I also tried without json.loads:
for i in queryset:#the list is in queryset variable
 print(i.subject)#this gives an error
</code>```

The function(it is in the admins.py file,it gets called for a particular action at the admin page for this model):

```<code>def authenticate_(modeladmin, request, queryset):
    #q = queryset.email;
    #req = json.loads(str(queryset )
    #q = req['email']
    for i in queryset:
        print(json.loads(str(i)))
    print('asdasdadasd-->'+str(queryset))
</code>```

Error trace:

```<code>Traceback:
File "/home/saurabh/Music/Project_ques10/test/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
  112.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/saurabh/Music/Project_ques10/test/lib/python3.4/site-packages/django/contrib/admin/options.py" in wrapper
  465.                 return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/saurabh/Music/Project_ques10/test/lib/python3.4/site-packages/django/utils/decorators.py" in _wrapped_view
  99.                     response = view_func(request, *args, **kwargs)
File "/home/saurabh/Music/Project_ques10/test/lib/python3.4/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  52.         response = view_func(request, *args, **kwargs)
File "/home/saurabh/Music/Project_ques10/test/lib/python3.4/site-packages/django/contrib/admin/sites.py" in inner
  198.             return view(request, *args, **kwargs)
File "/home/saurabh/Music/Project_ques10/test/lib/python3.4/site-packages/django/utils/decorators.py" in _wrapper
  29.             return bound_func(*args, **kwargs)
File "/home/saurabh/Music/Project_ques10/test/lib/python3.4/site-packages/django/utils/decorators.py" in _wrapped_view
  99.                     response = view_func(request, *args, **kwargs)
File "/home/saurabh/Music/Project_ques10/test/lib/python3.4/site-packages/django/utils/decorators.py" in bound_func
  25.                 return func(self, *args2, **kwargs2)
File "/home/saurabh/Music/Project_ques10/test/lib/python3.4/site-packages/django/contrib/admin/options.py" in changelist_view
  1364.                 response = self.response_action(request, queryset=cl.get_queryset(request))
File "/home/saurabh/Music/Project_ques10/test/lib/python3.4/site-packages/django/contrib/admin/options.py" in response_action
  1117.             response = func(self, request, queryset)
File "/home/saurabh/Music/Project_ques10/ques10-funda/biostar/apps/quespaper/admin.py" in authenticate_
  83.         print(json.loads(str(i)))
File "/usr/lib/python3.4/json/__init__.py" in loads
  318.         return _default_decoder.decode(s)
File "/usr/lib/python3.4/json/decoder.py" in decode
  343.         obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.4/json/decoder.py" in raw_decode
  361.             raise ValueError(errmsg("Expecting value", s, err.value)) from None

Exception Type: ValueError at /admin/quespaper/intermediate_table/
Exception Value: Expecting value: line 1 column 1 (char 0)
</code>```

Please suggest the correct way of parsing each object.

Thanks.

答:
Problem is that the object that you are trying to decode is not json encodable at the first place. Types acceptable to JSON are string, number, boolean, array and dict. So if you convert this object to string and try to decode it, then python won't be able to decode it to the right object and so it raises an error.

If you really want to use JSON format, you can use it on the string representations only after encoding it first like this:

```<code>for i in queryset:
    print(json.loads(json.dumps(str(i))))
</code>```

You may also need to define__str__() method for your model.

Your code without json.loads() is failing because your Intermediate_table object has no attribute email.

Title: parse a list of objects in django

Body:
There is a list of objects which is printed like this:

[<Intermediate_table: Intermediate_table object>, <Intermediate_table: Intermediate_table object>, <Intermediate_table: Intermediate_table object>, <Intermediate_table: Intermediate_table object>]

I want to extract the email attribute of an individual object for which I used json.loads(queryset),it shows an error:Expecting value: line 1 column 1 (char 0)

#I also tried without json.loads:
for i in queryset:#the list is in queryset variable
 print(i.subject)#this gives an error

The function(it is in the admins.py file,it gets called for a particular action at the admin page for this model):

def authenticate_(modeladmin, request, queryset):
    #q = queryset.email;
    #req = json.loads(str(queryset )
    #q = req['email']
    for i in queryset:
        print(json.loads(str(i)))
    print('asdasdadasd-->'+str(queryset))

Error trace:

Traceback:
File "/home/saurabh/Music/Project_ques10/test/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
  112.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/saurabh/Music/Project_ques10/test/lib/python3.4/site-packages/django/contrib/admin/options.py" in wrapper
  465.                 return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/saurabh/Music/Project_ques10/test/lib/python3.4/site-packages/django/utils/decorators.py" in _wrapped_view
  99.                     response = view_func(request, *args, **kwargs)
File "/home/saurabh/Music/Project_ques10/test/lib/python3.4/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  52.         response = view_func(request, *args, **kwargs)
File "/home/saurabh/Music/Project_ques10/test/lib/python3.4/site-packages/django/contrib/admin/sites.py" in inner
  198.             return view(request, *args, **kwargs)
File "/home/saurabh/Music/Project_ques10/test/lib/python3.4/site-packages/django/utils/decorators.py" in _wrapper
  29.             return bound_func(*args, **kwargs)
File "/home/saurabh/Music/Project_ques10/test/lib/python3.4/site-packages/django/utils/decorators.py" in _wrapped_view
  99.                     response = view_func(request, *args, **kwargs)
File "/home/saurabh/Music/Project_ques10/test/lib/python3.4/site-packages/django/utils/decorators.py" in bound_func
  25.                 return func(self, *args2, **kwargs2)
File "/home/saurabh/Music/Project_ques10/test/lib/python3.4/site-packages/django/contrib/admin/options.py" in changelist_view
  1364.                 response = self.response_action(request, queryset=cl.get_queryset(request))
File "/home/saurabh/Music/Project_ques10/test/lib/python3.4/site-packages/django/contrib/admin/options.py" in response_action
  1117.             response = func(self, request, queryset)
File "/home/saurabh/Music/Project_ques10/ques10-funda/biostar/apps/quespaper/admin.py" in authenticate_
  83.         print(json.loads(str(i)))
File "/usr/lib/python3.4/json/__init__.py" in loads
  318.         return _default_decoder.decode(s)
File "/usr/lib/python3.4/json/decoder.py" in decode
  343.         obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.4/json/decoder.py" in raw_decode
  361.             raise ValueError(errmsg("Expecting value", s, err.value)) from None

Exception Type: ValueError at /admin/quespaper/intermediate_table/
Exception Value: Expecting value: line 1 column 1 (char 0)

Please suggest the correct way of parsing each object.

Thanks.

Body:
Problem is that the object that you are trying to decode is not json encodable at the first place. Types acceptable to JSON are string, number, boolean, array and dict. So if you convert this object to string and try to decode it, then python won't be able to decode it to the right object and so it raises an error.

If you really want to use JSON format, you can use it on the string representations only after encoding it first like this:

for i in queryset:
    print(json.loads(json.dumps(str(i))))

You may also need to define__str__() method for your model.

Your code without json.loads() is failing because your Intermediate_table object has no attribute email.


来源: stackexchange

问:
How to output results from a for loop in a right way
I am trying to output results from a for loop. It doesn't output the right way. I have pasted the results in the end of my code. It shouldn't echo out like that.

```<code>for ($i = 0; $i < count($_FILES); $i++) {
      $target_path = $_FILES[$i];

        if($i == 0 ){
        $test1 = $target_path;
        }

        if($i == 1 ){
        $test2 = $target_path;
        }

//This part should output only 2 results but it outputs something different.
        echo $test1." img 1 <br>";

        echo $test2." img 2 <br>";
    }
</code>```

It shouldn't output the following:

```<code>73c4d636e78bc7d33f90c182fc6ffaec.png img 1
img 2
73c4d636e78bc7d33f90c182fc6ffaec.png img 1
5eeb5c30fc9bba82e057953945b06eab.jpg img 2
</code>```

答:
This should work.

```<code> for ($i = 0; $i < count($_FILES); $i++) {
  $target_path = $_FILES[$i];

  if($i == 0 ){
    $test1 = $target_path;
    echo $test1." img 1 <br>";
  }

  if($i == 1 ){
    $test2 = $target_path;
    echo $test2." img 2 <br>";
  }

}
</code>```

Or:

```<code> for ($i = 0; $i < count($_FILES); $i++) {
  $target_path = $_FILES[$i];

  if($i == 0 ){
    $test = $target_path;

  }

  if($i == 1 ){
    $test = $target_path;
  }

echo $test." img ".($i+1)." <br>";
}
</code>```

Or:

```<code> for ($i = 0; $i < count($_FILES); $i++) {
  $target_path = $_FILES[$i];

  if($i == 0 ){
    $test1 = $target_path;
  }

  if($i == 1 ){
    $test2 = $target_path;
  }

  if($i == 0 ){
    echo $test1." img 1 <br>";
  }
  //whatever
  if($i == 1 ){
    echo $test2." img 2 <br>";
  }

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to output results from a for loop. It doesn't output the right way. I have pasted the results in the end of my code. It shouldn't echo out like that.

for ($i = 0; $i < count($_FILES); $i++) {
      $target_path = $_FILES[$i];

        if($i == 0 ){
        $test1 = $target_path;
        }

        if($i == 1 ){
        $test2 = $target_path;
        }

//This part should output only 2 results but it outputs something different.
        echo $test1." img 1
";

        echo $test2." img 2
";
    }

It shouldn't output the following:

73c4d636e78bc7d33f90c182fc6ffaec.png img 1
img 2
73c4d636e78bc7d33f90c182fc6ffaec.png img 1
5eeb5c30fc9bba82e057953945b06eab.jpg img 2

Body:
This should work.

 for ($i = 0; $i < count($_FILES); $i++) {
  $target_path = $_FILES[$i];

  if($i == 0 ){
    $test1 = $target_path;
    echo $test1." img 1 <br>";
  }

  if($i == 1 ){
    $test2 = $target_path;
    echo $test2." img 2 <br>";
  }

}

Or:

 for ($i = 0; $i < count($_FILES); $i++) {
  $target_path = $_FILES[$i];

  if($i == 0 ){
    $test = $target_path;

  }

  if($i == 1 ){
    $test = $target_path;
  }

echo $test." img ".($i+1)." <br>";
}

Or:

 for ($i = 0; $i < count($_FILES); $i++) {
  $target_path = $_FILES[$i];

  if($i == 0 ){
    $test1 = $target_path;
  }

  if($i == 1 ){
    $test2 = $target_path;
  }

  if($i == 0 ){
    echo $test1." img 1 <br>";
  }
  //whatever
  if($i == 1 ){
    echo $test2." img 2 <br>";
  }

}


问:
Qt API to get application user data save location on iOS & Android
I am using commercial Qt 5.6 with app running on android & iOS. I want to save user data i.e .png & .jpeg files that my app generates. And, I want to keep the files private to the application so that other apps are not able to access them.

As I learn, the location I should use on iOS is

<Application_Home>/Documents

And, the location I should use for Android, it is

/mnt/sdcard/Android/data/<app_package_name>.

Is there an API in Qt which can return me the these file locations on iOS & android without having to deal with any java or swift code ?

答: Yes, have a look at the QStandardPaths Class.</p>


问:
Libgdx box2d ContactListener is extremely glitchy
I run into this situation while developing my little 2D side-scrolling platformer game using libgdx. The main problem is that beginContact(Contact contact) isn't called when it clearly needs to. Here are some simplified code snippets to give a quick overview:

ContactListener class which logs every contact between sensor and ground:

```<code>public class WorldContactListener implements ContactListener
{
Player player;

public WorldContactListener(Player player, World world)
{
    this.player = player;
    world.setContactListener(this);
}

@Override
public void beginContact(Contact contact)
{
    Object userDataA = contact.getFixtureA().getUserData();
    Object userDataB = contact.getFixtureB().getUserData();

    if((userDataA == Tomb.UserData.GROUND || userDataB == Tomb.UserData.GROUND)
  && (userDataA == Tomb.UserData.PLAYER_FEET  || userDataB == Tomb.UserData.PLAYER_FEET))
    {
        Gdx.app.log("collision", "start");
    }
}

@Override
public void endContact(Contact contact)
{
    Object userDataA = contact.getFixtureA().getUserData();
    Object userDataB = contact.getFixtureB().getUserData();

    if((userDataA == Tomb.UserData.GROUND || userDataB == Tomb.UserData.GROUND)
  && (userDataA == Tomb.UserData.PLAYER_FEET  || userDataB == Tomb.UserData.PLAYER_FEET))
    {
        Gdx.app.log("collision", "stop");
    }
}

@Override
public void preSolve(Contact contact, Manifold oldManifold)
{
}

@Override
public void postSolve(Contact contact, ContactImpulse impulse)
{
}
}
</code>```

Player creation:

```<code>    //Main rectangle:
    BodyDef bodyDef = new BodyDef();
    bodyDef.position.set(spawnCoordinates);
    bodyDef.type = BodyType.DynamicBody;
    body = world.createBody(bodyDef);
    FixtureDef fixtureDef = new FixtureDef();
    PolygonShape shape = new PolygonShape();
    shape.setAsBox(5 / Tomb.PPM, 14 / Tomb.PPM);
    fixtureDef.shape = shape;
    fixtureDef.friction = FRICTION; //1
    fixtureDef.restitution = RESTITUTION; //0
    body.createFixture(fixtureDef).setUserData(Tomb.UserData.PLAYER);

    //Circle-shaped sensor:
    fixtureDef = new FixtureDef();
    CircleShape feet = new CircleShape();
    feet.setPosition(new Vector2(0, -16 / Tomb.PPM));
    feet.setRadius(10 / Tomb.PPM);
    fixtureDef.shape = feet;
    fixtureDef.isSensor = true;
    body.createFixture(fixtureDef).setUserData(Tomb.UserData.PLAYER_FEET);
</code>```

Player movements:

```<code>private void handleInput(float delta)
{
    if(Gdx.input.isKeyJustPressed(Input.Keys.UP))
    {
        body.applyLinearImpulse(new Vector2(0, JUMP_POWER), body.getWorldCenter(), true);
    }
    if(Gdx.input.isKeyPressed(Input.Keys.RIGHT) && body.getLinearVelocity().x <= MAX_HORIZONTAL_VELOCITY)
    {
        body.applyLinearImpulse(new Vector2(HORIZONTAL_SPEED, 0), body.getWorldCenter(), true);
    }
    if(Gdx.input.isKeyPressed(Input.Keys.LEFT) && body.getLinearVelocity().x >= -MAX_HORIZONTAL_VELOCITY)
    {
        body.applyLinearImpulse(new Vector2(-HORIZONTAL_SPEED, 0), body.getWorldCenter(), true);
    }
}
</code>```

Initialization of a .tmx map, which is imported from Tiled Map Editor. It's noteworthy that whole terrain is one single PolygonMapObject, so specifically in this case for loop isn't needed.

```<code>protected void defineGround(int layerIndex)
{
    for(PolygonMapObject object : map.getLayers().get(layerIndex).getObjects().getByType(PolygonMapObject.class))
    {
        BodyDef bodyDef = new BodyDef();
        ChainShape chainShape = new ChainShape();
        FixtureDef fixtureDef = new FixtureDef();
        Body body;

        Polygon polygon = object.getPolygon();
        bodyDef.type = BodyType.StaticBody;
        bodyDef.position.set(polygon.getX() / Tomb.PPM, polygon.getY() / Tomb.PPM);
        body = world.createBody(bodyDef);
        float[] scaledVertices = new float[polygon.getVertices().length];
        for(int i = 0; i < polygon.getVertices().length; i++)
        {
            scaledVertices[i] = polygon.getVertices()[i] / Tomb.PPM;
        }
        chainShape.createChain(scaledVertices);
        fixtureDef.shape = chainShape;
        body.createFixture(fixtureDef).setUserData(Tomb.UserData.GROUND);
    }
}
</code>```

Finally, self-explaining pics, which show the game screen itself and eclipse console with WorldContactListener logs:

Same thing happens when trying to climb up the slope (or absolutely any non-flat surface):

I have tried all possible sensor shape and size variations, so this behavior isn't caused by CircleShape's size. What could be the case? Or any workaround which doesn't involve ContactListener?

答:
The deal is that there ale multiple collisions at one time. On your last image u can see that there are still (2-1 + 2-1) = 2 collisions between your player and polygons.

Here is my example solution:
Make some collision counter class with functions incCollision() and decCollision(), and maybe some bool isCollison() that will tell you if there actually is any collision.

Edit your ContactListener class:

```<code>public void beginContact(Contact contact)
{
...
   if((userDataA == Tomb.UserData.GROUND || userDataB == Tomb.UserData.GROUND)
      && (userDataA == Tomb.UserData.PLAYER_FEET  || userDataB == Tomb.UserData.PLAYER_FEET))
        {
            Gdx.app.log("collision", "start");
            counter.incCollision();
        }
}

public void endContact(Contact contact)
{
...
if((userDataA == Tomb.UserData.GROUND || userDataB == Tomb.UserData.GROUND)
  && (userDataA == Tomb.UserData.PLAYER_FEET  || userDataB == Tomb.UserData.PLAYER_FEET))
    {
        Gdx.app.log("collision", "stop");
        counter.decCollision();
    }
}
</code>```

Body:
I run into this situation while developing my little 2D side-scrolling platformer game using libgdx. The main problem is that beginContact(Contact contact) isn't called when it clearly needs to. Here are some simplified code snippets to give a quick overview:

ContactListener class which logs every contact between sensor and ground:

public class WorldContactListener implements ContactListener
{
Player player;

public WorldContactListener(Player player, World world)
{
    this.player = player;
    world.setContactListener(this);
}

@Override
public void beginContact(Contact contact)
{
    Object userDataA = contact.getFixtureA().getUserData();
    Object userDataB = contact.getFixtureB().getUserData();

    if((userDataA == Tomb.UserData.GROUND || userDataB == Tomb.UserData.GROUND)
  && (userDataA == Tomb.UserData.PLAYER_FEET  || userDataB == Tomb.UserData.PLAYER_FEET))
    {
        Gdx.app.log("collision", "start");
    }
}

@Override
public void endContact(Contact contact)
{
    Object userDataA = contact.getFixtureA().getUserData();
    Object userDataB = contact.getFixtureB().getUserData();

    if((userDataA == Tomb.UserData.GROUND || userDataB == Tomb.UserData.GROUND)
  && (userDataA == Tomb.UserData.PLAYER_FEET  || userDataB == Tomb.UserData.PLAYER_FEET))
    {
        Gdx.app.log("collision", "stop");
    }
}

@Override
public void preSolve(Contact contact, Manifold oldManifold)
{
}

@Override
public void postSolve(Contact contact, ContactImpulse impulse)
{
}
}

Player creation:

    //Main rectangle:
    BodyDef bodyDef = new BodyDef();
    bodyDef.position.set(spawnCoordinates);
    bodyDef.type = BodyType.DynamicBody;
    body = world.createBody(bodyDef);
    FixtureDef fixtureDef = new FixtureDef();
    PolygonShape shape = new PolygonShape();
    shape.setAsBox(5 / Tomb.PPM, 14 / Tomb.PPM);
    fixtureDef.shape = shape;
    fixtureDef.friction = FRICTION; //1
    fixtureDef.restitution = RESTITUTION; //0
    body.createFixture(fixtureDef).setUserData(Tomb.UserData.PLAYER);

    //Circle-shaped sensor:
    fixtureDef = new FixtureDef();
    CircleShape feet = new CircleShape();
    feet.setPosition(new Vector2(0, -16 / Tomb.PPM));
    feet.setRadius(10 / Tomb.PPM);
    fixtureDef.shape = feet;
    fixtureDef.isSensor = true;
    body.createFixture(fixtureDef).setUserData(Tomb.UserData.PLAYER_FEET);

Player movements:

private void handleInput(float delta)
{
    if(Gdx.input.isKeyJustPressed(Input.Keys.UP))
    {
        body.applyLinearImpulse(new Vector2(0, JUMP_POWER), body.getWorldCenter(), true);
    }
    if(Gdx.input.isKeyPressed(Input.Keys.RIGHT) && body.getLinearVelocity().x <= MAX_HORIZONTAL_VELOCITY)
    {
        body.applyLinearImpulse(new Vector2(HORIZONTAL_SPEED, 0), body.getWorldCenter(), true);
    }
    if(Gdx.input.isKeyPressed(Input.Keys.LEFT) && body.getLinearVelocity().x >= -MAX_HORIZONTAL_VELOCITY)
    {
        body.applyLinearImpulse(new Vector2(-HORIZONTAL_SPEED, 0), body.getWorldCenter(), true);
    }
}

Initialization of a .tmx map, which is imported from Tiled Map Editor. It's noteworthy that whole terrain is one single PolygonMapObject, so specifically in this case for loop isn't needed.

protected void defineGround(int layerIndex)
{
    for(PolygonMapObject object : map.getLayers().get(layerIndex).getObjects().getByType(PolygonMapObject.class))
    {
        BodyDef bodyDef = new BodyDef();
        ChainShape chainShape = new ChainShape();
        FixtureDef fixtureDef = new FixtureDef();
        Body body;

        Polygon polygon = object.getPolygon();
        bodyDef.type = BodyType.StaticBody;
        bodyDef.position.set(polygon.getX() / Tomb.PPM, polygon.getY() / Tomb.PPM);
        body = world.createBody(bodyDef);
        float[] scaledVertices = new float[polygon.getVertices().length];
        for(int i = 0; i < polygon.getVertices().length; i++)
        {
            scaledVertices[i] = polygon.getVertices()[i] / Tomb.PPM;
        }
        chainShape.createChain(scaledVertices);
        fixtureDef.shape = chainShape;
        body.createFixture(fixtureDef).setUserData(Tomb.UserData.GROUND);
    }
}

Finally, self-explaining pics, which show the game screen itself and eclipse console with WorldContactListener logs:

Same thing happens when trying to climb up the slope (or absolutely any non-flat surface):

I have tried all possible sensor shape and size variations, so this behavior isn't caused by CircleShape's size. What could be the case? Or any workaround which doesn't involve ContactListener?

Body:
The deal is that there ale multiple collisions at one time. On your last image u can see that there are still (2-1 + 2-1) = 2 collisions between your player and polygons.

Here is my example solution:
Make some collision counter class with functions incCollision() and decCollision(), and maybe some bool isCollison() that will tell you if there actually is any collision.

Edit your ContactListener class:

public void beginContact(Contact contact)
{
...
   if((userDataA == Tomb.UserData.GROUND || userDataB == Tomb.UserData.GROUND)
      && (userDataA == Tomb.UserData.PLAYER_FEET  || userDataB == Tomb.UserData.PLAYER_FEET))
        {
            Gdx.app.log("collision", "start");
            counter.incCollision();
        }
}

public void endContact(Contact contact)
{
...
if((userDataA == Tomb.UserData.GROUND || userDataB == Tomb.UserData.GROUND)
  && (userDataA == Tomb.UserData.PLAYER_FEET  || userDataB == Tomb.UserData.PLAYER_FEET))
    {
        Gdx.app.log("collision", "stop");
        counter.decCollision();
    }
}


问:
Cant get Element of an HashMap that are new puttet?
Hey guys I have no Idea what happen? I add birthdays but if call them with getHashMap for example I cant get the elements in the class swingmenu. I just have thoughts about the Problem. I think its because I call new Event in a class and where I output the hashmap in a different class I call new Event too. But I dont know if I am right?

Maybe any Solution would help me. If you have Question then please ask me. For me its important to learn something new. There are some short coded showen because its not relevant. I debug the class swingFormatFunction and find out that the the instance event is null.

This part dont get added into my HashMap.

```<code>public class swingFormatFunction{
private Event event = new Event();
public void geburtstageFormatieren(String content) {
    String formatContent = content.replace(';', ' ');
    for (String s : formatContent.split("\n")) {
        event.addBirthday(s.substring(0, 5).toString(), new Event(s.substring(12).toString()));
    }

}
}
</code>```

That is my menu where I call a Menuitem and click "ok". This function works fine I get the elements outputted.

```<code>public class swingMenu{
okBTN.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == okBTN) {
            dialog.dispose();
            JDialog dialog = new JDialog();
            dialog.setModal(true);
            dialog.setTitle("Calendar Special Events");
            int yearNumber = Integer.parseInt((String) yearCombobox.getSelectedItem());
            JTextArea textArea = new JTextArea();

            Event event = new Event(yearNumber);
            StringBuilder stringBuilder = new StringBuilder();

            for (Map.Entry entry : event.getEventMap().entrySet()) {
                stringBuilder.append(entry.getKey() + " : " + entry.getValue() + "\n");
            }

            textArea.setText(stringBuilder.toString());
            dialog.setContentPane(textArea);

            dialog.pack();
            dialog.setLocationRelativeTo(null);
            dialog.setResizable(true);
            textArea.setEditable(false);
            dialog.setVisible(true);

        }
    }
});
</code>```

That is my Event class. This class contains my HashMap where I work with it.

```<code>    public class Event{
    private HashMap<String, Event> eventMap = new HashMap<>();
    public Event(String name) {
        this.name = name;
    }

    public Event(int year) {
        addStrongMoveableHolidayInMap(year);
    }

    public Event() {

    }

    private void addMoveableHoliday(int year) {
        /*      Bewegliche Feiertage    */

        /*Rose monday (-48)*/
        int daynumberOfEasterSunday = calenderFunction.easterSunday(year) - 48;
        String gregorDate = calenderFunction.kalenderDatumFuerJD(daynumberOfEasterSunday);

        String day = gregorDate.substring(0, 2);
        String month = gregorDate.substring(3, 5);
        String date = day + "." + month;
        this.eventMap.put(date, new Event("Rosenmontag"));
    }

    private void addStrongHoliday(int year) {
        /*      Feste Feiertage         */
        this.eventMap.put("24.12", new Event("1. Weihnachtstag"));
    }

    void addStrongMoveableHolidayInMap(int year) {
        addStrongHoliday(year);
        addMoveableHoliday(year);
    }

    public void addBirthday(String year, Event event) {
        this.eventMap.put(year, event);
    }

    public HashMap<String, Event> getEventMap() {
        return eventMap;
    }
}
</code>```

I hope you guys can help me.

Best Regards
Manuellsen

答:
The two event objects are totally independent.
The first one in swingFormatFunction is a instance attribute and the second one in ActionListener is a local variable.

The Event's eventMap attribute is also an instance attribute, so each Event object has its own map. Maybe you want to share one eventMap accross all events.

Body:
Hey guys I have no Idea what happen? I add birthdays but if call them with getHashMap for example I cant get the elements in the class swingmenu. I just have thoughts about the Problem. I think its because I call new Event in a class and where I output the hashmap in a different class I call new Event too. But I dont know if I am right?

Maybe any Solution would help me. If you have Question then please ask me. For me its important to learn something new. There are some short coded showen because its not relevant. I debug the class swingFormatFunction and find out that the the instance event is null.

This part dont get added into my HashMap.

public class swingFormatFunction{
private Event event = new Event();
public void geburtstageFormatieren(String content) {
    String formatContent = content.replace(';', ' ');
    for (String s : formatContent.split("\n")) {
        event.addBirthday(s.substring(0, 5).toString(), new Event(s.substring(12).toString()));
    }

}
}

That is my menu where I call a Menuitem and click "ok". This function works fine I get the elements outputted.

public class swingMenu{
okBTN.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == okBTN) {
            dialog.dispose();
            JDialog dialog = new JDialog();
            dialog.setModal(true);
            dialog.setTitle("Calendar Special Events");
            int yearNumber = Integer.parseInt((String) yearCombobox.getSelectedItem());
            JTextArea textArea = new JTextArea();

            Event event = new Event(yearNumber);
            StringBuilder stringBuilder = new StringBuilder();

            for (Map.Entry entry : event.getEventMap().entrySet()) {
                stringBuilder.append(entry.getKey() + " : " + entry.getValue() + "\n");
            }

            textArea.setText(stringBuilder.toString());
            dialog.setContentPane(textArea);

            dialog.pack();
            dialog.setLocationRelativeTo(null);
            dialog.setResizable(true);
            textArea.setEditable(false);
            dialog.setVisible(true);

        }
    }
});

That is my Event class. This class contains my HashMap where I work with it.

    public class Event{
    private HashMap<String, Event> eventMap = new HashMap<>();
    public Event(String name) {
        this.name = name;
    }

    public Event(int year) {
        addStrongMoveableHolidayInMap(year);
    }

    public Event() {

    }

    private void addMoveableHoliday(int year) {
        /*      Bewegliche Feiertage    */

        /*Rose monday (-48)*/
        int daynumberOfEasterSunday = calenderFunction.easterSunday(year) - 48;
        String gregorDate = calenderFunction.kalenderDatumFuerJD(daynumberOfEasterSunday);

        String day = gregorDate.substring(0, 2);
        String month = gregorDate.substring(3, 5);
        String date = day + "." + month;
        this.eventMap.put(date, new Event("Rosenmontag"));
    }

    private void addStrongHoliday(int year) {
        /*      Feste Feiertage         */
        this.eventMap.put("24.12", new Event("1. Weihnachtstag"));
    }

    void addStrongMoveableHolidayInMap(int year) {
        addStrongHoliday(year);
        addMoveableHoliday(year);
    }

    public void addBirthday(String year, Event event) {
        this.eventMap.put(year, event);
    }

    public HashMap<String, Event> getEventMap() {
        return eventMap;
    }
}

I hope you guys can help me.

Best Regards
Manuellsen


问:
Efficient way to convert all data frame columns in Scala
I am trying to do type cast of all data frame columns based on an input as shown below, how can I do this with a single command that converts all data frame columns? The following code works fine, but I need a generic command that works for any data frame. Thanks in advance for your kind suggestions.</p>

```<code>    for (colIndex <- 0 to tmpDF.columns.length - 1) {

      val columns = df.columns
      newdf = df.withColumn(columns(0), df(columns(0)).cast(dataType(0)))
        .withColumn(columns(1), df(columns(1)).cast(dataType(1)))
        .withColumn(columns(2), df(columns(2)).cast(dataType(2)))
        .withColumn(columns(3), df(columns(3)).cast(dataType(3)))
        .withColumn(columns(4), df(columns(4)).cast(dataType(4)))

   //  newdf = df.withColumn(columns(colIndex), df(columns(colIndex)).cast(dataType(colIndex))) --> This didn't work, only last column was updated

}
</code>```

答:
Another suggestion, using a more "functional way", is with foldLeft. In this case, your "dataType" variable can be a Map[String, DataType] (or Map[String, String]) mapping each column name to the new type you want to give :

import org.apache.spark.sql.types._
import spark.implicits._

val df = Seq((1, "1"), (2, "2")).toDF("col1", "col2")

val dataType: Map[String, DataType] = Map(
  "col1" -> StringType,
  "col2" -> IntegerType
)

val result = df.columns.foldLeft(df) {
  (newDF, colName) => newDF.withColumn(colName, newDF(colName).cast(dataType(colName)))
}

result.show
```

<p>Note that no mutable vars were needed, which in Scala should often be our goal.</p>

<p>If you want to keep using the indexes instead of the column names, you can adapt the code above accordingly:</p>

<pre class="lang-scala prettyprint-override"><code>val dataType = List(StringType, IntegerType)
val cols = df.columns
val result = cols.indices.foldLeft(df) {
  (newDF, i) => newDF.withColumn(cols(i), newDF(cols(i)).cast(dataType(i)))
}
</code>```

In both cases, the output is:

df: org.apache.spark.sql.DataFrame = [col1: int, col2: string]
result: org.apache.spark.sql.DataFrame = [col1: string, col2: int]

+----+----+
|col1|col2|
+----+----+
|   1|   1|
|   2|   2|
+----+----+
```

Here you can find some info about foldLeft.

Body:
I am trying to do type cast of all data frame columns based on an input as shown below, how can I do this with a single command that converts all data frame columns? The following code works fine, but I need a generic command that works for any data frame. Thanks in advance for your kind suggestions.

    for (colIndex <- 0 to tmpDF.columns.length - 1) {

      val columns = df.columns
      newdf = df.withColumn(columns(0), df(columns(0)).cast(dataType(0)))
        .withColumn(columns(1), df(columns(1)).cast(dataType(1)))
        .withColumn(columns(2), df(columns(2)).cast(dataType(2)))
        .withColumn(columns(3), df(columns(3)).cast(dataType(3)))
        .withColumn(columns(4), df(columns(4)).cast(dataType(4)))

   //  newdf = df.withColumn(columns(colIndex), df(columns(colIndex)).cast(dataType(colIndex))) --> This didn't work, only last column was updated

}

Body:
Another suggestion, using a more "functional way", is with foldLeft. In this case, your "dataType" variable can be a Map[String, DataType] (or Map[String, String]) mapping each column name to the new type you want to give :

import org.apache.spark.sql.types._
import spark.implicits._

val df = Seq((1, "1"), (2, "2")).toDF("col1", "col2")

val dataType: Map[String, DataType] = Map(
  "col1" -> StringType,
  "col2" -> IntegerType
)

val result = df.columns.foldLeft(df) {
  (newDF, colName) => newDF.withColumn(colName, newDF(colName).cast(dataType(colName)))
}

result.show

Note that no mutable vars were needed, which in Scala should often be our goal.

If you want to keep using the indexes instead of the column names, you can adapt the code above accordingly:

val dataType = List(StringType, IntegerType)
val cols = df.columns
val result = cols.indices.foldLeft(df) {
  (newDF, i) => newDF.withColumn(cols(i), newDF(cols(i)).cast(dataType(i)))
}

In both cases, the output is:

df: org.apache.spark.sql.DataFrame = [col1: int, col2: string]
result: org.apache.spark.sql.DataFrame = [col1: string, col2: int]

+----+----+
|col1|col2|
+----+----+
|   1|   1|
|   2|   2|
+----+----+

Here you can find some info about foldLeft.


问:
Database design in GAE/J : relational modelling vs entity-attribute-value
Imagine you plan to create a social network running on GAE/Java where each user has a set of properties  (i.e. age, current town, interests).

Alternative 1: classical approach - the user_id and every property as a "row"

```<code>entity  property_1 property_2 property_3
------  ---------- ---------- -----------------
bob     missing    NY         [football, books]
tom     34         missing    [books, horses]
</code>```

Alternative 2: entity-atributte-value (EAV)

```<code>entity   attribute   value
------   ---------   -----
bob      town        NY
bob      interests   [football, books]
tom      age         34
tom      interests   [books, horses]
</code>```

What pros/cons do you think each option has?  My main concerns are:

What is the impact on multi-criteria searches (i.e. "give me the users with ages under 45 that live in NY and like books")

What GAE/J implications could it have? (i.e. indexes, datastore size...)

How to model attributes with multiple values ("interests" for example) if you want to retrieve "users that like books" ?

I think the second alternative is more flexible and maybe easier to implement, but I would like to know what other experienced developers think.

Thank you.

答: Did you have a look at Building Scalable, Complex Apps on App Engine from Google I/O 2009? The video has terrible sound-quality, but it covers your topics. He talks about list properties and merge-joins and their limitations.</p>

ContentLicense: CC BY-SA 2.5

Body:
Imagine you plan to create a social network running on GAE/Java where each user has a set of properties  (i.e. age, current town, interests).

Alternative 1: classical approach - the user_id and every property as a "row"

entity  property_1 property_2 property_3
------  ---------- ---------- -----------------
bob     missing    NY         [football, books]
tom     34         missing    [books, horses]

Alternative 2: entity-atributte-value (EAV)

entity   attribute   value
------   ---------   -----
bob      town        NY
bob      interests   [football, books]
tom      age         34
tom      interests   [books, horses]

What pros/cons do you think each option has?  My main concerns are:

What is the impact on multi-criteria searches (i.e. "give me the users with ages under 45 that live in NY and like books")

What GAE/J implications could it have? (i.e. indexes, datastore size...)

How to model attributes with multiple values ("interests" for example) if you want to retrieve "users that like books" ?

I think the second alternative is more flexible and maybe easier to implement, but I would like to know what other experienced developers think.

Thank you.


问:
Showing Filename Differences in List Array (Java)
I am trying to compare files and my solution works with folders that have a small amount of files in them like 10 but not folders with like over 200 filenames in them. The last part of my codes comes back NULL or Results = [ ] usually the text file(s) name is in here that shows the difference between both folders any help is appreciated. The problem is the last part of my code

```<code>package nameCompare;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

// https://stackoverflow.com/questions/19662384/comparing-file-names
// http://www.javaprogrammingforums.com/java-programming-tutorials/3-java-program-can-list-all-files-given-directory.html

public class fileNameCompare {

    public static void main(String[] args) {
                             // first directory path here
        String path1 = "C:/Users/Jonathan/Desktop/ADP/MagMediaAfter";
        //String path1 = "C:/Users/Jonathan/Desktop/FolderA";

        // second directory path here
        String path2 = "C:/Users/Jonathan/Desktop/ADP/MagMediaAfter";
        //String path2 = "C:/Users/Jonathan/Desktop/FolderB";

        File folder1 = new File(path1);
        int fileCount = folder1.list().length;

        File folder2 = new File(path2);
        int fileCountTwo = folder2.list().length;

        File[] listOfFiles1 = folder1.listFiles();
        File[] listOfFiles2 = folder2.listFiles();

        //we'll need these to store the file names as Strings
        ArrayList<String> BeforeMM = new ArrayList<String>();
        ArrayList<String> AfterMM = new ArrayList<String>();

        //get file names from directory
        for (int i = 0; i < listOfFiles1.length; i++)
        {
            if (listOfFiles1[i].isFile())
            {
                BeforeMM.add(listOfFiles1[i].getName());//wow
            }
        }

        for (int i = 0; i < listOfFiles2.length; i++)
        {
            if (listOfFiles2[i].isFile())
            {
                AfterMM.add(listOfFiles2[i].getName());//seriously wow
            }
        }

            // Number of Files in each Folder or Directory
            System.out.println("Files in FolderA / BeforeMM ----> " + fileCount );
            System.out.println("Files in FolderB / AfterMM -----> " + fileCountTwo );
            System.out.println("------------------------------------");

            System.out.println( "Size/Number of Array Elements BeforeMM -----> "+BeforeMM.size() );
            System.out.println( "Size/Number of Array Elements AfterMM  -----> "+AfterMM.size() );
            System.out.println("------------------------------------");

            System.out.println("Before Media Folder Conatins----> " + BeforeMM );
            System.out.println("After Media Folder  Conatins----> " + AfterMM );
            System.out.println("------------------------------------");
            //this is where problems start
            List<String> result = AfterMM.stream().filter(elem -> !BeforeMM.contains(elem)).collect(Collectors.toList());
            System.out.println("Result: File(s) present in After BUT NOT BeforeMM folder:\n" + result);
            // Result equals Test2.txt

            /*// Remove all elements in BeforeFolder from AfterFolder
            BeforeMM.removeAll(AfterMM);
            // Show results
            System.out.println("Result: " + AfterMM);
            */

    }

}
</code>```

答:
I don't see a problem in your code,I had tried the code for two directories which had around 1K files.See at anypoint the BeforeMM is always the superset.the result can be empty in two cases

Files in BeforeMM == Files in AfterMM

Files in AfterMM = Files in BeforeMM - few files missing

Body:
I am trying to compare files and my solution works with folders that have a small amount of files in them like 10 but not folders with like over 200 filenames in them. The last part of my codes comes back NULL or Results = [ ] usually the text file(s) name is in here that shows the difference between both folders any help is appreciated. The problem is the last part of my code

package nameCompare;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

// https://stackoverflow.com/questions/19662384/comparing-file-names
// http://www.javaprogrammingforums.com/java-programming-tutorials/3-java-program-can-list-all-files-given-directory.html

public class fileNameCompare {

    public static void main(String[] args) {
                             // first directory path here
        String path1 = "C:/Users/Jonathan/Desktop/ADP/MagMediaAfter";
        //String path1 = "C:/Users/Jonathan/Desktop/FolderA";

        // second directory path here
        String path2 = "C:/Users/Jonathan/Desktop/ADP/MagMediaAfter";
        //String path2 = "C:/Users/Jonathan/Desktop/FolderB";

        File folder1 = new File(path1);
        int fileCount = folder1.list().length;

        File folder2 = new File(path2);
        int fileCountTwo = folder2.list().length;

        File[] listOfFiles1 = folder1.listFiles();
        File[] listOfFiles2 = folder2.listFiles();

        //we'll need these to store the file names as Strings
        ArrayList<String> BeforeMM = new ArrayList<String>();
        ArrayList<String> AfterMM = new ArrayList<String>();

        //get file names from directory
        for (int i = 0; i < listOfFiles1.length; i++)
        {
            if (listOfFiles1[i].isFile())
            {
                BeforeMM.add(listOfFiles1[i].getName());//wow
            }
        }

        for (int i = 0; i < listOfFiles2.length; i++)
        {
            if (listOfFiles2[i].isFile())
            {
                AfterMM.add(listOfFiles2[i].getName());//seriously wow
            }
        }

            // Number of Files in each Folder or Directory
            System.out.println("Files in FolderA / BeforeMM ----> " + fileCount );
            System.out.println("Files in FolderB / AfterMM -----> " + fileCountTwo );
            System.out.println("------------------------------------");

            System.out.println( "Size/Number of Array Elements BeforeMM -----> "+BeforeMM.size() );
            System.out.println( "Size/Number of Array Elements AfterMM  -----> "+AfterMM.size() );
            System.out.println("------------------------------------");

            System.out.println("Before Media Folder Conatins----> " + BeforeMM );
            System.out.println("After Media Folder  Conatins----> " + AfterMM );
            System.out.println("------------------------------------");
            //this is where problems start
            List<String> result = AfterMM.stream().filter(elem -> !BeforeMM.contains(elem)).collect(Collectors.toList());
            System.out.println("Result: File(s) present in After BUT NOT BeforeMM folder:\n" + result);
            // Result equals Test2.txt

            /*// Remove all elements in BeforeFolder from AfterFolder
            BeforeMM.removeAll(AfterMM);
            // Show results
            System.out.println("Result: " + AfterMM);
            */

    }

}


问:
Setting TCP timeout for SQL connection in Go
When I connect to database (using standard go sql library) using VPN and VPN interface goes down, there's a 75 seconds timeout when I try to do SQL query, no matter if the interface goes up meanwhile. I'd like to decrease this timeout to some reasonable time, so my application won't be frozen for 75 seconds in such case.

```<code>db, err := sql.Open(driverName, dataSourceName)
</code>```

Is it possible to set it somehow via db variable?

答:
Starting with Go 1.8, the sql.DB abstraction now accepts context.Context, which can be used to time out connections faster.

```<code>func (c *Client) DoLookup(ctx context.Context, id int) (string, error) {
  var name string
  // create a child context with a timeout
  newCtx, cancel := context.WithTimeout(ctx, time.Second)
  // release resources used in `newCtx` if
  // the DB operation finishes faster than the timeout
  defer cancel()

  row := c.db.QueryRowContext(newCtx, "SELECT name FROM items WHERE id = ?", id)

  err := row.Scan(&name)
  if err != nil {
    return "", err
  }

  return name, nil
}
</code>```

If your DoLookup function doesn't yet take a context.Context (and it really should!) you can create a parent one by calling context.TODO().

ContentLicense: CC BY-SA 4.0

Body:
When I connect to database (using standard go sql library) using VPN and VPN interface goes down, there's a 75 seconds timeout when I try to do SQL query, no matter if the interface goes up meanwhile. I'd like to decrease this timeout to some reasonable time, so my application won't be frozen for 75 seconds in such case.

db, err := sql.Open(driverName, dataSourceName)

Is it possible to set it somehow via db variable?

Body:
Starting with Go 1.8, the sql.DB abstraction now accepts context.Context, which can be used to time out connections faster.

func (c *Client) DoLookup(ctx context.Context, id int) (string, error) {
  var name string
  // create a child context with a timeout
  newCtx, cancel := context.WithTimeout(ctx, time.Second)
  // release resources used in `newCtx` if
  // the DB operation finishes faster than the timeout
  defer cancel()

  row := c.db.QueryRowContext(newCtx, "SELECT name FROM items WHERE id = ?", id)

  err := row.Scan(&name)
  if err != nil {
    return "", err
  }

  return name, nil
}

If your DoLookup function doesn't yet take a context.Context (and it really should!) you can create a parent one by calling context.TODO().


问:
Virtual functions and performance - C++
In my class design, I use abstract classes and virtual functions extensively. I had a  feeling that virtual functions affects the performance. Is this true? But I think this performance difference is not noticeable and looks like I am doing premature optimization. Right?</p>

答:
The only ever way that I can see that a virtual function will become a performance problem is if many virtual functions are called within a tight loop, and if and only if they cause a page fault or other "heavy" memory operation to occur.

Though like other people have said it's pretty much never going to be a problem for you in real life. And if you think it is, run a profiler, do some tests, and verify if this really is a problem before trying to "undesign" your code for a performance benefit.

OwnerDisplayName: Appu

Title: Virtual functions and performance - C++

LastEditorDisplayName: Serge

OwnerDisplayName: Daemin


问:
Send message from server at specific time in php?
Is there any way to send mail at specific time in php?

Please give me hint for that file. I forget to that file which is used to send mail to specific time.

答: Note that cron jobs can be easily configured at your Cpanel ( if you have one )</p>


问:
Stuck in echoing data out of variable CodeIgniter
I try to get some information out of my database to my webpage. Everything seems to be fine but there is one thing that doesn't want to go right. I put all my information out my database into $data. When i do this

```<code>print_r($data);
</code>```

My webpage gives me this:

```<code>(
[0] => stdClass Object
   (
   [reparatie_id] => 19
   [customer_id] => 4
   [medewerker] => 4
   [name] => Joost
   )
)
</code>```

Everything seems to be good but when i try to do this:

```<code>echo $data->voornaam;
</code>```

I keep getting this error

```<code>A PHP Error was encountered

Severity: Notice

Message:  Trying to get property of non-object

Filename: reparaties/cases.php

Line Number: 7

Backtrace:

        File: C:\Ampps\www\beco\application\views\reparaties\cases.php

        Line: 7

        Function: _error_handler

        File: C:\Ampps\www\beco\application\controllers\Reparaties.php

        Line: 57

        Function: view

        File: C:\Ampps\www\beco\public\index.php

        Line: 315

        Function: require_once
</code>```

答:
```<code>Actually the $data array has an object at 0 position. So you need to any property of object. do like this:
<?php
$data[0]->reparatie_id;
$data[0]->customer_id;
$data[0]->medewerker;
$data[0]->name; ?>
output will be:
19, 4, 4, joost
</code>```

Body:
I try to get some information out of my database to my webpage. Everything seems to be fine but there is one thing that doesn't want to go right. I put all my information out my database into $data. When i do this

print_r($data);

My webpage gives me this:

(
[0] => stdClass Object
   (
   [reparatie_id] => 19
   [customer_id] => 4
   [medewerker] => 4
   [name] => Joost
   )
)

Everything seems to be good but when i try to do this:

echo $data->voornaam;

I keep getting this error

A PHP Error was encountered

Severity: Notice

Message:  Trying to get property of non-object

Filename: reparaties/cases.php

Line Number: 7

Backtrace:

        File: C:\Ampps\www\beco\application\views\reparaties\cases.php

        Line: 7

        Function: _error_handler

        File: C:\Ampps\www\beco\application\controllers\Reparaties.php

        Line: 57

        Function: view

        File: C:\Ampps\www\beco\public\index.php

        Line: 315

        Function: require_once


问:
Using Go to write a library for an iPhone app
I'm considering using Go as a low-level, performant language alternative to C/Objective-C to implement a library for an iPhone App. Could either of the Go compilers generate a library that could be linked into a native iPhone app with the Go runtime, etc.? Is there an ARM port for Go or does gccgo/gcc support this? I imagine that since gccgo uses gcc as the back-end and Xcode uses gcc to compile iPhone apps that there is a strong chance that this is possible. If it's possible, how would I set that up in an Xcode project?

Has anyone tried this or seen it discussed before? (When I do a Google search like "compiling go code iphone" the "go" part is completely unused and I get only stuff about iPhone development.)

答: The Go Mobile project now has some support for IOS and Android mobile development. See the wiki section on Building for IOS for details for your application.</p>


问:
Adding '' to every character of a tuple sublist
Hello I'm just finishing my Lorenz code but i have struggle with something, I can't add '' to a character of a list.

```<code>my_sublist:[(0,0,0,0,0,0,0),(0,0,0,0,0,0,1),(0,0,0,0,0,1,0)]
</code>```

and the output that I expect is:

```<code>my_sublist:[('0','0','0','0','0','0','0'),('0','0','0','0','0','0','1'),('0','0','0','0','0','1','0')]
</code>```

答:
What you want isn't adding quote characters, it's converting your values in your tuples to strings. You can do that like this:

```<code>In [397]: my_sublist = [(0, 0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0, 1), (0, 0, 0, 0, 0, 1, 0)]

In [398]: x = list(map(lambda x: tuple(map(str, x)), my_sublist))

In [399]: x
Out[399]:
[('0', '0', '0', '0', '0', '0', '0'),
 ('0', '0', '0', '0', '0', '0', '1'),
 ('0', '0', '0', '0', '0', '1', '0')]
</code>```

What this does is, it converts each element to a string using the map function:

```<code>In [400]: x = (1, 2, 3, 4)

In [403]: tuple(map(str, x))
Out[403]: ('1', '2', '3', '4')
</code>```

And since you have a list of tuples, just apply the same thing above to each one tuple in your list.

Body:
Hello I'm just finishing my Lorenz code but i have struggle with something, I can't add '' to a character of a list.

my_sublist:[(0,0,0,0,0,0,0),(0,0,0,0,0,0,1),(0,0,0,0,0,1,0)]

and the output that I expect is:

my_sublist:[('0','0','0','0','0','0','0'),('0','0','0','0','0','0','1'),('0','0','0','0','0','1','0')]

Body:
What you want isn't adding quote characters, it's converting your values in your tuples to strings. You can do that like this:

In [397]: my_sublist = [(0, 0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0, 1), (0, 0, 0, 0, 0, 1, 0)]

In [398]: x = list(map(lambda x: tuple(map(str, x)), my_sublist))

In [399]: x
Out[399]:
[('0', '0', '0', '0', '0', '0', '0'),
 ('0', '0', '0', '0', '0', '0', '1'),
 ('0', '0', '0', '0', '0', '1', '0')]

What this does is, it converts each element to a string using the map function:

In [400]: x = (1, 2, 3, 4)

In [403]: tuple(map(str, x))
Out[403]: ('1', '2', '3', '4')

And since you have a list of tuples, just apply the same thing above to each one tuple in your list.


问:
How to display only selected products in Spree?
Am using Spree Commerce, and right now every product I add on my backend is displayed on the homepage. Is there a way that I can display only products of my choice on the frontpage, and not display everything as it does by default?

I know deface allows me to customise the look of everything, but it is not the answer I am looking for.

Thanks

答:
@elliot Actually it's pretty simple. Go to product's edit page on admin end and set discontinue_on for that product with a date equal to the current date or lesser.
Only those product are visible on the frontend for which available_on is lesser than the current date and discontinue_on is greater than the current date.


问:
Change report display from ALV Grid to ALV List Viewer
I've been asked to change an ALV Grid report to ALV List Viewer. What I have found so far is that the only thing I need is to replace the REUSE_ALV_GRID_DISPLAY function for REUSE_ALV_LIST_DISPLAY (please correct me if I am wrong).

However, the report I need to change is using the cl_gui_alv_grid class which does not use the functions above.

What can I do to change the report using cl_gui_alv_grid? Or there is no way and I have to rewrite the code and use REUSE_ALV_LIST_DISPLAY?

答:
It is impossible with cl_gui_alv_grid. You should use cl_salv_table with list-display parameter to accomplish this:

```<code>    cl_salv_table=>factory(
      EXPORTING
        list_display = abap_true
      IMPORTING
        r_salv_table = o_alv
      CHANGING
        t_table      = lt_table ).
</code>```

Body:
It is impossible with cl_gui_alv_grid. You should use cl_salv_table with list-display parameter to accomplish this:

    cl_salv_table=>factory(
      EXPORTING
        list_display = abap_true
      IMPORTING
        r_salv_table = o_alv
      CHANGING
        t_table      = lt_table ).


问:
Xcode won't recognize my new provisioning profile
My app's development provisioning profile expired a couple of weeks ago, so I went to the provisioning portal to get a fresh new one. After obtaining it, I visited the Xcode Organizer, removed the expired profile from my devices as well as my Mac, then imported the new profile. Xcode installs the profile onto my devices immediately, and my app runs again on the devices.

The problem is that while the Organizer is able to see the new profile and install it as normal, the IDE gets confused between the old one and the new one. Every time I try to build the app, it fails immediately. The error console tells me that Xcode can't find the old profile, because the GUID listed belongs to the old one. That's strange; I thought Xcode would've been aware of the new profile by now.

I've tried removing the new profile from my devices and my Mac, then reinstalling the profile. Doesn't work, Xcode is still trying to look for the old one. I've also tried selecting a different profile to make Xcode forget the old one, then selecting the new one. I've even tried manually entering the GUID of the new one in the Other choice. Yet Xcode still insists on looking for the old profile, which by now is already gone from my Mac.

How do I convince Xcode that I've generated a new provisioning profile for my app for it to use?

答:
Most answers did not work for me as they seem to be for older versions.

For Xcode 8.3.2:

Xcode->Preferences->Accounts

Select Apple ID

Double-click your Team

Click the '+' dropdown in the bottom left to "Create a certificate"

Choose iOS Development

Click 'Done'

After doing this I was able to tell Xcode was using the latest profile by clicking the 'i' info icon next to "Xcode Managed Profile" under Targets->General->Signing and confirming that the 'Created' date reflected the new one.


问:
Char-array to int
I have an array char input[11] = {'0','2','7', '-','1','1','2', ,'0','0','9','5'};

How do I convert input[0,1,2] to int one = 27, input[3,4,5,6] to int two = -112 and input[7,8,9,10] to int three = 95?

thx, JNK

答:
You can use a combination of strncpy() to extract the character range and atoi() to convert it to an integer (or read this question for more ways to convert a string to an int).

```<code>int extract(char *input, int from, int length) {
  char temp[length+1] = { 0 };
  strncpy(temp, input+from, length);
  return atoi(temp);
}

int main() {
  char input[11] = {'0','2','7','-','1','1','2','0','0','9','5'};
  cout << "Heading: " << extract(input, 0, 3) << endl;
  cout << "Pitch:   " << extract(input, 3, 4) << endl;
  cout << "Roll:    " << extract(input, 7, 4) << endl;
}
</code>```

Outputs

```<code>Heading: 27
Pitch:   -112
Roll:    95
</code>```

http://ideone.com/SUutl

Title: Char-array to int

Body:
You can use a combination of strncpy() to extract the character range and atoi() to convert it to an integer (or read this question for more ways to convert a string to an int).

int extract(char *input, int from, int length) {
  char temp[length+1] = { 0 };
  strncpy(temp, input+from, length);
  return atoi(temp);
}

int main() {
  char input[11] = {'0','2','7','-','1','1','2','0','0','9','5'};
  cout << "Heading: " << extract(input, 0, 3) << endl;
  cout << "Pitch:   " << extract(input, 3, 4) << endl;
  cout << "Roll:    " << extract(input, 7, 4) << endl;
}

Outputs

Heading: 27
Pitch:   -112
Roll:    95

http://ideone.com/SUutl


问:
strlen() dosn't count with if/else statments
I want to count my text from database and if it is more than (ex. 100) characters i want to display a button Read More so when you clck it it sends me to full text here are my codes:

index.php

```<code>$sql = "SELECT * FROM posts ORDER BY `posts`.`id` DESC";
    $result = mysqli_query($conn,$sql);
    while ($row = mysqli_fetch_assoc($result)) {
        echo "<div id='posts'>
        <h3>".$row['titulli']."</h3>
        <h5>".$row['data']."</h5>
        <p>".$row['teksti']."</p>
        ".$count = $row['teksti'];
         echo "<button><a href='post.php?titulli=".$row['titulli']."&data=".$row['data']."'>Read More</a></button></div>";
        }
</code>```

I added an if statment but i think i have an error writing it:
When i add this code to it, it totaly brakes my page

```<code>  while ($row = mysqli_fetch_assoc($result)) {
        echo "<div id='posts'>
        <h3>".$row['titulli']."</h3>
        <h5>".$row['data']."</h5>
        <p>".$row['teksti']."</p>
        ".$count = $row['teksti'];
        if (strlen($count > 100)) {
            echo "<button><a href='post.php?titulli=".$row['titulli']."&data=".$row['data']."'>Read More</a></button></div>";
        }
    }
</code>```

答:
The problem is with your function call of strlen()

```<code>if(strlen($count > 100))
</code>```

Should be:

```<code>if(strlen($count) > 100)
</code>```

Take note of the location of the parentheses.

Body:
I want to count my text from database and if it is more than (ex. 100) characters i want to display a button Read More so when you clck it it sends me to full text here are my codes:

index.php

$sql = "SELECT * FROM posts ORDER BY `posts`.`id` DESC";
    $result = mysqli_query($conn,$sql);
    while ($row = mysqli_fetch_assoc($result)) {
        echo "

".$row['titulli']."

".$row['data']."

".$row['teksti']."

        ".$count = $row['teksti'];
         echo "<button>Read More</button>
";
        }

I added an if statment but i think i have an error writing it:
When i add this code to it, it totaly brakes my page

  while ($row = mysqli_fetch_assoc($result)) {
        echo "

".$row['titulli']."

".$row['data']."

".$row['teksti']."

        ".$count = $row['teksti'];
        if (strlen($count > 100)) {
            echo "<button>Read More</button>
";
        }
    }

Body:
The problem is with your function call of strlen()

if(strlen($count > 100))

Should be:

if(strlen($count) > 100)

Take note of the location of the parentheses.


答:
It's not entirely clear what you want, but by the looks of it, you have a list of tuples with integers in it, and you want string representations of those integers. You can do this several ways by either wrapping the integers in a str() function prior to inserting into the tuples, or by iterating the list of tuples and converting them.

```<code>new_list = [tuple(str(a) for a in b) for b in my_sublist]
</code>```

This is a list comprehension method and iterates both layers of your list and tuples, converting each item to a string. It's doing:

Convert each item in tuple a to a string str(a) for each tuple b in the list my_sublist. Since it is list comprehension you need to convert the second layer back into a tuple tuple(str(a) for a in b).

Title: Adding '' to every character of a tuple sublist

Body:
It's not entirely clear what you want, but by the looks of it, you have a list of tuples with integers in it, and you want string representations of those integers. You can do this several ways by either wrapping the integers in a str() function prior to inserting into the tuples, or by iterating the list of tuples and converting them.

new_list = [tuple(str(a) for a in b) for b in my_sublist]

This is a list comprehension method and iterates both layers of your list and tuples, converting each item to a string. It's doing:

Convert each item in tuple a to a string str(a) for each tuple b in the list my_sublist. Since it is list comprehension you need to convert the second layer back into a tuple tuple(str(a) for a in b).


问:
Dealing with Exception in Overridden Interface in Java
I have a Java interface that I am implementing (EdgeProvider from JGraphT) and which is not allowed to be null. However, I'm instantiating a generic type in an overridden method and can't figure out how to deal with either InstantiationException or IllegalAccessException in a way that I can detect and cleanly break out of the execution flow.

```<code>EdgeProvider<V, E> ep = new EdgeProvider<V, E>() {
      @Override
      public E buildEdge(V from, V to, String label, Map<String, String> attributes) {
        try {
          return eClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
          return null;
        }
      }
    };
</code>```

If I rethrow I just get a warning that I have unhandled exceptions. Any suggestions?

答: You need to add throws clause in the buildEdge method and there is no need to have the try/catch if you are not handling it like returning null and handle the exception in caller method.</p>

Body:
I have a Java interface that I am implementing (EdgeProvider from JGraphT) and which is not allowed to be null. However, I'm instantiating a generic type in an overridden method and can't figure out how to deal with either InstantiationException or IllegalAccessException in a way that I can detect and cleanly break out of the execution flow.

EdgeProvider<V, E> ep = new EdgeProvider<V, E>() {
      @Override
      public E buildEdge(V from, V to, String label, Map<String, String> attributes) {
        try {
          return eClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
          return null;
        }
      }
    };

If I rethrow I just get a warning that I have unhandled exceptions. Any suggestions?


问:
How to output results from a for loop in a right way
I am trying to output results from a for loop. It doesn't output the right way. I have pasted the results in the end of my code. It shouldn't echo out like that.

```<code>for ($i = 0; $i < count($_FILES); $i++) {
      $target_path = $_FILES[$i];

        if($i == 0 ){
        $test1 = $target_path;
        }

        if($i == 1 ){
        $test2 = $target_path;
        }

//This part should output only 2 results but it outputs something different.
        echo $test1." img 1 <br>";

        echo $test2." img 2 <br>";
    }
</code>```

It shouldn't output the following:

```<code>73c4d636e78bc7d33f90c182fc6ffaec.png img 1
img 2
73c4d636e78bc7d33f90c182fc6ffaec.png img 1
5eeb5c30fc9bba82e057953945b06eab.jpg img 2
</code>```

答:
Just do like this</p>

```<code>  $target_path_arr = array();
  for ($i = 0; $i < count($_FILES); $i++) {
    $target_path = $_FILES[$i];
    $target_path_arr[] = $target_path; // use this in future
    echo $target_path." img ". $i+1."<br>";
 }
</code>```

Body:
I am trying to output results from a for loop. It doesn't output the right way. I have pasted the results in the end of my code. It shouldn't echo out like that.

for ($i = 0; $i < count($_FILES); $i++) {
      $target_path = $_FILES[$i];

        if($i == 0 ){
        $test1 = $target_path;
        }

        if($i == 1 ){
        $test2 = $target_path;
        }

//This part should output only 2 results but it outputs something different.
        echo $test1." img 1
";

        echo $test2." img 2
";
    }

It shouldn't output the following:

73c4d636e78bc7d33f90c182fc6ffaec.png img 1
img 2
73c4d636e78bc7d33f90c182fc6ffaec.png img 1
5eeb5c30fc9bba82e057953945b06eab.jpg img 2

Body:
Just do like this

  $target_path_arr = array();
  for ($i = 0; $i < count($_FILES); $i++) {
    $target_path = $_FILES[$i];
    $target_path_arr[] = $target_path; // use this in future
    echo $target_path." img ". $i+1."<br>";
 }


问:
How do I put extra number at the end of username if duplicate
Hard to explain, and let me show an example.

If username foo already exists in MySQL I want php script will allow it but to be foo1

Then if foo1 exists too, script will generate the username will be foo2

If foo2 existed then become foo3

How to make like that?

Like Col. Shrapnel said Natural increment which seems more sensible. just like "New Folder(3)" stuff in Windows

答:
First, use a regular expression to parse out the leading alpha part of the requested username, together with any trailing numeric suffix, something like:

```<code>^([a-zA-Z_]+)(\d)*$
</code>```

The first group gives you the stem (let's assign this to a variable called UsernameStem) and the second group gives you the number (let's assign this to UsernameNumber). Beware that the user may have not entered a numeric suffix, so you need to check for this special case and assign 0 to UsernameNumber.

You can then issue a SQL statement on your users table as follows:

```<code>SELECT MAX(username) FROM users WHERE username LIKE :UsernameStem || '%'
</code>```

This will give you the existing username with the highest numeric suffix for the user's desired name.

You can again use the regex above to parse out this maximum number - this time examine the second group returned by your regex match.  You can then add 1 to this number to give the next available username.

Example: the user request "foo21".  The regex will parse out "foo" as the UsernameStem and "21" as the username number.  Assuming that you have a user in your database with the username "foo44", the SQL query will return you this username.  Applying the regex again to this username from your database will enable you to parse out the number "44".  You can then convert this to an int, add 1, then concatenate this with your original UsernameStem.  This will yield "foo45".

Good luck!

Body:
First, use a regular expression to parse out the leading alpha part of the requested username, together with any trailing numeric suffix, something like:

^([a-zA-Z_]+)(\d)*$

The first group gives you the stem (let's assign this to a variable called UsernameStem) and the second group gives you the number (let's assign this to UsernameNumber). Beware that the user may have not entered a numeric suffix, so you need to check for this special case and assign 0 to UsernameNumber.

You can then issue a SQL statement on your users table as follows:

SELECT MAX(username) FROM users WHERE username LIKE :UsernameStem || '%'

This will give you the existing username with the highest numeric suffix for the user's desired name.

You can again use the regex above to parse out this maximum number - this time examine the second group returned by your regex match.  You can then add 1 to this number to give the next available username.

Example: the user request "foo21".  The regex will parse out "foo" as the UsernameStem and "21" as the username number.  Assuming that you have a user in your database with the username "foo44", the SQL query will return you this username.  Applying the regex again to this username from your database will enable you to parse out the number "44".  You can then convert this to an int, add 1, then concatenate this with your original UsernameStem.  This will yield "foo45".

Good luck!


问:
Angular 4 : Why compiling a project with my package hosted with npm trigger a 'makeDecorator' error on compilation
I got this error since I started to code my two npm packages, and I can't find a solution for this issue. Each time I run ng serve, I have this error, and then if I just add a space character and Ctrl+S a file (to run an Angular-CLI compilation) It diseapper ! How to resolve this ?

Error :

ERROR in Error encountered resolving symbol values statically. Calling
  function 'makeDecorator', function calls are not supported. Consider
  replacing the function or lambda with a reference to an exported
  function, resolving symbol NgModule in
  D:/GitHub/angular-npm/ngx-heyl-modal/demo/node_modules/ngx-heyl-snackbar/node_modules/@angular/core/src/metadata/ng_module.d.ts, resolving symbol NgModule in
  D:/GitHub/angular-npm/ngx-heyl-modal/demo/node_modules/ngx-heyl-snackbar/node_modules/@angular/core/src/metadata.d.ts,
  resolving symbol NgModule in
  D:/GitHub/angular-npm/ngx-heyl-modal/demo/node_modules/ngx-heyl-snackbar/node_modules/@angular/core/src/core.d.ts,
  resolving symbol NgModule in
  D:/GitHub/angular-npm/ngx-heyl-modal/demo/node_modules/ngx-heyl-snackbar/node_modules/@angular/core/index.d.ts,
  resolving symbol SnackbarModule in
  D:/GitHub/angular-npm/ngx-heyl-modal/demo/node_modules/ngx-heyl-snackbar/index.ts,
  resolving symbol SnackbarModule in
  D:/GitHub/angular-npm/ngx-heyl-modal/demo/node_modules/ngx-heyl-snackbar/index.ts

my packages : (With all my sources on Git)

https://www.npmjs.com/package/ngx-heyl-modal

https://www.npmjs.com/package/ngx-heyl-snackbar

EDIT :

I tried to use npm link with a simple project : empty service, empty component (just a div in the html file, no input no functions at all) and this issue is still here. I think it's because of the NgModule, maybe I'm wrong in how I wrote it ? or my package.json ?

答:
You should not ship node_modules folder in your package.

You must keep in mind that you’re writing library for Angular project. Since project itself must have Angular core as a dependency the library should not include Angular sources in the bundles it produces. To do so you need to setup peer dependencies in package.json file.

```<code>{
  ...
  "peerDependencies": {
    "@angular/common": "^4.0.0",
    "@angular/core": "^4.0.0"
  }
  ...
}
</code>```

Simple way to create AOT compatible angular library is just to run ngc but i would advice you to follow Angular 4 package format

Here is my test library https://www.npmjs.com/package/@zuz/lib (source, peerDependencies in  package.json)

See also these links for possible solutions

https://medium.com/@trekhleb/how-to-create-aot-jit-compatible-angular-4-library-with-external-scss-html-templates-9da6e68dac6e

https://medium.com/spektrakel-blog/angular-libraries-are-fun-fece73cceb05

https://medium.com/@tinesoft/easily-create-and-publish-your-next-angular-library-with-yeoman-via-generator-ngx-library-88feb0aa63fc

Body:
You should not ship node_modules folder in your package.

You must keep in mind that you’re writing library for Angular project. Since project itself must have Angular core as a dependency the library should not include Angular sources in the bundles it produces. To do so you need to setup peer dependencies in package.json file.

{
  ...
  "peerDependencies": {
    "@angular/common": "^4.0.0",
    "@angular/core": "^4.0.0"
  }
  ...
}

Simple way to create AOT compatible angular library is just to run ngc but i would advice you to follow Angular 4 package format

Here is my test library https://www.npmjs.com/package/@zuz/lib (source, peerDependencies in  package.json)

See also these links for possible solutions

https://medium.com/@trekhleb/how-to-create-aot-jit-compatible-angular-4-library-with-external-scss-html-templates-9da6e68dac6e

https://medium.com/spektrakel-blog/angular-libraries-are-fun-fece73cceb05

https://medium.com/@tinesoft/easily-create-and-publish-your-next-angular-library-with-yeoman-via-generator-ngx-library-88feb0aa63fc


问:
Producing a batch message
Let's say there is a batch API for performing tasks List[T]. In order to do the job all the tasks needs to be pushed to kafka. There are 2 ways to do that :

1) Pushing List as a message in kafka
2) Pushing individual task T in kafka

I believe approach 1 would be better since i don't have to push the messages to kafka mutiple times for a single batch call. Can some one please tell me if there is any harm in such approach ?

答:
Option 1 is the preferred method in Kafka so long as the entire batch should always stay together. If you publish a List of records as a batch then they will be stored as a batch, they will be (optionally) compressed as a batch yielding better compression, and they will be fetched by consumers as a batch yielding fewer fetch requests.

If you send individual messages then you will have to give them a common key or they will get spread out over different partitions and possibly be sent out of order, or to different consumers of a consumer group.

Title: Producing a batch message


问:
Auto file updater in C#?
In c# i m creating a application based on Thread, that read a text file from Computer(actually remote computer) selected by user. if user makes any changes in original file then this application should display the modified file(whole). </p>

<p>Successfully its doing but, thread that I am using don't know how and where to place that it continuous read the original file from background. My application gets hangs with this code    </p>

```<code>public partial class FormFileUpdate : Form
{
    // This delegate enables asynchronous calls for setting the text property on a richTextBox control.
    delegate void UpdateTextCallback(object text);

    // This thread is used to demonstrate both thread-safe and unsafe ways to call a Windows Forms control.
    private Thread autoReadThread = null;

    public FormFileUpdate()
    {
        InitializeComponent();

        //Creating Thread
        this.autoReadThread = new Thread(new ParameterizedThreadStart(UpdateText));
    }

    private void openToolStripButton_Click(object sender, EventArgs e)
    {
        OpenFileDialog fileOpen = new OpenFileDialog();
        fileOpen.Title = "Select a text document";
        fileOpen.Filter = @"Text File|*.txt|Word Document|*.rtf|MS office Documnet|*.doc|See All files|*.*";
        fileOpen.FilterIndex = 1;
        fileOpen.RestoreDirectory = true;
        fileOpen.Multiselect = false;
        if (fileOpen.ShowDialog() == DialogResult.OK)
        {
            //Created Thread will start here
            this.autoReadThread.Start(fileOpen.FileName);
        }
    }

    private void UpdateText(object fileName)
    {
        StreamReader readerStream = null;
        while(true)
        {
            if (this.richTextBox1.InvokeRequired)
            {
                UpdateTextCallback back = new UpdateTextCallback(UpdateText);
                this.Invoke(back, new object[] { fileName });
            }
            else
            {
                try
                {
                    string fileToUpdate = (string)fileName;
                    readerStream = new StreamReader(fileToUpdate);
                    richTextBox1.Text = readerStream.ReadToEnd();
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
                finally
                {
                    if (readerStream != null)
                    {
                        readerStream.Close();
                        Thread.Sleep(100);
                    }
                }
            }
        }
    }
}
</code>```

答:
You are making the file read from the GUI thread which is a time consuming action. Only the GUI update should be done with begin invoke.

Try not to use while(true), you can use the FileSystemWatcher class to update the display only when the file changes (Take a look here).

Title: Auto file updater in C#?

Body:
In c# i m creating a application based on Thread, that read a text file from Computer(actually remote computer) selected by user. if user makes any changes in original file then this application should display the modified file(whole).

Successfully its doing but, thread that I am using don't know how and where to place that it continuous read the original file from background. My application gets hangs with this code

public partial class FormFileUpdate : Form
{
    // This delegate enables asynchronous calls for setting the text property on a richTextBox control.
    delegate void UpdateTextCallback(object text);

    // This thread is used to demonstrate both thread-safe and unsafe ways to call a Windows Forms control.
    private Thread autoReadThread = null;

    public FormFileUpdate()
    {
        InitializeComponent();

        //Creating Thread
        this.autoReadThread = new Thread(new ParameterizedThreadStart(UpdateText));
    }

    private void openToolStripButton_Click(object sender, EventArgs e)
    {
        OpenFileDialog fileOpen = new OpenFileDialog();
        fileOpen.Title = "Select a text document";
        fileOpen.Filter = @"Text File|*.txt|Word Document|*.rtf|MS office Documnet|*.doc|See All files|*.*";
        fileOpen.FilterIndex = 1;
        fileOpen.RestoreDirectory = true;
        fileOpen.Multiselect = false;
        if (fileOpen.ShowDialog() == DialogResult.OK)
        {
            //Created Thread will start here
            this.autoReadThread.Start(fileOpen.FileName);
        }
    }

    private void UpdateText(object fileName)
    {
        StreamReader readerStream = null;
        while(true)
        {
            if (this.richTextBox1.InvokeRequired)
            {
                UpdateTextCallback back = new UpdateTextCallback(UpdateText);
                this.Invoke(back, new object[] { fileName });
            }
            else
            {
                try
                {
                    string fileToUpdate = (string)fileName;
                    readerStream = new StreamReader(fileToUpdate);
                    richTextBox1.Text = readerStream.ReadToEnd();
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
                finally
                {
                    if (readerStream != null)
                    {
                        readerStream.Close();
                        Thread.Sleep(100);
                    }
                }
            }
        }
    }
}


问:
Let user force stop a loop
I am making an app that uses tkinter for interface
the interface has two buttons, one that says 'calculate' and one that says 'stop'.
the Calculate button fires a calculate() which has a recursive call to itself, which makes it either an infinite loop, or a very deep loop. I want the user to be able to be able to make the calculation stop throw the button 'stop'.</p>

```<code>def init():
    btnCalculate = Button(myframe, text="Caculate", command= Calculate, width=10)
    btnStop = Button(myframe, text="Stop", command= Stop, width=10)
    btnCalculate.place(x=0, y=0)
    btnStop.place(x=100, y=0)

def Calculate():
    Calculate(para)

def Calculate(para):
    # do some stuff
    # check condition
    if condition:
        Calculate(para)

def Stop():
    return
</code>```

答:
Recursion blocks event loops that a GUI must use to do its work. So here is a modification of what you have that uses event scheduling to do what you want. To simulate recursion, I repeatedly put a call to the Calculate method on the event stack for processing. You can change the frequency from 1000 (milliseconds) to whatever you need.</p>

```<code>from tkinter import *

stop = False

def init():
    btnCalculate = Button(myframe, text="Calculate", command=Calculate, width=10)
    btnStop = Button(myframe, text="Stop", command= Stop, width=10)
    btnCalculate.pack()
    btnStop.pack()

#def Calculate():
#    Calculate(para)

def Calculate(*args):
    global stop
    # do some stuff
    # check condition
    if not stop:
        print("Calculating...")
        root.after(1000, lambda a=args: Calculate(a))

def Stop():
    global stop
    print('Stopping')
    stop = True

root = Tk()
myframe = Frame(root)
myframe.pack()
init()
root.mainloop()
</code>```

Title: Let user force stop a loop

Body:
I am making an app that uses tkinter for interface
the interface has two buttons, one that says 'calculate' and one that says 'stop'.
the Calculate button fires a calculate() which has a recursive call to itself, which makes it either an infinite loop, or a very deep loop. I want the user to be able to be able to make the calculation stop throw the button 'stop'.

def init():
    btnCalculate = Button(myframe, text="Caculate", command= Calculate, width=10)
    btnStop = Button(myframe, text="Stop", command= Stop, width=10)
    btnCalculate.place(x=0, y=0)
    btnStop.place(x=100, y=0)

def Calculate():
    Calculate(para)

def Calculate(para):
    # do some stuff
    # check condition
    if condition:
        Calculate(para)

def Stop():
    return

Body:
Recursion blocks event loops that a GUI must use to do its work. So here is a modification of what you have that uses event scheduling to do what you want. To simulate recursion, I repeatedly put a call to the Calculate method on the event stack for processing. You can change the frequency from 1000 (milliseconds) to whatever you need.

from tkinter import *

stop = False

def init():
    btnCalculate = Button(myframe, text="Calculate", command=Calculate, width=10)
    btnStop = Button(myframe, text="Stop", command= Stop, width=10)
    btnCalculate.pack()
    btnStop.pack()

#def Calculate():
#    Calculate(para)

def Calculate(*args):
    global stop
    # do some stuff
    # check condition
    if not stop:
        print("Calculating...")
        root.after(1000, lambda a=args: Calculate(a))

def Stop():
    global stop
    print('Stopping')
    stop = True

root = Tk()
myframe = Frame(root)
myframe.pack()
init()
root.mainloop()


问:
How to display json data in ionic 3
I'm new to ionic 3 and I would like to get a JSON with my data in my ionic 3
so I was trying to follow this tutorial:
https://www.youtube.com/watch?v=vuc4dp0qHSc

Project ionic-info:

```<code>https://prnt.sc/ft60lb
</code>```

But I see no data in my console:

```<code>  https://prnt.sc/ft63rl
</code>```

My project inside editor:
https://i.stack.imgur.com/0jyPu.jpg

and here : package.json

{
  "name": "ts-test",
  "version": "0.0.1",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "lint": "ionic-app-scripts lint",
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "4.1.3",
    "@angular/compiler": "4.1.3",
    "@angular/compiler-cli": "4.1.3",
    "@angular/core": "4.1.3",
    "@angular/forms": "4.1.3",
    "@angular/http": "4.1.3",
    "@angular/platform-browser": "4.1.3",
    "@angular/platform-browser-dynamic": "4.1.3",
    "@ionic-native/core": "3.12.1",
    "@ionic-native/splash-screen": "3.12.1",
    "@ionic-native/status-bar": "3.12.1",
    "@ionic/storage": "2.0.1",
    "ionic-angular": "3.5.0",
    "ionicons": "3.0.0",
    "rxjs": "5.4.0",
    "sw-toolbox": "3.6.0",
    "zone.js": "0.8.12"
  },
  "devDependencies": {
    "@ionic/app-scripts": "1.3.12",
    "@ionic/cli-plugin-ionic-angular": "1.3.1",
    "typescript": "2.3.4"
  },
  "description": "An Ionic project"
}```
</div>
</div>
</p>

<p>and here reddit-data.ts</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

/*
  Generated class for the RedditDataProvider provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular DI.
*/
@Injectable()
export class RedditDataProvider {

  constructor(public http: Http) {
    console.log('Hello RedditDataProvider Provider');

  }
getRemoteData(){
  this.http.get('https://www.reddit.com/r/gifs/top/.json?limit=10&sort=hot').map(res=>res.json()).subscribe(data => {
    console.log(data);
  });
}

}</code>```

here : app.module.ts

import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';

import { AboutPage } from '../pages/about/about';
import { ContactPage } from '../pages/contact/contact';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { RedditDataProvider } from '../providers/reddit-data/reddit-data';
import { HttpModule } from '@angular/http';

@NgModule({
  declarations: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    TabsPage
  ],
  imports: [

    BrowserModule,
      HttpModule,
    IonicModule.forRoot(MyApp)

  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    TabsPage
  ],
  providers: [

    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    RedditDataProvider
  ]
})
export class AppModule {}```
</div>
</div>
</p>

<p>here : home.ts</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { RedditDataProvider } from '../../providers/reddit-data/reddit-data';
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController,public redditService:RedditDataProvider) {

  }
ionicViewDidLoad(){

  this.redditService.getRemoteData();

}
}</code>```

答:
Try with .subscribe in home.ts

```<code>ionicViewDidLoad(){
     this.redditService.getRemoteData().subscribe(res => {
     console.log(res);
    });
  }
</code>```

And also add provider

```<code>@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
  providers: [RedditDataProvider]
})
</code>```

reddit-data.ts you can change to

```<code>getRemoteData(){
    return this.http.get('https://www.reddit.com/r/gifs/top/.json?limit=10&sort=hot')
      .map(res => res.json());
  }
</code>```

Title: How to display json data in ionic 3

Body:
I'm new to ionic 3 and I would like to get a JSON with my data in my ionic 3
so I was trying to follow this tutorial:
https://www.youtube.com/watch?v=vuc4dp0qHSc

Project ionic-info:

https://prnt.sc/ft60lb

But I see no data in my console:

  https://prnt.sc/ft63rl

My project inside editor:
https://i.stack.imgur.com/0jyPu.jpg

and here : package.json

{
  "name": "ts-test",
  "version": "0.0.1",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "lint": "ionic-app-scripts lint",
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "4.1.3",
    "@angular/compiler": "4.1.3",
    "@angular/compiler-cli": "4.1.3",
    "@angular/core": "4.1.3",
    "@angular/forms": "4.1.3",
    "@angular/http": "4.1.3",
    "@angular/platform-browser": "4.1.3",
    "@angular/platform-browser-dynamic": "4.1.3",
    "@ionic-native/core": "3.12.1",
    "@ionic-native/splash-screen": "3.12.1",
    "@ionic-native/status-bar": "3.12.1",
    "@ionic/storage": "2.0.1",
    "ionic-angular": "3.5.0",
    "ionicons": "3.0.0",
    "rxjs": "5.4.0",
    "sw-toolbox": "3.6.0",
    "zone.js": "0.8.12"
  },
  "devDependencies": {
    "@ionic/app-scripts": "1.3.12",
    "@ionic/cli-plugin-ionic-angular": "1.3.1",
    "typescript": "2.3.4"
  },
  "description": "An Ionic project"
}

and here reddit-data.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

/*
  Generated class for the RedditDataProvider provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular DI.
*/
@Injectable()
export class RedditDataProvider {

  constructor(public http: Http) {
    console.log('Hello RedditDataProvider Provider');

  }
getRemoteData(){
  this.http.get('https://www.reddit.com/r/gifs/top/.json?limit=10&sort=hot').map(res=>res.json()).subscribe(data => {
    console.log(data);
  });
}

}

here : app.module.ts

import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';

import { AboutPage } from '../pages/about/about';
import { ContactPage } from '../pages/contact/contact';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { RedditDataProvider } from '../providers/reddit-data/reddit-data';
import { HttpModule } from '@angular/http';

@NgModule({
  declarations: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    TabsPage
  ],
  imports: [

    BrowserModule,
      HttpModule,
    IonicModule.forRoot(MyApp)

  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    TabsPage
  ],
  providers: [

    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    RedditDataProvider
  ]
})
export class AppModule {}

here : home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { RedditDataProvider } from '../../providers/reddit-data/reddit-data';
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController,public redditService:RedditDataProvider) {

  }
ionicViewDidLoad(){

  this.redditService.getRemoteData();

}
}

Body:
Try with .subscribe in home.ts

ionicViewDidLoad(){
     this.redditService.getRemoteData().subscribe(res => {
     console.log(res);
    });
  }

And also add provider

@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
  providers: [RedditDataProvider]
})

reddit-data.ts you can change to

getRemoteData(){
    return this.http.get('https://www.reddit.com/r/gifs/top/.json?limit=10&sort=hot')
      .map(res => res.json());
  }


问:
Python switch statement with aliases
How to write an efficient "switch" statement that can return same thing for different input?

Simple switch in Python can be implemented using dictionary  like this:

```<code>def switch(s):
    case = {'phone': '123 456 789', 'website': 'www.example.com'}
    return case[s]
</code>```

This one has constant access time, however I want to use aliases, i.e. switch('website') will return the same thing as switch('site') etc. without duplicating values, i.e. without using

case = {'website': 'www.example.com, 'site': 'www.example.com}

What can be used, is:

```<code>def switch(s):
    case = {('telephone', 'number', 'phone'): '123 456 789',
            ('website', 'site'): 'www.example.com'}
    for key, value in case.items():
        if s in key:
            return value
</code>```

But this approach has worse than linear access time.

It can be made constant, by using

```<code>def switch(s):
    case = ['123 456 789', 'www.example.com']
    aliases = {'telephone': 0, 'number': 0, 'phone': 0,
               'website': 1, 'site': 1}
    return case[aliases[s]]
</code>```

but then I'm sort-of duplicating values and in case I decide to remove any answer, I have to edit aliases' and/or case's return values (if I no longer want to return '123 456 789' I have to delete it from case and modify aliases so that aliases['website'] and aliases['site'] return 0 OR leave dummy value in case's 1st cell OR make case a dictionary)

Is there a better way to write such statements?

答:
You can use the linked hashmaps approach:

```<code>def switch(s):
    alias = {'telephone': 1, 'number': 1, 'phone': 1,
             'website': 2, 'site': 2}
    case = {1: '123 456 789', 2: 'www.example.com'}
    return case[alias[s]]
</code>```

That way you are keeping the O(1) lookup time.

Of course, for real data, you'll want to automate the construction of alias and case maps, but that should be rather straightforward.

Updates/deletes should also be rather simple, since they come down to simple dict update/delete.

Also, to make insertion of new values easier, you can use UUID4 (or some other random value) instead of numbers.

Title: Python switch statement with aliases

Body:
How to write an efficient "switch" statement that can return same thing for different input?

Simple switch in Python can be implemented using dictionary  like this:

def switch(s):
    case = {'phone': '123 456 789', 'website': 'www.example.com'}
    return case[s]

This one has constant access time, however I want to use aliases, i.e. switch('website') will return the same thing as switch('site') etc. without duplicating values, i.e. without using

case = {'website': 'www.example.com, 'site': 'www.example.com}

What can be used, is:

def switch(s):
    case = {('telephone', 'number', 'phone'): '123 456 789',
            ('website', 'site'): 'www.example.com'}
    for key, value in case.items():
        if s in key:
            return value

But this approach has worse than linear access time.

It can be made constant, by using

def switch(s):
    case = ['123 456 789', 'www.example.com']
    aliases = {'telephone': 0, 'number': 0, 'phone': 0,
               'website': 1, 'site': 1}
    return case[aliases[s]]

but then I'm sort-of duplicating values and in case I decide to remove any answer, I have to edit aliases' and/or case's return values (if I no longer want to return '123 456 789' I have to delete it from case and modify aliases so that aliases['website'] and aliases['site'] return 0 OR leave dummy value in case's 1st cell OR make case a dictionary)

Is there a better way to write such statements?

Body:
You can use the linked hashmaps approach:

def switch(s):
    alias = {'telephone': 1, 'number': 1, 'phone': 1,
             'website': 2, 'site': 2}
    case = {1: '123 456 789', 2: 'www.example.com'}
    return case[alias[s]]

That way you are keeping the O(1) lookup time.

Of course, for real data, you'll want to automate the construction of alias and case maps, but that should be rather straightforward.

Updates/deletes should also be rather simple, since they come down to simple dict update/delete.

Also, to make insertion of new values easier, you can use UUID4 (or some other random value) instead of numbers.