问:
Python, MQTT broker, publish message
I have configured MQTT Broker, receiving published messages from another piece of code (not written or accessible by me). I added another topic to the broker configuration and am now trying to publish data to this new topic from a piece of python code. I get the feedback that the message is published by the callback function, but no actual data is received.

Is there anything I am missing?

I am using the following code:

```<code>import paho.mqtt.client as mqtt
import time

#=========================================================================
def on_connect(client, userdata, flags, rc) :
    print "on_connect()"

#=========================================================================
def on_publish(client, userdata, mid) :
    print "on_publish()"

#=========================================================================
def send() :
    mqttc = mqtt.Client()
    mqttc.on_connect = on_connect
    mqttc.on_publish = on_publish

    #host      = "localhost"
    host      = "127.0.0.1"
    port      = 1883
    keepalive = 60

    print "\nConnect to '%s', port '%s', keepalive '%s'" % (host, port, keepalive)
    mqttc.connect(host=host, port=port, keepalive=keepalive)

    time.sleep(3)
    mqttc.loop_start()
    time.sleep(3)

    topic = "data/MY/TOPIC"
    msg = "MY_MESSAGE"

    print "Publish to '%s' msg '%s'" % (topic, msg)
    mqttc.publish(topic, msg, qos=2)

    time.sleep(3)
    mqttc.loop_stop()
# end send()

#=========================================================================
if __name__ == "__main__":
    send()
# end if
</code>```

Getting the stdout

```<code>Connect to '127.0.0.1', port '1883', keepalive '60'
on_connect()
Publish to 'data/MY/TOPIC' msg 'MY MESSAGE'
on_publish()
</code>```

I am not sure if the loop() functions are necessary, but if I do not embed the publishing in the loop_start() and loop_stop(), I do not get a on_connect callback.

答:
The loop functions are necessary as these are where all the network traffic is processed.

Manually setting up a connection to the broker to just send a single message like this is not a good idea, it would be better to start the client, leave it running (by calling loop_start() and not calling loop_stop()) in the background and then just call the publish method on the mqttc client object.

If you don't want to keep a instance of the client running then you should use the single message publish helper method provided by the paho python library (https://pypi.python.org/pypi/paho-mqtt/1.1#single):

```<code>import paho.mqtt.publish as publish

publish.single("paho/test/single", "payload", hostname="iot.eclipse.org")
</code>```

Title: Python, MQTT broker, publish message

Body:
I have configured MQTT Broker, receiving published messages from another piece of code (not written or accessible by me). I added another topic to the broker configuration and am now trying to publish data to this new topic from a piece of python code. I get the feedback that the message is published by the callback function, but no actual data is received.

Is there anything I am missing?

I am using the following code:

import paho.mqtt.client as mqtt
import time

#=========================================================================
def on_connect(client, userdata, flags, rc) :
    print "on_connect()"

#=========================================================================
def on_publish(client, userdata, mid) :
    print "on_publish()"

#=========================================================================
def send() :
    mqttc = mqtt.Client()
    mqttc.on_connect = on_connect
    mqttc.on_publish = on_publish

    #host      = "localhost"
    host      = "127.0.0.1"
    port      = 1883
    keepalive = 60

    print "\nConnect to '%s', port '%s', keepalive '%s'" % (host, port, keepalive)
    mqttc.connect(host=host, port=port, keepalive=keepalive)

    time.sleep(3)
    mqttc.loop_start()
    time.sleep(3)

    topic = "data/MY/TOPIC"
    msg = "MY_MESSAGE"

    print "Publish to '%s' msg '%s'" % (topic, msg)
    mqttc.publish(topic, msg, qos=2)

    time.sleep(3)
    mqttc.loop_stop()
# end send()

#=========================================================================
if __name__ == "__main__":
    send()
# end if

Getting the stdout

Connect to '127.0.0.1', port '1883', keepalive '60'
on_connect()
Publish to 'data/MY/TOPIC' msg 'MY MESSAGE'
on_publish()

I am not sure if the loop() functions are necessary, but if I do not embed the publishing in the loop_start() and loop_stop(), I do not get a on_connect callback.

Body:
The loop functions are necessary as these are where all the network traffic is processed.

Manually setting up a connection to the broker to just send a single message like this is not a good idea, it would be better to start the client, leave it running (by calling loop_start() and not calling loop_stop()) in the background and then just call the publish method on the mqttc client object.

If you don't want to keep a instance of the client running then you should use the single message publish helper method provided by the paho python library (https://pypi.python.org/pypi/paho-mqtt/1.1#single):

import paho.mqtt.publish as publish

publish.single("paho/test/single", "payload", hostname="iot.eclipse.org")


来源: stackexchange

问:
Python, gettext: How to get right locale for module- and class-level variables?
I have some troubles when i use gettext for module- and class-level variables.

First of all, at import time i use my default locale and install it.
After it I get specific locale when I start my project by parsing settings and use gettext.translation.install for set right locale. All work well, but in my code all module- and class-level variables stay translated with default locale, not right.

For example I have project like this:

```<code>├── foo.py
├── i18t
│   └── __init__.py
├── __init__.py
└── run.py
</code>```

i18t/__init__.py contains:

```<code>import gettext
from os import path

SUPPORTED_LANGUAGES = ('en', 'fr')
DEFAULT_LANGUAGE = SUPPORTED_LANGUAGES[0]

locale_path = path.abspath(path.join(path.dirname(__file__), 'locale'))

TRANSLATIONS = {
    lang: gettext.translation(
        'domain',
        locale_path,
        languages=[lang]
    ) for lang in SUPPORTED_LANGUAGES
}

def install_language(language):
    lang = TRANSLATIONS.get(language)
    if lang is None:
        lang = TRANSLATIONS[DEFAULT_LANGUAGE]
    lang.install()
</code>```

__init__.py:

```<code>from i18n import DEFAULT_LANGUAGE, install_language

install_language(DEFAULT_LANGUAGE)
</code>```

foo.py:

```<code>foo = _('Bar')
</code>```

run.py:

```<code>from i18t import install_language
import foo

def main():
    ...
    read config and get right locale
    ...
    install_language(right_locale)
    bar = _('Bazz')
    print(foo.foo)
    print(bar)
</code>```

I execute run.py and I get translated foo.foo with default locale and bar with right locale.
I know that foo.foo run _(gettext) only once when I import module but I need to get right translated string.
Which better way to do it?

答:
Problem of this case is desire to use run-time function gettext for strings which evaluated only once in import-time. I think it's better not to do this.

But I resolved this problem with using string-like object like in speaklater package or inherit object UserSting and make your own gettext function:

```<code>from collections import UserString

class RuntimeTranslatedString(UserString):

    def __init__(self, message):
        self._data = message

    @property
    def data(self):
        return _(self._data)

def N_(message):
    return RuntimeTranslatedString(message)
</code>```

In your code you can use it like _(gettext):

```<code>from .i18n import N_

foo = N_('Bar')
</code>```

Don't forget add it to your extract_message command. In my setup.cfg it looks like:

```<code>[extract_messages]
output_file = my-package/i18n/locale/translation.pot
keywords = _ N_
</code>```

I'm not sure that this is the good solution but it works.

ContentLicense: CC BY-SA 3.0

Body:
I have some troubles when i use gettext for module- and class-level variables.

First of all, at import time i use my default locale and install it.
After it I get specific locale when I start my project by parsing settings and use gettext.translation.install for set right locale. All work well, but in my code all module- and class-level variables stay translated with default locale, not right.

For example I have project like this:

├── foo.py
├── i18t
│   └── __init__.py
├── __init__.py
└── run.py

i18t/__init__.py contains:

import gettext
from os import path

SUPPORTED_LANGUAGES = ('en', 'fr')
DEFAULT_LANGUAGE = SUPPORTED_LANGUAGES[0]

locale_path = path.abspath(path.join(path.dirname(__file__), 'locale'))

TRANSLATIONS = {
    lang: gettext.translation(
        'domain',
        locale_path,
        languages=[lang]
    ) for lang in SUPPORTED_LANGUAGES
}

def install_language(language):
    lang = TRANSLATIONS.get(language)
    if lang is None:
        lang = TRANSLATIONS[DEFAULT_LANGUAGE]
    lang.install()

__init__.py:

from i18n import DEFAULT_LANGUAGE, install_language

install_language(DEFAULT_LANGUAGE)

foo.py:

foo = _('Bar')

run.py:

from i18t import install_language
import foo

def main():
    ...
    read config and get right locale
    ...
    install_language(right_locale)
    bar = _('Bazz')
    print(foo.foo)
    print(bar)

I execute run.py and I get translated foo.foo with default locale and bar with right locale.
I know that foo.foo run _(gettext) only once when I import module but I need to get right translated string.
Which better way to do it?

Body:
Problem of this case is desire to use run-time function gettext for strings which evaluated only once in import-time. I think it's better not to do this.

But I resolved this problem with using string-like object like in speaklater package or inherit object UserSting and make your own gettext function:

from collections import UserString

class RuntimeTranslatedString(UserString):

    def __init__(self, message):
        self._data = message

    @property
    def data(self):
        return _(self._data)

def N_(message):
    return RuntimeTranslatedString(message)

In your code you can use it like _(gettext):

from .i18n import N_

foo = N_('Bar')

Don't forget add it to your extract_message command. In my setup.cfg it looks like:

[extract_messages]
output_file = my-package/i18n/locale/translation.pot
keywords = _ N_

I'm not sure that this is the good solution but it works.


问:
FCM Push Notification: MismatchSenderId
Good day,

I am trying to use this URL from FCM to send messages:

https://fcm.googleapis.com/fcm/send

With a header of

```<code>    Authorization value of **key:*Key from Firebase Console***
    Content-Type: **application/json**
</code>```

The body consist of this:

```<code>    {
       "to" : "MyKey generated",
       "notification" : {
       "body" : "Hey",
       "title" : "Hey"
    }
 }
</code>```

But the result i always received is this:

```<code>     {
        "multicast_id": 7942550122547405787,
        "success": 0,
        "failure": 1,
        "canonical_ids": 0,
        "results": [
            {
               "error": "MismatchSenderId"
           }
      ]
    }
</code>```

The server key I got is from here:

Server Key

My URL reference is the docs in FCM server.

I am testing this in Postman. Did I miss something? Thanks

答:
According to the docs

A registration token is tied to a certain group of senders. When a client app registers for FCM, it must specify which senders are allowed to send messages. You should use one of those sender IDs when sending messages to the client app. If you switch to a different sender, the existing registration tokens won't work.

So it sounds like you are trying to send a push notification to an ID that is not associated with the sender ID. You should verify that you have the correct keys in the correct places

Title: FCM Push Notification: MismatchSenderId

Body:
Good day,

I am trying to use this URL from FCM to send messages:

https://fcm.googleapis.com/fcm/send

With a header of

    Authorization value of **key:*Key from Firebase Console***
    Content-Type: **application/json**

The body consist of this:

    {
       "to" : "MyKey generated",
       "notification" : {
       "body" : "Hey",
       "title" : "Hey"
    }
 }

But the result i always received is this:

     {
        "multicast_id": 7942550122547405787,
        "success": 0,
        "failure": 1,
        "canonical_ids": 0,
        "results": [
            {
               "error": "MismatchSenderId"
           }
      ]
    }

The server key I got is from here:

Server Key

My URL reference is the docs in FCM server.

I am testing this in Postman. Did I miss something? Thanks


问:
Secure access to part of properties
In my application I have two roles (admin and normal). In model I have class (example):

```<code>public class Foo
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }

    public string Extra { get; set; }
}
</code>```

Users can also edit that objects and use filters to search. Application is based on WebAPI ASP.NET Core with EF Core.

There is a requirement that normal should not see (or do anything with it) Extra property. Should I protect the data everywhere in application ( services, controllers, data access layer) by splitting model class (or something else) or just format output of endpoints by ignoring properties?

One of my ideas is to create an attribute, put it on Extra property and then, using ContractResolver ignoring properties with that attribute when user is not eligible to see that property. Also modify EF change tracker to ignore saving that property (in same cases).

Is there any pattern or strategy how to handle with that problem?

答:
There's no built-in mechanism for this, no, because it's far too granular. Also, trying to enforce this at the EF level would mean leaking your HttpContext into your DAL, which is a bad idea for a number of reasons.

My best recommendation would be to model it with inheritance. In other words, create something like:

```<code>public class Foo
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }
}

public class ExtraFoo : Foo
{
    public string Extra { get; set; }
}
</code>```

By default, Entity Framework will implement this via single-table inheritance, so your backing table will look pretty much exactly the same. However, this then gives you the ability to work with one or the other separately.

Then, I would recommend employing completely separate controllers and/or actions for working with each type. This allows you employ different authorization for each, ensuring that "normal" users will only ever be able to work with Foo (rather than ExtraFoo). To negate the obvious duplication this would imply, you can employ a base controller utilizing generics that each type-specific controller could then inherit from:

```<code>public class BaseFooController<TFoo> : Controller
    where TFoo : Foo, new()
{
    // all your actions here, utilizing generic type, e.g.:

    [HttpPost]
    public ActionResult Create(TFoo foo)
    {
        ...
    }
}

[Authorize(Roles = "normal")]
public class FooController : BaseFooController<Foo>
{
}

[Authorize(Roles = "admin")]
public class ExtraFooController : BaseFooController<ExtraFoo>
{
}
</code>```

Title: Secure access to part of properties

Body:
In my application I have two roles (admin and normal). In model I have class (example):

public class Foo
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }

    public string Extra { get; set; }
}

Users can also edit that objects and use filters to search. Application is based on WebAPI ASP.NET Core with EF Core.

There is a requirement that normal should not see (or do anything with it) Extra property. Should I protect the data everywhere in application ( services, controllers, data access layer) by splitting model class (or something else) or just format output of endpoints by ignoring properties?

One of my ideas is to create an attribute, put it on Extra property and then, using ContractResolver ignoring properties with that attribute when user is not eligible to see that property. Also modify EF change tracker to ignore saving that property (in same cases).

Is there any pattern or strategy how to handle with that problem?

Body:
There's no built-in mechanism for this, no, because it's far too granular. Also, trying to enforce this at the EF level would mean leaking your HttpContext into your DAL, which is a bad idea for a number of reasons.

My best recommendation would be to model it with inheritance. In other words, create something like:

public class Foo
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }
}

public class ExtraFoo : Foo
{
    public string Extra { get; set; }
}

By default, Entity Framework will implement this via single-table inheritance, so your backing table will look pretty much exactly the same. However, this then gives you the ability to work with one or the other separately.

Then, I would recommend employing completely separate controllers and/or actions for working with each type. This allows you employ different authorization for each, ensuring that "normal" users will only ever be able to work with Foo (rather than ExtraFoo). To negate the obvious duplication this would imply, you can employ a base controller utilizing generics that each type-specific controller could then inherit from:

public class BaseFooController<TFoo> : Controller
    where TFoo : Foo, new()
{
    // all your actions here, utilizing generic type, e.g.:

    [HttpPost]
    public ActionResult Create(TFoo foo)
    {
        ...
    }
}

[Authorize(Roles = "normal")]
public class FooController : BaseFooController<Foo>
{
}

[Authorize(Roles = "admin")]
public class ExtraFooController : BaseFooController<ExtraFoo>
{
}


问:
Remove some part of URL using javascript
I have a URL which will be something like below

```<code>http://localhost:22306/NESSPATH/VSAT/I-HP-AAMB-ENB-0003_C1//Panaromic//120.jpg
</code>```

I want URL which will be something like this

```<code>NESSPATH/VSAT/I-HP-AAMB-ENB-0003_C1//Panaromic//120.jpg
</code>```

Here is what I get in variable

```<code>VSATSaving.PANAROMIC_120 = document.getElementById('ImgPanaromic120').src;
</code>```

how to get that using javascript. Tried with lastIndexOf but it is not working

答:
var a = document.createElement('a');
a.href = 'http://localhost:22306/NESSPATH/VSAT/I-HP-AAMB-ENB-0003_C1//Panaromic//120.jpg';
console.log(a.pathname);```

Body:
I have a URL which will be something like below

http://localhost:22306/NESSPATH/VSAT/I-HP-AAMB-ENB-0003_C1//Panaromic//120.jpg

I want URL which will be something like this

NESSPATH/VSAT/I-HP-AAMB-ENB-0003_C1//Panaromic//120.jpg

Here is what I get in variable

VSATSaving.PANAROMIC_120 = document.getElementById('ImgPanaromic120').src;

how to get that using javascript. Tried with lastIndexOf but it is not working


问:
How do I get a textbox with particular ValidationGroup in jQuery?
I have an ASP.NET TextBox ID="txtDate" in my usercontrol. It has ValidationGroup="MyUC" set. Now my UC is inside a Repeater Control. So there will be multiple instances of the same textbox.
I am able to get all textboxes like: $("[id$='_txtDate']");

Each of the txtDate will have a separate ValidationGroup assigned to it, dynamically.
So I want to get a textbox based on the id + ValidationGroup using jQuery / javascript.

How can it be done? Any guidance really appreciated.

Edited based on Josiah's Reply and the way I found:

Sorry, my scenario is kind of complicated to include entire code. In short the textboxes are attached to jquery datepicker and the code below runs when a date is selected. The same handler is attached to multiple textboxes. Here is what I have:

```<code>var valgrp="MyGroup"; /*this mygroup is dynamic but keeping static for e.g.*/
var txtdate1 = $("[id$='txtDate']").filter(function(){if(this.Validators!=null){return this.Validators[0].validationGroup == valgrp;}});
var txtdate2 = $("[id$='txtDate']").filter(function(){return this.validationGroup == valgrp;});
alert("date1- " + txtdate1.val()); /*this returns date selected from datepicker*/
alert("date2 " + txtdate2.val()); /*this returns empty*/
</code>```

Depending on the date I want to do something else. So txtdate1 is currently working for me where I don't have to add class to my textbox. I was playing with the txtdate2 which isn't behaving how I was expecting and so I had to post this question.

Here is a sample test to see this.validationGroup not returned:

```<code> $(function () {
            $("#btntest").click(function () {
                $("[id$='txtDate']").each(function () {
                    alert(this.validationGroup);//returns undefined
                    alert(this.Validators[0].validationGroup); //returns "test"
                });
            });
        });
  <input id="btntest" type="button" value="button" />
  <asp:TextBox ID="txtDate" runat="server" ValidationGroup="test"></asp:TextBox>
   <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Text="*" ErrorMessage="Required." ControlToValidate="txtDate" ValidationGroup="test"></asp:RequiredFieldValidator>
</code>```

答:
While Josiah's solution didn't work but his idea of attaching class to textbox could have been a potential solution. Since it didn't exactly fit my needs I would answer my own question. Here is the solution I came up with:

```<code>var valgrp="MyGroup"; /*this mygroup is dynamic but keeping static for e.g.*/
var txtdate1 = $("[id$='txtDate']").filter(function(){if(this.Validators!=null){return this.Validators[0].validationGroup == valgrp;}});
</code>```

The above returns me the textbox I am looking for. The key is

this.Validators[0].validationGroup

It gets the validationGroup of the first validator control attached to the textbox (this).

ContentLicense: CC BY-SA 2.5

Body:
I have an ASP.NET TextBox ID="txtDate" in my usercontrol. It has ValidationGroup="MyUC" set. Now my UC is inside a Repeater Control. So there will be multiple instances of the same textbox.
I am able to get all textboxes like: $("[id$='_txtDate']");

Each of the txtDate will have a separate ValidationGroup assigned to it, dynamically.
So I want to get a textbox based on the id + ValidationGroup using jQuery / javascript.

How can it be done? Any guidance really appreciated.

Edited based on Josiah's Reply and the way I found:

Sorry, my scenario is kind of complicated to include entire code. In short the textboxes are attached to jquery datepicker and the code below runs when a date is selected. The same handler is attached to multiple textboxes. Here is what I have:

var valgrp="MyGroup"; /*this mygroup is dynamic but keeping static for e.g.*/
var txtdate1 = $("[id$='txtDate']").filter(function(){if(this.Validators!=null){return this.Validators[0].validationGroup == valgrp;}});
var txtdate2 = $("[id$='txtDate']").filter(function(){return this.validationGroup == valgrp;});
alert("date1- " + txtdate1.val()); /*this returns date selected from datepicker*/
alert("date2 " + txtdate2.val()); /*this returns empty*/

Depending on the date I want to do something else. So txtdate1 is currently working for me where I don't have to add class to my textbox. I was playing with the txtdate2 which isn't behaving how I was expecting and so I had to post this question.

Here is a sample test to see this.validationGroup not returned:

 $(function () {
            $("#btntest").click(function () {
                $("[id$='txtDate']").each(function () {
                    alert(this.validationGroup);//returns undefined
                    alert(this.Validators[0].validationGroup); //returns "test"
                });
            });
        });
  <input id="btntest" type="button" value="button" />
  <asp:TextBox ID="txtDate" runat="server" ValidationGroup="test"></asp:TextBox>
   <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Text="*" ErrorMessage="Required." ControlToValidate="txtDate" ValidationGroup="test"></asp:RequiredFieldValidator>

Body:
While Josiah's solution didn't work but his idea of attaching class to textbox could have been a potential solution. Since it didn't exactly fit my needs I would answer my own question. Here is the solution I came up with:

var valgrp="MyGroup"; /*this mygroup is dynamic but keeping static for e.g.*/
var txtdate1 = $("[id$='txtDate']").filter(function(){if(this.Validators!=null){return this.Validators[0].validationGroup == valgrp;}});

The above returns me the textbox I am looking for. The key is

this.Validators[0].validationGroup

It gets the validationGroup of the first validator control attached to the textbox (this).


答:
the header must be like this

```<code>Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
</code>```

to check the validity of a server key

```<code>api_key=YOUR_SERVER_KEY

curl --header "Authorization: key=$api_key" \
       --header Content-Type:"application/json" \
       https://fcm.googleapis.com/fcm/send \
       -d "{\"registration_ids\":[\"ABC\"]}"
</code>```

if everything is ok so you need to recheck the senderId

Title: FCM Push Notification: MismatchSenderId

Body:
the header must be like this

Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

to check the validity of a server key

api_key=YOUR_SERVER_KEY

curl --header "Authorization: key=$api_key" \
       --header Content-Type:"application/json" \
       https://fcm.googleapis.com/fcm/send \
       -d "{\"registration_ids\":[\"ABC\"]}"

if everything is ok so you need to recheck the senderId


问:
ParseObject.remove not working in Back4App
I am triying to delete a field of an object in Back4App, but I cannot achieve such a simple operation. By "deleting" I mean set a field that has data to "undefined".
According to the guide, I just have to call myObject.remove("field"). I tryed that (with correct field name), then save the object (I tried all of the saving functions available), but the object is unmodified. There is no error thrown.

I can change the field (with put ("field", otherObject), because it is a pointer field) with no problem. But put("field", JSONObject.NULL) is not working either.

I do not know if this code would work in the original Parse, I am coding this now. The equivalent function in iOS ([myObject removeObjectForKey:@"field"];) in the same database is working nicely...

答:
For what I could gather from your question, the problem is that you're trying to clean a field from a relational object:

"I can change the field (with put ("field", otherObject), because it is
  a pointer field)"

On that case, I'm not really sure if using simple object deletion would work. I'd suggest you to take a look at Parse's documentation on Relational Data in order to understand how you should remove that field.

Long story short, I'm not sure if the idea of cleaning the field that you wish will work, but what can be done when you have a relation like this:

```<code>ParseUser user = ParseUser.getCurrentUser();
ParseRelation<ParseObject> relation = user.getRelation("field");
relation.add(MyObject);
user.saveInBackground();
</code>```

Is to simply remove the relation like this:

```<code>relation.remove(MyObject);
</code>```

As you can check in the link above.

Body:
For what I could gather from your question, the problem is that you're trying to clean a field from a relational object:

"I can change the field (with put ("field", otherObject), because it is
  a pointer field)"

On that case, I'm not really sure if using simple object deletion would work. I'd suggest you to take a look at Parse's documentation on Relational Data in order to understand how you should remove that field.

Long story short, I'm not sure if the idea of cleaning the field that you wish will work, but what can be done when you have a relation like this:

ParseUser user = ParseUser.getCurrentUser();
ParseRelation<ParseObject> relation = user.getRelation("field");
relation.add(MyObject);
user.saveInBackground();

Is to simply remove the relation like this:

relation.remove(MyObject);

As you can check in the link above.


问:
Session timeout is not working in JSF 2.0
I am new to JSF 2.0 / PrimeFaces and I've created one webapp using JSF 2.0 + Spring 4. For session timeout, I've done below mapping in web.xml :

```<code><session-config>
    <session-timeout>1</session-timeout>
</session-config>

<error-page>
    <exception-type>javax.faces.application.ViewExpiredException</exception-type>
    <location>/resources/login/timeout.xhtml</location>
</error-page>
</code>```

After login, user redirects to admin.xhtml in which there element as

```<code><h:link value="showAnotherPage" outcome="other.xhtml"/>
</code>```

But after 2 or 5 minutes, when I click on the link, it redirects me to other.xhtml page not on timeout page.

Is anything that I'm missing to configure? Please help.

答:
I'd personally implement it in another way.

Define an Exception handler factory in your faces-config.xml as follows:

```<code><factory>
    <exception-handler-factory>
        com.package.faces.FullAjaxExceptionHandlerFactory
    </exception-handler-factory>
</factory>
</code>```

Create the exception handler factory that extends javax.faces.context.ExceptionHandlerFactory. It should return your own implementation of the ExceptionHandler. This could be an example:

```<code>import javax.faces.context.ExceptionHandler;
import javax.faces.context.ExceptionHandlerFactory;

public class FullAjaxExceptionHandlerFactory extends ExceptionHandlerFactory {

    private ExceptionHandlerFactory wrapped;

    /**
     * Construct a new full ajax exception handler factory around the given wrapped factory.
     * @param wrapped The wrapped factory.
     */
    public FullAjaxExceptionHandlerFactory(ExceptionHandlerFactory wrapped) {
            this.wrapped = wrapped;
    }

    /**
     * Returns a new instance of {@link FullAjaxExceptionHandler} which wraps the original exception handler.
     */
    @Override
    public ExceptionHandler getExceptionHandler() {
            return new FullAjaxExceptionHandler(wrapped.getExceptionHandler());
    }

    /**
     * Returns the wrapped factory.
     */
    @Override
    public ExceptionHandlerFactory getWrapped() {
            return wrapped;
    }

}
</code>```

In the end, extend the javax.faces.context.ExceptionHandlerWrapper to handle all exceptions. An example is the following:

```<code>public class FullAjaxExceptionHandler extends ExceptionHandlerWrapper {

    private ExceptionHandler wrapped;

    public FullAjaxExceptionHandler(ExceptionHandler wrapped) {
        this.wrapped = wrapped;
    }

    private static Throwable extractCustomException(Throwable ex) {
        Throwable t = ex;
        while (t != null) {
            if (t instanceof YourOwnExceptionInterface) {
                return t;
            }
            t = t.getCause();
        }
        return ex;
    }

    private static String extractMessage(Throwable t) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        t.printStackTrace(pw);

        return matchJmillErrorTag(sw.toString());
    }

    public static boolean handleException(Throwable original) {
        Throwable ex = extractCustomException(original);

        if (ex instanceof ViewExpiredException) {
            // redirect to login page
            return false;
        } else if (ex instanceof YourOwnExceptionInterface) {
            ((YourOwnExceptionInterface) ex).handle();
            return true;
        } else if (ex instanceof NonexistentConversationException) {
            FacesContext.getCurrentInstance().getExternalContext().invalidateSession();

            // redirect to login page

            return false;
        } else {
            String message = extractMessage(ex);
            final FacesContext fc = FacesContext.getCurrentInstance();
            original.printStackTrace();

            // redirect to error page

            fc.responseComplete();
            return true;
        }
    }

    @Override
    public void handle() throws FacesException {
        final Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator();
        FacesContext facesContext = FacesContext.getCurrentInstance();
        if (Redirector.isRedirectingToLogin(facesContext)) {
            return;
        }
        while (i.hasNext()) {
            ExceptionQueuedEvent event = i.next();
            ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();
            i.remove();
            if (!handleException(context.getException())) {
                return;
            }
        }
        getWrapped().handle();
    }

    @Override
    public ExceptionHandler getWrapped() {
        return wrapped;
    }

}
</code>```

Check the public static boolean handleException(Throwable original) in the previous class. You could use that to manage all your exceptions.

At one point I put a condition there about YourOwnExceptionInterface which is an interface with a handle() method that I'd implement for example by a NotAuthorizedException kind of exception. In this case in the handle() method of the NotAuthorizedException I'd notify the user that he can't complete a certain operation through a p:growl component for example. I'd use this in my beans as throw new NotAuthorizedException("message");

The custom exception class should of course extend the RuntimeException.

Body:
I am new to JSF 2.0 / PrimeFaces and I've created one webapp using JSF 2.0 + Spring 4. For session timeout, I've done below mapping in web.xml :

<session-config>
    <session-timeout>1</session-timeout>
</session-config>

<error-page>
    <exception-type>javax.faces.application.ViewExpiredException</exception-type>
    <location>/resources/login/timeout.xhtml</location>
</error-page>

After login, user redirects to admin.xhtml in which there element as

<h:link value="showAnotherPage" outcome="other.xhtml"/>

But after 2 or 5 minutes, when I click on the link, it redirects me to other.xhtml page not on timeout page.

Is anything that I'm missing to configure? Please help.

Body:
I'd personally implement it in another way.

Define an Exception handler factory in your faces-config.xml as follows:

<factory>
    <exception-handler-factory>
        com.package.faces.FullAjaxExceptionHandlerFactory
    </exception-handler-factory>
</factory>

Create the exception handler factory that extends javax.faces.context.ExceptionHandlerFactory. It should return your own implementation of the ExceptionHandler. This could be an example:

import javax.faces.context.ExceptionHandler;
import javax.faces.context.ExceptionHandlerFactory;

public class FullAjaxExceptionHandlerFactory extends ExceptionHandlerFactory {

    private ExceptionHandlerFactory wrapped;

    /**
     * Construct a new full ajax exception handler factory around the given wrapped factory.
     * @param wrapped The wrapped factory.
     */
    public FullAjaxExceptionHandlerFactory(ExceptionHandlerFactory wrapped) {
            this.wrapped = wrapped;
    }

    /**
     * Returns a new instance of {@link FullAjaxExceptionHandler} which wraps the original exception handler.
     */
    @Override
    public ExceptionHandler getExceptionHandler() {
            return new FullAjaxExceptionHandler(wrapped.getExceptionHandler());
    }

    /**
     * Returns the wrapped factory.
     */
    @Override
    public ExceptionHandlerFactory getWrapped() {
            return wrapped;
    }

}

In the end, extend the javax.faces.context.ExceptionHandlerWrapper to handle all exceptions. An example is the following:

public class FullAjaxExceptionHandler extends ExceptionHandlerWrapper {

    private ExceptionHandler wrapped;

    public FullAjaxExceptionHandler(ExceptionHandler wrapped) {
        this.wrapped = wrapped;
    }

    private static Throwable extractCustomException(Throwable ex) {
        Throwable t = ex;
        while (t != null) {
            if (t instanceof YourOwnExceptionInterface) {
                return t;
            }
            t = t.getCause();
        }
        return ex;
    }

    private static String extractMessage(Throwable t) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        t.printStackTrace(pw);

        return matchJmillErrorTag(sw.toString());
    }

    public static boolean handleException(Throwable original) {
        Throwable ex = extractCustomException(original);

        if (ex instanceof ViewExpiredException) {
            // redirect to login page
            return false;
        } else if (ex instanceof YourOwnExceptionInterface) {
            ((YourOwnExceptionInterface) ex).handle();
            return true;
        } else if (ex instanceof NonexistentConversationException) {
            FacesContext.getCurrentInstance().getExternalContext().invalidateSession();

            // redirect to login page

            return false;
        } else {
            String message = extractMessage(ex);
            final FacesContext fc = FacesContext.getCurrentInstance();
            original.printStackTrace();

            // redirect to error page

            fc.responseComplete();
            return true;
        }
    }

    @Override
    public void handle() throws FacesException {
        final Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator();
        FacesContext facesContext = FacesContext.getCurrentInstance();
        if (Redirector.isRedirectingToLogin(facesContext)) {
            return;
        }
        while (i.hasNext()) {
            ExceptionQueuedEvent event = i.next();
            ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();
            i.remove();
            if (!handleException(context.getException())) {
                return;
            }
        }
        getWrapped().handle();
    }

    @Override
    public ExceptionHandler getWrapped() {
        return wrapped;
    }

}

Check the public static boolean handleException(Throwable original) in the previous class. You could use that to manage all your exceptions.

At one point I put a condition there about YourOwnExceptionInterface which is an interface with a handle() method that I'd implement for example by a NotAuthorizedException kind of exception. In this case in the handle() method of the NotAuthorizedException I'd notify the user that he can't complete a certain operation through a p:growl component for example. I'd use this in my beans as throw new NotAuthorizedException("message");

The custom exception class should of course extend the RuntimeException.


问:
Doctrine 2 - Indirect one to many association
After a lot of searching for indirect associations, I only came up with this question. What I'd like to know is the exact opposite of that question, so I'm building up on it. Given the same entities:

```<code>class Continent {
    /**
    * @ORM\Id
    * @ORM\Column(type="integer", name="id")
    * @ORM\GeneratedValue(strategy="IDENTITY")
    */
    private $id;

    /**
    * @ORM\OneToMany(targetEntity="AppBundle\Entity\Country", mappedBy="continent")
    */
    private $countries;
}

class Country {
    /**
    * @ORM\Id
    * @ORM\Column(type="integer", name="id")
    * @ORM\GeneratedValue(strategy="IDENTITY")
    */
    private $id;

    /**
    * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Continent", inversedBy="countries")
    * @ORM\JoinColumn(name="continent_id", referencedColumnName="id")
    */
    private $continent;

    /**
    * @ORM\OneToMany(targetEntity="AppBundle\Entity\City", mappedBy="country")
    */
    private $cities;
}

class City {
    /**
    * @ORM\Id
    * @ORM\Column(type="integer", name="id")
    * @ORM\GeneratedValue(strategy="IDENTITY")
    */
    private $id;

    /**
    * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Country", inversedBy="cities")
    * @ORM\JoinColumn(name="country_id", referencedColumnName="id")
    */
    private $country;
}
</code>```

Is there any way to have a collection of all cities in a continent, without having to build a custom query every time, with a field in the same fashion as the countries collection, possibly via annotations or maybe dynamic mapping?

The only way I could think of is by overriding the find... methods in the Repository - which I'm not sure how exactly I could achieve adding the field - and then either looping over the countries and adding their cities to a new collection, or using a custom query entirely.

答:
First a comment about your mapping. Your mapping is wrong here:

inversedBy="countries" not inversedBy="country" and probably you want a column named continent_id instead of continentt_id

```<code>/**
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Continent", inversedBy="countries")
 * @ORM\JoinColumn(name="continent_id", referencedColumnName="id")
 */
 private $continent;
</code>```

And here it should be inversedBy="cities" not inversedBy="city":

```<code>/**
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Country", inversedBy="cities")
 * @ORM\JoinColumn(name="country_id", referencedColumnName="id")
 */
 private $country;
</code>```

Consider using validation for your entity model, the validation tool that ships with doctrine ORM will help you to get these things correct.

You can get such a result set by inner joining the countries with a certain continent.

Inside your CityRepository:

```<code>use Doctrine\ORM\Query\Expr\Join;

//...

public function findCitiesByContinent($params){
    $queryBuilder = $this->createQueryBuilder('c')
        ->innerJoin('c.country', 'cc', Join::WITH, 'cc.continent = :continent')
        ->setParameter('continent', $params['continent']);

    $query = $queryBuilder->getQuery();
    return $query->getResult();
}
</code>```

You can reuse the query and just pass a different value for continent to your $params array each time you want the cities for a different continent.

This code is not tested, but I think it should work. Just leave a comment if you run into issues while testing this.

You can also add methods like @Edwin suggested, but you have to realize that it will eagerly load all entities. This is killing for performance if you have a huge amount of rows in your tables (a lot of cities and countries). That is why a query in your repository would be better.

Alternatively you can do this inside your entities by using criteria and collection filtering. You can read on how to do this here in the documentation chapter 8.8. Filtering Collections

The advantage of using a filter is also well explained in the documentation:

If the collection has not been loaded from the database yet, the filtering API can work on the SQL level to make optimized access to large collections.

Body:
After a lot of searching for indirect associations, I only came up with this question. What I'd like to know is the exact opposite of that question, so I'm building up on it. Given the same entities:

class Continent {
    /**
    * @ORM\Id
    * @ORM\Column(type="integer", name="id")
    * @ORM\GeneratedValue(strategy="IDENTITY")
    */
    private $id;

    /**
    * @ORM\OneToMany(targetEntity="AppBundle\Entity\Country", mappedBy="continent")
    */
    private $countries;
}

class Country {
    /**
    * @ORM\Id
    * @ORM\Column(type="integer", name="id")
    * @ORM\GeneratedValue(strategy="IDENTITY")
    */
    private $id;

    /**
    * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Continent", inversedBy="countries")
    * @ORM\JoinColumn(name="continent_id", referencedColumnName="id")
    */
    private $continent;

    /**
    * @ORM\OneToMany(targetEntity="AppBundle\Entity\City", mappedBy="country")
    */
    private $cities;
}

class City {
    /**
    * @ORM\Id
    * @ORM\Column(type="integer", name="id")
    * @ORM\GeneratedValue(strategy="IDENTITY")
    */
    private $id;

    /**
    * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Country", inversedBy="cities")
    * @ORM\JoinColumn(name="country_id", referencedColumnName="id")
    */
    private $country;
}

Is there any way to have a collection of all cities in a continent, without having to build a custom query every time, with a field in the same fashion as the countries collection, possibly via annotations or maybe dynamic mapping?

The only way I could think of is by overriding the find... methods in the Repository - which I'm not sure how exactly I could achieve adding the field - and then either looping over the countries and adding their cities to a new collection, or using a custom query entirely.

Body:
First a comment about your mapping. Your mapping is wrong here:

inversedBy="countries" not inversedBy="country" and probably you want a column named continent_id instead of continentt_id

/**
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Continent", inversedBy="countries")
 * @ORM\JoinColumn(name="continent_id", referencedColumnName="id")
 */
 private $continent;

And here it should be inversedBy="cities" not inversedBy="city":

/**
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Country", inversedBy="cities")
 * @ORM\JoinColumn(name="country_id", referencedColumnName="id")
 */
 private $country;

Consider using validation for your entity model, the validation tool that ships with doctrine ORM will help you to get these things correct.

You can get such a result set by inner joining the countries with a certain continent.

Inside your CityRepository:

use Doctrine\ORM\Query\Expr\Join;

//...

public function findCitiesByContinent($params){
    $queryBuilder = $this->createQueryBuilder('c')
        ->innerJoin('c.country', 'cc', Join::WITH, 'cc.continent = :continent')
        ->setParameter('continent', $params['continent']);

    $query = $queryBuilder->getQuery();
    return $query->getResult();
}

You can reuse the query and just pass a different value for continent to your $params array each time you want the cities for a different continent.

This code is not tested, but I think it should work. Just leave a comment if you run into issues while testing this.

You can also add methods like @Edwin suggested, but you have to realize that it will eagerly load all entities. This is killing for performance if you have a huge amount of rows in your tables (a lot of cities and countries). That is why a query in your repository would be better.

Alternatively you can do this inside your entities by using criteria and collection filtering. You can read on how to do this here in the documentation chapter 8.8. Filtering Collections

The advantage of using a filter is also well explained in the documentation:

If the collection has not been loaded from the database yet, the filtering API can work on the SQL level to make optimized access to large collections.


问:
How to bring back removed spaces from a string
I have windows form application that encrypt the string and decrypt
it back using Caesar Algorithm. When encrypting a string I have to remove spaces from it ,but when I'll decrypt it again I should bring back the removed spaces into their actual places.

The problem I faced in this case is in bringing the removed spaces from the encrypted string and also when decrypting there are some letters are changed into special characters like this pattern where the encryption key is 3:

Plain text: My name is Shafaq Zahir

Encrypted text: PbqdphlvVkdidtCdklu

Decrypted text: M_nameisShafaq@ahir

This is my code

```<code>class CaesarAlgorithm
    {
        public string Encrypt(string pt,int key)
        {
            char[] buffer = pt.Replace(" ",string.Empty).ToCharArray();
            //char[] buffer = pt.ToCharArray();
            for(int i=0;i<buffer.Length;i++)
            {
                if (buffer[i] >= 'a' && buffer[i] <= 'z')
                {
                    buffer[i] = (char)(buffer[i] + key);
                    if (buffer[i] > 'z')
                    {
                        buffer[i] = (char)(buffer[i] - 26);
                    }
                }
                else if (buffer[i] >= 'A' && buffer[i] <= 'Z')
                {
                    buffer[i] = (char)(buffer[i] + key);
                    if (buffer[i] > 'Z')
                    {
                        buffer[i] = (char)(buffer[i] - 26);
                    }
                }
            }

            return new string (buffer);

        }

        public string Decrypt(string pt,int key)
        {
            char[] buffer = pt.ToCharArray();
            for (int i = 0; i < buffer.Length; i++)
            {
                if (buffer[i] >= 'a' && buffer[i] <= 'z')
                {
                    buffer[i] = (char)(buffer[i] - key);
                    if (buffer[i] > 'z')
                    {
                        buffer[i] = (char)(buffer[i] - 26);
                    }
                }
                else if (buffer[i] >= 'A' && buffer[i] <= 'Z')
                {
                    buffer[i] = (char)(buffer[i] - key);
                    if (buffer[i] > 'Z')
                    {
                        buffer[i] = (char)(buffer[i] - 26);
                    }
                }
            }

            return new string(buffer);
        }
    }
}
</code>```

答:
Shouldn't this code

```<code>if (buffer[i] > 'Z')
 {
buffer[i] = (char)(buffer[i] - 26);
 }
</code>```

Be

```<code>if (buffer[i] <'A')
 {
buffer[i] = (char)(buffer[i] + 26);
 }
</code>```

In your decrypt function?
To check if it's less than A or a because you are subtracting key from it.
Also don't replace spaces in your code. Just encrypt them and decrypt them they will stay, that said, there is no way to recover spaces unless you keep index information with it.!

Body:
I have windows form application that encrypt the string and decrypt
it back using Caesar Algorithm. When encrypting a string I have to remove spaces from it ,but when I'll decrypt it again I should bring back the removed spaces into their actual places.

The problem I faced in this case is in bringing the removed spaces from the encrypted string and also when decrypting there are some letters are changed into special characters like this pattern where the encryption key is 3:

Plain text: My name is Shafaq Zahir

Encrypted text: PbqdphlvVkdidtCdklu

Decrypted text: M_nameisShafaq@ahir

This is my code

class CaesarAlgorithm
    {
        public string Encrypt(string pt,int key)
        {
            char[] buffer = pt.Replace(" ",string.Empty).ToCharArray();
            //char[] buffer = pt.ToCharArray();
            for(int i=0;i<buffer.Length;i++)
            {
                if (buffer[i] >= 'a' && buffer[i] <= 'z')
                {
                    buffer[i] = (char)(buffer[i] + key);
                    if (buffer[i] > 'z')
                    {
                        buffer[i] = (char)(buffer[i] - 26);
                    }
                }
                else if (buffer[i] >= 'A' && buffer[i] <= 'Z')
                {
                    buffer[i] = (char)(buffer[i] + key);
                    if (buffer[i] > 'Z')
                    {
                        buffer[i] = (char)(buffer[i] - 26);
                    }
                }
            }

            return new string (buffer);

        }

        public string Decrypt(string pt,int key)
        {
            char[] buffer = pt.ToCharArray();
            for (int i = 0; i < buffer.Length; i++)
            {
                if (buffer[i] >= 'a' && buffer[i] <= 'z')
                {
                    buffer[i] = (char)(buffer[i] - key);
                    if (buffer[i] > 'z')
                    {
                        buffer[i] = (char)(buffer[i] - 26);
                    }
                }
                else if (buffer[i] >= 'A' && buffer[i] <= 'Z')
                {
                    buffer[i] = (char)(buffer[i] - key);
                    if (buffer[i] > 'Z')
                    {
                        buffer[i] = (char)(buffer[i] - 26);
                    }
                }
            }

            return new string(buffer);
        }
    }
}

Body:
Shouldn't this code

if (buffer[i] > 'Z')
 {
buffer[i] = (char)(buffer[i] - 26);
 }

Be

if (buffer[i] <'A')
 {
buffer[i] = (char)(buffer[i] + 26);
 }

In your decrypt function?
To check if it's less than A or a because you are subtracting key from it.
Also don't replace spaces in your code. Just encrypt them and decrypt them they will stay, that said, there is no way to recover spaces unless you keep index information with it.!


问:
SQL: No Sub-Query but only Joins
I am trying to find an alternative to this query where no sub-select is present but only joins (left, right, inner etc).

```<code>select count(SC.NUMBER_C)
from FNQP2PORTAL.SA.SEC_CAS SC
where SC.NUMBER_C not in (
select E.Reference from
FNQP2HQ.dbo.Entities E
join FNQP2HQ.dbo.Classes C on C.ID = E.ClassID
where C.Reference =  'Assembly case')
</code>```

So, it should be something like...

```<code>select count(SC.NUMBER_C)
from FNQP2PORTAL.SA.SEC_CAS SC
left join  FNQP2HQ.dbo.Entities E on E.Reference = SC.NUMBER_C and E.Reference IS NULL
inner join FNQP2HQ.dbo.Classes C on C.ID = E.ClassID and C.Reference =  'Assembly case'
</code>```

Can somebody help me here?

答:
Try the below code , it may throw error as you have not share the sample data with us. But you should use exists clause.</p>

```<code>SELECT COUNT(SC.NUMBER_C)
    FROM FNQP2PORTAL.SA.SEC_CAS SC,
    FNQP2HQ.dbo.Classes C,
    FNQP2HQ.dbo.Entities E
     WHERE C.ID = E.ClassID
     AND C.Reference = 'Assembly Case'
    and not exists(
    select 1 from  FNQP2HQ.dbo.Entities E1
        ON SC.NUMBER_C = E1.Reference)
</code>```

Title: SQL: No Sub-Query but only Joins

Body:
I am trying to find an alternative to this query where no sub-select is present but only joins (left, right, inner etc).

select count(SC.NUMBER_C)
from FNQP2PORTAL.SA.SEC_CAS SC
where SC.NUMBER_C not in (
select E.Reference from
FNQP2HQ.dbo.Entities E
join FNQP2HQ.dbo.Classes C on C.ID = E.ClassID
where C.Reference =  'Assembly case')

So, it should be something like...

select count(SC.NUMBER_C)
from FNQP2PORTAL.SA.SEC_CAS SC
left join  FNQP2HQ.dbo.Entities E on E.Reference = SC.NUMBER_C and E.Reference IS NULL
inner join FNQP2HQ.dbo.Classes C on C.ID = E.ClassID and C.Reference =  'Assembly case'

Can somebody help me here?

Body:
Try the below code , it may throw error as you have not share the sample data with us. But you should use exists clause.

SELECT COUNT(SC.NUMBER_C)
    FROM FNQP2PORTAL.SA.SEC_CAS SC,
    FNQP2HQ.dbo.Classes C,
    FNQP2HQ.dbo.Entities E
     WHERE C.ID = E.ClassID
     AND C.Reference = 'Assembly Case'
    and not exists(
    select 1 from  FNQP2HQ.dbo.Entities E1
        ON SC.NUMBER_C = E1.Reference)


问:
Swift Switch case on enum with Classes
This is the first time I use this kind of enums, enum with associated value type, I need to make a switch statement depending on the object's type, I cannot managed to do it, this is the enum:

```<code>enum TypeEnum {
    case foo(FooClass)
    case doo(DooClass)
    case roo(RooClass)
}
</code>```

My object has a variable of type TypeEnum, now I need to check which kind of object is in the enum:

```<code>if let anObject = object as? TypeEnum {

  switch anObject {
  case .foo(???):
     return true
    ...
    default:
      return false
    }

 }
</code>```

I have no idea what to put instead of ???. Xcode tells me to put something, but I just want to switch on .foo.

Any ideas?

答:
You could use the underscore to indicate that you aren't interested in the associated type:</p>

```<code>case .foo(_):
...
</code>```

Title: Swift Switch case on enum with Classes

Body:
This is the first time I use this kind of enums, enum with associated value type, I need to make a switch statement depending on the object's type, I cannot managed to do it, this is the enum:

enum TypeEnum {
    case foo(FooClass)
    case doo(DooClass)
    case roo(RooClass)
}

My object has a variable of type TypeEnum, now I need to check which kind of object is in the enum:

if let anObject = object as? TypeEnum {

  switch anObject {
  case .foo(???):
     return true
    ...
    default:
      return false
    }

 }

I have no idea what to put instead of ???. Xcode tells me to put something, but I just want to switch on .foo.

Any ideas?

Body:
You could use the underscore to indicate that you aren't interested in the associated type:

case .foo(_):
...


问:
Label Propagation in sklearn is classifying every vector as 1
I have 2000 labelled data (7 different labels) and about 100K unlabeled data and I am trying to use sklearn.semi_supervised.LabelPropagation. The data has 1024 dimensions. My problem is that the classifier is labeling everything as 1. My code looks like this:

```<code>X_unlabeled = X_unlabeled[:10000, :]
X_both = np.vstack((X_train, X_unlabeled))
y_both = np.append(y_train, -np.ones((X_unlabeled.shape[0],)))
clf = LabelPropagation(max_iter=100).fit(X_both, y_both)
y_pred = clf.predict(X_test)
</code>```

y_pred is all ones. Also, X_train is 2000x1024 and X_unlabeled is a subset of the unlabeled data which is 10000x1024.

I also get this error upon calling fit on the classifier:

/usr/local/lib/python2.7/site-packages/sklearn/semi_supervised/label_propagation.py:255: RuntimeWarning: invalid value encountered in divide
    self.label_distributions_ /= normalizer

答: The LabelPropagation will finally be fixed in version 0.19</p>

Body:
I have 2000 labelled data (7 different labels) and about 100K unlabeled data and I am trying to use sklearn.semi_supervised.LabelPropagation. The data has 1024 dimensions. My problem is that the classifier is labeling everything as 1. My code looks like this:

X_unlabeled = X_unlabeled[:10000, :]
X_both = np.vstack((X_train, X_unlabeled))
y_both = np.append(y_train, -np.ones((X_unlabeled.shape[0],)))
clf = LabelPropagation(max_iter=100).fit(X_both, y_both)
y_pred = clf.predict(X_test)

y_pred is all ones. Also, X_train is 2000x1024 and X_unlabeled is a subset of the unlabeled data which is 10000x1024.

I also get this error upon calling fit on the classifier:

/usr/local/lib/python2.7/site-packages/sklearn/semi_supervised/label_propagation.py:255: RuntimeWarning: invalid value encountered in divide
    self.label_distributions_ /= normalizer


问:
Loop list while adding to it
I've built my system in c-sharp (winforms) and I've run into a problem. In my view - my graphical interface - I'm starting a pretty heavy algorithm, which in each loop adds a result to a list in my view. The algorithm runs in a presenter (MVP pattern), using a backgroundworker - enabling the view not to freeze. As I said before, the algorithm runs in a loop, and since it's so heavy, I want to process the results of the algorithm as they come in.

View:

```<code>...
public List<string> Results { get; }
...
_presenter.RunAlgorithmAsync();
//Start processing results
...
</code>```

Backgroundworker in presenter:

```<code>...
_view.Results.Add(result);
...
</code>```

To sum it up, how can I start processing the list while the backgroundworker adds to it? Of course, the backgroundworker can work faster than the processing of the list, and vice versa - the processing may have to wait for results to arrive to the list, and the list need to be able up build up a stack of results.

I realize this question may be blurry, but if you ask me questions, I'm sure I can define the problem better.

答: Use a threadsafe queue to drive your producer/consumer pattern, such as the .NET 4 ConcurrentQueue:  http://www.codethinked.com/post/2010/02/04/NET-40-and-System_Collections_Concurrent_ConcurrentQueue.aspx</p>

Title: Loop list while adding to it

Body:
I've built my system in c-sharp (winforms) and I've run into a problem. In my view - my graphical interface - I'm starting a pretty heavy algorithm, which in each loop adds a result to a list in my view. The algorithm runs in a presenter (MVP pattern), using a backgroundworker - enabling the view not to freeze. As I said before, the algorithm runs in a loop, and since it's so heavy, I want to process the results of the algorithm as they come in.

View:

...
public List<string> Results { get; }
...
_presenter.RunAlgorithmAsync();
//Start processing results
...

Backgroundworker in presenter:

...
_view.Results.Add(result);
...

To sum it up, how can I start processing the list while the backgroundworker adds to it? Of course, the backgroundworker can work faster than the processing of the list, and vice versa - the processing may have to wait for results to arrive to the list, and the list need to be able up build up a stack of results.

I realize this question may be blurry, but if you ask me questions, I'm sure I can define the problem better.


问:
Android Studio Canary 4 App won't run unless you update Google Play Services
I have updated Emulators from SDK manager and created new Virtual Device. Still having trouble with running my app from Android Studio using Google Maps API. Please help.

UPDATE:

I have fixed it by installing a Virtual Device which is 1 API lower (API 25) using x86_64. This installs the necessary Intel Atom System Image. Now I can see the Goodle Map in the emulator

答:
There can be two ways

1: https://medium.com/@dai_shi/installing-google-play-services-on-an-android-studio-emulator-fffceb2c28a1

2: use genymotion (requires virtual box) link- https://www.genymotion.com/


问:
How to check if Kik/Snapchat Usernames are valid/exists with PHP
I need to check from a Website / Webhosting(no vps) if a kik and snapchat username exists / is valid?

I have no Idea how to do that since these are only mobile apps

答:
I found this URL:

https://feelinsonice-hrd.appspot.com/web/deeplink/snapcode?username=joshconstine&type=SVG

If there is a <image clip-path="url(#clip)" in there, then it sure is a valid snapchat username.


问:
Unhandled JS Exception: Error
i got into this error while trying to run react-native app fresh from init.

heres what i did:

react-native init NameOfApp

react-native run-ios

and got this screen

Please help. Im new in react-native.

Btw. My react native version is 0.43.3.

答:
I had the same error and got it fixed by running the following code from the current project folde:</p>

```<code>./node_modules/react-native/packager/packager.sh start --resetCache
</code>```

Title: Unhandled JS Exception: Error

Body:
I had the same error and got it fixed by running the following code from the current project folde:

./node_modules/react-native/packager/packager.sh start --resetCache


问:
How to limit the upload speed of an application?
I am using QNetworkAccessManager to upload a file (and some data) like this:

```<code>QNetworkRequest request(<some URL>);
QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
<multipart is filled with single parts>

networkAccessManager->post(request, multiPart);
</code>```

It works well.
However, users have reported that the upload influences their upload bandwidth. Which... makes sense, of course ;)

Now, I would like to implement something to limit the upload speed of this post request. However, after looking around for a while, I found absolutely nothing to do this in any simple way.

There is setReadBufferSize for the QNetworkReply, but no equivalent for writing. Seems like an obvious mistake not to add that...

I have found this thing: http://doc.qt.io/qt-5/qtnetwork-torrent-example.html

And tried to adjust some of its classes to my needs.
However, it all fails because I just cannot find a way to interrupt the writing of data (to do it slower than it normally would). That example relies on the user writing the writing-code himself - but that isn't possible here since Qt internally does the writing of the data after a post request.

I also tried using the Windows API Traffic Control, but that can just be used to limit a complete network interface or inspect packets, not a specific application. Plus, this has practically no examples, just some ancient code snippets. Not exactly what I want to work with...

Is there any way to achieve an upload throttle at all without having to rewrite Qt sources (which I won't do)?

A way to "globally" limit the upload speed of the application would be acceptable as well, using Windows API code or anything, really, as long as it is possible in code.

Additional info:

Limiting the upload speed of the user's computer is not acceptable. It must be limiting only a specific application. Similar to what you can do with NetLimiter.

答:
I would try this way: QHttpMultiPart uses QHttpPart elements as data chunks. And QHttpPart has QHttpPart::setBodyDevice( QIODevice * device ) to set its data provider. Create your own QIODevice provider and control data bandwidth inside it.

EDIT:
More general solution for QNetworkAccessManager would be to provide QIODevice for QNetworkAccessManager::post( const QNetworkRequest & request, QIODevice * data ) and control the bandwidth there.

See also at this proposed solution

Body:
I am using QNetworkAccessManager to upload a file (and some data) like this:

QNetworkRequest request(<some URL>);
QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
<multipart is filled with single parts>

networkAccessManager->post(request, multiPart);

It works well.
However, users have reported that the upload influences their upload bandwidth. Which... makes sense, of course ;)

Now, I would like to implement something to limit the upload speed of this post request. However, after looking around for a while, I found absolutely nothing to do this in any simple way.

There is setReadBufferSize for the QNetworkReply, but no equivalent for writing. Seems like an obvious mistake not to add that...

I have found this thing: http://doc.qt.io/qt-5/qtnetwork-torrent-example.html

And tried to adjust some of its classes to my needs.
However, it all fails because I just cannot find a way to interrupt the writing of data (to do it slower than it normally would). That example relies on the user writing the writing-code himself - but that isn't possible here since Qt internally does the writing of the data after a post request.

I also tried using the Windows API Traffic Control, but that can just be used to limit a complete network interface or inspect packets, not a specific application. Plus, this has practically no examples, just some ancient code snippets. Not exactly what I want to work with...

Is there any way to achieve an upload throttle at all without having to rewrite Qt sources (which I won't do)?

A way to "globally" limit the upload speed of the application would be acceptable as well, using Windows API code or anything, really, as long as it is possible in code.

Additional info:

Limiting the upload speed of the user's computer is not acceptable. It must be limiting only a specific application. Similar to what you can do with NetLimiter.


问:
How to get current function into a variable?
How can I get a variable that contains the currently executing function in Python? I don't want the function's name. I know I can use inspect.stack to get the current function name. I want the actual callable object. Can this be done without using inspect.stack to retrieve the function's name and then evaling the name to get the callable object?

Edit: I have a reason to do this, but it's not even a remotely good one. I'm using plac to parse command-line arguments. You use it by doing plac.call(main), which generates an ArgumentParser object from the function signature of "main". Inside "main", if there is a problem with the arguments, I want to exit with an error message that includes the help text from the ArgumentParser object, which means that I need to directly access this object by calling plac.parser_from(main).print_help(). It would be nice to be able to say instead: plac.parser_from(get_current_function()).print_help(), so that I am not relying on the function being named "main". Right now, my implementation of "get_current_function" would be:

```<code>import inspect
def get_current_function():
    return eval(inspect.stack()[1][3])
</code>```

But this implementation relies on the function having a name, which I suppose is not too onerous. I'm never going to do plac.call(lambda ...).

In the long run, it might be more useful to ask the author of plac to implement a print_help method to print the help text of the function that was most-recently called using plac, or something similar.

答:
The call stack does not keep a reference to the function itself -
although the running frame as a reference to the code object that is the code associated to a given function.

(Functions are objects with code, and some information about their environment, such as closures, name, globals dictionary, doc string, default parameters and so on).

Therefore if you are running a regular function, you are better of using its own name on the globals dictionary to call itself, as has been pointed out.

If you are running some dynamic, or lambda code, in which you can't use the function name, the only solution is to rebuild another function object which re-uses thre currently running code object and call that new function instead.

You will loose a couple of things, like default arguments, and it may be hard to get it working with closures (although it can be done).

I have written a blog post on doing exactly that - calling anonymous functions from within themselves - I hope the code in there can help you:

http://metapython.blogspot.com/2010/11/recursive-lambda-functions.html

On a side note: avoid the use o inspect.stack -- it is too slow, as it rebuilds a lot of information each time it is called. prefer to use inspect.currentframe to deal with code frames instead.

This may sounds complicated, but the code itself is very short - I am pasting it bellow. The post above contains more information on how this works.

```<code>from inspect import currentframe
from types import FunctionType

lambda_cache = {}

def myself (*args, **kw):
    caller_frame = currentframe(1)
    code = caller_frame.f_code
    if not code in lambda_cache:
        lambda_cache[code] = FunctionType(code, caller_frame.f_globals)
    return lambda_cache[code](*args, **kw)

if __name__ == "__main__":
    print "Factorial of 5", (lambda n: n * myself(n - 1) if n > 1 else 1)(5)
</code>```

If you really need the original function itself, the "myself" function above could be made to search on some scopes (like the calling function global dictionary) for a function object which code object would match with the one retrieved from the frame, instead of creating a new function.

ContentLicense: CC BY-SA 4.0

Body:
How can I get a variable that contains the currently executing function in Python? I don't want the function's name. I know I can use inspect.stack to get the current function name. I want the actual callable object. Can this be done without using inspect.stack to retrieve the function's name and then evaling the name to get the callable object?

Edit: I have a reason to do this, but it's not even a remotely good one. I'm using plac to parse command-line arguments. You use it by doing plac.call(main), which generates an ArgumentParser object from the function signature of "main". Inside "main", if there is a problem with the arguments, I want to exit with an error message that includes the help text from the ArgumentParser object, which means that I need to directly access this object by calling plac.parser_from(main).print_help(). It would be nice to be able to say instead: plac.parser_from(get_current_function()).print_help(), so that I am not relying on the function being named "main". Right now, my implementation of "get_current_function" would be:

import inspect
def get_current_function():
    return eval(inspect.stack()[1][3])

But this implementation relies on the function having a name, which I suppose is not too onerous. I'm never going to do plac.call(lambda ...).

In the long run, it might be more useful to ask the author of plac to implement a print_help method to print the help text of the function that was most-recently called using plac, or something similar.

Body:
The call stack does not keep a reference to the function itself -
although the running frame as a reference to the code object that is the code associated to a given function.

(Functions are objects with code, and some information about their environment, such as closures, name, globals dictionary, doc string, default parameters and so on).

Therefore if you are running a regular function, you are better of using its own name on the globals dictionary to call itself, as has been pointed out.

If you are running some dynamic, or lambda code, in which you can't use the function name, the only solution is to rebuild another function object which re-uses thre currently running code object and call that new function instead.

You will loose a couple of things, like default arguments, and it may be hard to get it working with closures (although it can be done).

I have written a blog post on doing exactly that - calling anonymous functions from within themselves - I hope the code in there can help you:

http://metapython.blogspot.com/2010/11/recursive-lambda-functions.html

On a side note: avoid the use o inspect.stack -- it is too slow, as it rebuilds a lot of information each time it is called. prefer to use inspect.currentframe to deal with code frames instead.

This may sounds complicated, but the code itself is very short - I am pasting it bellow. The post above contains more information on how this works.

from inspect import currentframe
from types import FunctionType

lambda_cache = {}

def myself (*args, **kw):
    caller_frame = currentframe(1)
    code = caller_frame.f_code
    if not code in lambda_cache:
        lambda_cache[code] = FunctionType(code, caller_frame.f_globals)
    return lambda_cache[code](*args, **kw)

if __name__ == "__main__":
    print "Factorial of 5", (lambda n: n * myself(n - 1) if n > 1 else 1)(5)

If you really need the original function itself, the "myself" function above could be made to search on some scopes (like the calling function global dictionary) for a function object which code object would match with the one retrieved from the frame, instead of creating a new function.


问:
Property [ptitle] does not exist on this collection instance in Laravel 5
I have a table with full of created products and when I click one of products' edit button, I get this error message: Property [ptitle] does not exist on this collection instance (View: C:\xampp\htdocs\webshop\resources\views\admin\termekszerk.blade.php)
Can anyone help me to solve this, please?
Models:

```<code>class Category extends Model
{

protected $fillable = ['cid', 'cname'];
protected $primaryKey = 'cid';

 public function item()
{
    return $this->hasMany('App\Item', 'cid');
}
}

class Item extends Model
{
protected $fillable = ['pid', 'pcat', 'pdescription', 'ptitle', 'pdb', 'par', 'pcikkszam' ];
protected $primaryKey = 'pid';

public function category()
{
    return $this->belongsTo('App\Category', 'pcat');
}

}
</code>```

Controller:

```<code>public function pedit($pid)
{
    $product = Item::find($pid)->first();
    return view('admin.termekszerk', compact('product'));
}

public function pupdate(ProductFormRequest $request, $pid)
{
    $product = Item::find($pid)->first();
    $product->ptitle = $request->get('ptitle');
    $product->pcat = $request->get('pcat');
    $product->pcikkszam = $request->get('pcikkszam');
    $product->par = $request->get('par');
    $product->pdb = $request->get('pdb');
    $product->pdescription = $request->get('pdescription');

    $product->save();
    return redirect(action('CategoriesController@index', $product->pid))->with('status', 'A termék frissítve!');

}
</code>```

termekszerk blade (this is the page what does not show when I click before edit button):

```<code><div class="container">
    <div class="well well bs-component">

        <form class="form-horizontal" method="post">

            @foreach ($errors->all() as $error)
                <p class="alert alert-danger">{{ $error }}</p>
            @endforeach

            <input type="hidden" name="_token" value="{!! csrf_token() !!}">

            <fieldset>
                <legend>Termék szerkesztése</legend>
                <div class="form-group">
                    <label for="title" class="col-lg-2 control-label">Termék neve</label>
                    <div class="col-lg-10">
                        <input type="text" class="form-control" id="ptitle" name="ptitle" value="{!! $product->ptitle !!}">
                    </div>
                </div>
                <div class="form-group">
                    <label for="title" class="col-lg-2 control-label">Cikkszám</label>
                    <div class="col-lg-10">
                        <input type="text" class="form-control" id="pcikkszam" name="pcikkszam" value="{!! $product->pcikkszam !!}">
                    </div>
                </div>
                <div class="form-group">
                    <label for="title" class="col-lg-2 control-label">Termék ára</label>
                    <div class="col-lg-10">
                        <input type="text" class="form-control" id="par" name="par" value="{!! $product->par !!}">
                    </div>
                </div>
                <div class="form-group">
                    <label for="title" class="col-lg-2 control-label">Mennyiség</label>
                    <div class="col-lg-10">
                        <input type="text" class="form-control" id="pdb" name="pdb" value="{!! $product->pdb !!}">
                    </div>
                </div>
                <div class="form-group">
                    <label for="content" class="col-lg-2 control-label">Termék leírás</label>
                    <div class="col-lg-10">
                        <textarea class="form-control" rows="18" id="pdescription" name="pdescription">{!! $product->pdescription !!}</textarea>
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-lg-10 col-lg-offset-2">
                        <a href="/admin/create_products"><button class="btn btn-default pbtn">Mégsem</button></a>

                         <form method="post" action="{!! action('CategoriesController@pupdate', $product->pid) !!}">
                            <input type="hidden" name="_token" value="{!! csrf_token() !!}">

                            <button type="submit" class="btn btn-primary pbtn">Változtatás</button>
                        </form>

                        <form method="post" action="{!! action('CategoriesController@pdestroy', $product->pid) !!}">
                            <input type="hidden" name="_token" value="{!! csrf_token() !!}">

                            <button type="submit" class="btn btn-danger pull-right pbtn">Törlés</button>
                        </form>

                    </div>
                </div>
            </fieldset>
        </form>

    </div>
</div>
</code>```

答: If you have added "ptitle" later and your previous products in database are without ptitle then may be thats why it is causing error</p>

Body:
I have a table with full of created products and when I click one of products' edit button, I get this error message: Property [ptitle] does not exist on this collection instance (View: C:\xampp\htdocs\webshop\resources\views\admin\termekszerk.blade.php)
Can anyone help me to solve this, please?
Models:

class Category extends Model
{

protected $fillable = ['cid', 'cname'];
protected $primaryKey = 'cid';

 public function item()
{
    return $this->hasMany('App\Item', 'cid');
}
}

class Item extends Model
{
protected $fillable = ['pid', 'pcat', 'pdescription', 'ptitle', 'pdb', 'par', 'pcikkszam' ];
protected $primaryKey = 'pid';

public function category()
{
    return $this->belongsTo('App\Category', 'pcat');
}

}

Controller:

public function pedit($pid)
{
    $product = Item::find($pid)->first();
    return view('admin.termekszerk', compact('product'));
}

public function pupdate(ProductFormRequest $request, $pid)
{
    $product = Item::find($pid)->first();
    $product->ptitle = $request->get('ptitle');
    $product->pcat = $request->get('pcat');
    $product->pcikkszam = $request->get('pcikkszam');
    $product->par = $request->get('par');
    $product->pdb = $request->get('pdb');
    $product->pdescription = $request->get('pdescription');

    $product->save();
    return redirect(action('CategoriesController@index', $product->pid))->with('status', 'A termék frissítve!');

}

termekszerk blade (this is the page what does not show when I click before edit button):

        <form class="form-horizontal" method="post">

            @foreach ($errors->all() as $error)

{{ $error }}

            @endforeach

            <input type="hidden" name="_token" value="{!! csrf_token() !!}">

            <fieldset>
                <legend>Termék szerkesztése</legend>

                    Termék neve

                        <input type="text" class="form-control" id="ptitle" name="ptitle" value="{!! $product->ptitle !!}">

                    Cikkszám

                        <input type="text" class="form-control" id="pcikkszam" name="pcikkszam" value="{!! $product->pcikkszam !!}">

                    Termék ára

                        <input type="text" class="form-control" id="par" name="par" value="{!! $product->par !!}">

                    Mennyiség

                        <input type="text" class="form-control" id="pdb" name="pdb" value="{!! $product->pdb !!}">

                    Termék leírás

                        <textarea class="form-control" rows="18" id="pdescription" name="pdescription">{!! $product->pdescription !!}</textarea>

                        <button class="btn btn-default pbtn">Mégsem</button>

                         <form method="post" action="{!! action('CategoriesController@pupdate', $product->pid) !!}">
                            <input type="hidden" name="_token" value="{!! csrf_token() !!}">

                            <button type="submit" class="btn btn-primary pbtn">Változtatás</button>
                        </form>

                        <form method="post" action="{!! action('CategoriesController@pdestroy', $product->pid) !!}">
                            <input type="hidden" name="_token" value="{!! csrf_token() !!}">

                            <button type="submit" class="btn btn-danger pull-right pbtn">Törlés</button>
                        </form>

            </fieldset>
        </form>


问:
Curl execution in python failed
I wanted to download files for around 300 item. An example is below:

```<code>curl 'http://genome.jgi.doe.gov/ext-api/downloads/get-directory?organism=Absrep1' -b cookies > Absrep1.xml
</code>```

This opens the page and downloads the content and stores it as xml file in my end

I tried to do a batch script in perl with system command, like

```<code>system('curl 'http://genome.jgi.doe.gov/ext-api/downloads/get-directory?organism=Absrep1'
-b cookies > Absrep1.xml');
</code>```

But, it did not work. There was syntax error, which I guess is due to single quotes.

I tried with python,

```<code>import subprocess
bash_com = 'curl "http://genome.jgi.doe.gov/ext-api/downloads/get-directory?organism=Absrep1" '
subprocess.Popen(bash_com)
output = subprocess.check_output(['bash','-c', bash_com])
</code>```

It did not work. I get the error, File does not exist. Even if it works, how can I include the

-b cookies > Absrep1.xml'

part in it?

Please help. Thanks in Advance,

AP

答:
In Perl, you should be able to use this:

system(q{curl 'http://genome.jgi.doe.gov/ext-api/downloads/get-directory?organism=Absrep1' -b cookies > Absrep1.xml});

However, you might be better off using LWP or possibly even HTTP::Tiny(unless you need the cookies) instead of shelling out. For more advanced uses, there is also WWW::Mechanize.

Title: Curl execution in python failed

Body:
I wanted to download files for around 300 item. An example is below:

curl 'http://genome.jgi.doe.gov/ext-api/downloads/get-directory?organism=Absrep1' -b cookies > Absrep1.xml

This opens the page and downloads the content and stores it as xml file in my end

I tried to do a batch script in perl with system command, like

system('curl 'http://genome.jgi.doe.gov/ext-api/downloads/get-directory?organism=Absrep1'
-b cookies > Absrep1.xml');

But, it did not work. There was syntax error, which I guess is due to single quotes.

I tried with python,

import subprocess
bash_com = 'curl "http://genome.jgi.doe.gov/ext-api/downloads/get-directory?organism=Absrep1" '
subprocess.Popen(bash_com)
output = subprocess.check_output(['bash','-c', bash_com])

It did not work. I get the error, File does not exist. Even if it works, how can I include the

-b cookies > Absrep1.xml'

part in it?

Please help. Thanks in Advance,

AP


问:
scikit-learn LabelPropagation replaces original labels
I try to learn scikit-learn and applied the LabelPropagation example for missing labels:

http://scikit-learn.org/stable/auto_examples/semi_supervised/plot_label_propagation_structure.html#example-semi-supervised-plot-label-propagation-structure-py

Adding one "wrong" label to the outer circle by

```<code>...
labels     = -np.ones(n_samples)
labels[0]  = outer
labels[1]  = inner
labels[2]  = outer
labels[-1] = inner
...
</code>```

I get the original label replaced by the other class, even if alpha is set to 1.0. As far as I understood, if alpha is 1.0 none of the original labels will be replaced.

Does anyone understand what happens?

Thanks in advance.

答: LabelSpreading and LabelPropagation will finally be fixed in version 0.19</p>

Body:
I try to learn scikit-learn and applied the LabelPropagation example for missing labels:

http://scikit-learn.org/stable/auto_examples/semi_supervised/plot_label_propagation_structure.html#example-semi-supervised-plot-label-propagation-structure-py

Adding one "wrong" label to the outer circle by

...
labels     = -np.ones(n_samples)
labels[0]  = outer
labels[1]  = inner
labels[2]  = outer
labels[-1] = inner
...

I get the original label replaced by the other class, even if alpha is set to 1.0. As far as I understood, if alpha is 1.0 none of the original labels will be replaced.

Does anyone understand what happens?

Thanks in advance.


问:
Filter Firebase Database DataSnapshot children on Android
I want to query the data from Firebase on Android.
And this is my data

And this is my Android Studio code :

```<code>Firebase myFirebaseRef = new Firebase("https://....../myCoffee/"+phone+"");
            myFirebaseRef.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot snapshot) {
                    int size= (int) snapshot.getChildrenCount();
                    txtMyCoffee.setText(""+size);
                          }
                @Override
                public void onCancelled(FirebaseError firebaseError) {
                }
            });
</code>```

Question :  The total count of the children is 4. How would I filter the children to only count children whose "coffeeNo" is "Acoffee"?

答:
Just improve your query to get only the result your are looking for:

```<code>DatabaseReference databaseRef = FirebaseDatabase.getInstance().getReferenceFromUrl("https://....../myCoffee/"+phone+"");
Query acoffeeQuery = databaseRef.orderByChild("coffeeNo").equalTo("Acoffee");
acoffeeQuery.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
        final int size = (int) snapshot.getChildrenCount();
        //size is equal to 2
    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {}
});
</code>```

This way, you do not have to loop over all results and you do not have
to implement a counter manually.

Body:
I want to query the data from Firebase on Android.
And this is my data

And this is my Android Studio code :

Firebase myFirebaseRef = new Firebase("https://....../myCoffee/"+phone+"");
            myFirebaseRef.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot snapshot) {
                    int size= (int) snapshot.getChildrenCount();
                    txtMyCoffee.setText(""+size);
                          }
                @Override
                public void onCancelled(FirebaseError firebaseError) {
                }
            });

Question :  The total count of the children is 4. How would I filter the children to only count children whose "coffeeNo" is "Acoffee"?

Body:
Just improve your query to get only the result your are looking for:

DatabaseReference databaseRef = FirebaseDatabase.getInstance().getReferenceFromUrl("https://....../myCoffee/"+phone+"");
Query acoffeeQuery = databaseRef.orderByChild("coffeeNo").equalTo("Acoffee");
acoffeeQuery.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
        final int size = (int) snapshot.getChildrenCount();
        //size is equal to 2
    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {}
});

This way, you do not have to loop over all results and you do not have
to implement a counter manually.


问:
java.time.format.DateTimeParseException: Text could not be parsed at index 3
I am using Java 8 to parse the the date and find difference between two dates.

Here is my snippet:

```<code>String date1 ="01-JAN-2017";
String date2 = "02-FEB-2017";

DateTimeFormatter df = DateTimeFormatter .ofPattern("DD-MMM-YYYY", en);
LocalDate  d1 = LocalDate.parse(date1, df);
LocalDate  d2 = LocalDate.parse(date2, df);

Long datediff = ChronoUnit.DAYS.between(d1,d2);
</code>```

When I run I get the error:

java.time.format.DateTimeParseException: Text could not be parsed at index 3

答:
First of all, check the javadoc. The uppercase D represents the day-of-year field (not the day-of-month as you want), and uppercase Y represents the week-based-year field (not the year as you want). The correct patterns are the lowercase letters d and y.

Also, you're using month names in uppercase letters (JAN and FEB), so your formatter must be case insensitive (the default behaviour is to accept only values like Jan and Feb). And these  month names are English abbreviations, so you must also use English locale to make sure it parses the names correctly (using java.util.Locale class).

So, your formatter should be created like this:

```<code>DateTimeFormatter df = new DateTimeFormatterBuilder()
    // case insensitive to parse JAN and FEB
    .parseCaseInsensitive()
    // add pattern
    .appendPattern("dd-MMM-yyyy")
    // create formatter (use English Locale to parse month names)
    .toFormatter(Locale.ENGLISH);
</code>```

This will make your code work (and datediff will be 32).

Body:
I am using Java 8 to parse the the date and find difference between two dates.

Here is my snippet:

String date1 ="01-JAN-2017";
String date2 = "02-FEB-2017";

DateTimeFormatter df = DateTimeFormatter .ofPattern("DD-MMM-YYYY", en);
LocalDate  d1 = LocalDate.parse(date1, df);
LocalDate  d2 = LocalDate.parse(date2, df);

Long datediff = ChronoUnit.DAYS.between(d1,d2);

When I run I get the error:

java.time.format.DateTimeParseException: Text could not be parsed at index 3

Body:
First of all, check the javadoc. The uppercase D represents the day-of-year field (not the day-of-month as you want), and uppercase Y represents the week-based-year field (not the year as you want). The correct patterns are the lowercase letters d and y.

Also, you're using month names in uppercase letters (JAN and FEB), so your formatter must be case insensitive (the default behaviour is to accept only values like Jan and Feb). And these  month names are English abbreviations, so you must also use English locale to make sure it parses the names correctly (using java.util.Locale class).

So, your formatter should be created like this:

DateTimeFormatter df = new DateTimeFormatterBuilder()
    // case insensitive to parse JAN and FEB
    .parseCaseInsensitive()
    // add pattern
    .appendPattern("dd-MMM-yyyy")
    // create formatter (use English Locale to parse month names)
    .toFormatter(Locale.ENGLISH);

This will make your code work (and datediff will be 32).


问:
Using Apache Knox in non Hadoop app
Does it makes sense to use Knox (+LDAP) as authentication proxy to application that is not using Hadoop at all?

I'm new to this domain and have heard about such possibility but I don't quite get it. Maybe there are some viable alternatives?

答: Absolutely ! you can use Apache Knox without Hadoop. I use it to secure my  Raspberry Pi Motion setup, this is a link to the blog post (it is still work in progress but you'll get an idea) Securing Raspberry Pi Security Camera (or UIs) using Apache Knox</p>

Title: Using Apache Knox in non Hadoop app


问:
Two return statements for one method? Python
I have a method which should print reports. There are two reports that are printed using the same method but has different conditions. I have given the if-else condition but some reason the else part is not being executed!
Kindly help me with the issue

```<code>count = 80
a = 20
if a > count:
    return xyz
else:
    return abc
</code>```

abc and xyz are two different types of reports that I have.

Edit:
This is my actual function. In each I'm fetching my records.

```<code>            for inv_no in each:
                if inv_no.invoice_date > '2017-06-30':
                    return {
                            'type': 'ir.actions.report.xml',
                            'report_name': 'gst_invoice_print',
                            'datas': datas,
                            }
                else:
                    return {
                            'type': 'ir.actions.report.xml',
                            'report_name': 'invoice_print',
                            'datas': datas,
                            }
</code>```

答:
I don't understand your problem, because your code works perfectly.
This code below works for me:

```<code>count = 80
a = 20
def test(a, count):
    if a > count:
        return "xyz"
    else:
        return "abc"
print test(a,count)
</code>```

it returns "abc"...

Body:
I have a method which should print reports. There are two reports that are printed using the same method but has different conditions. I have given the if-else condition but some reason the else part is not being executed!
Kindly help me with the issue

count = 80
a = 20
if a > count:
    return xyz
else:
    return abc

abc and xyz are two different types of reports that I have.

Edit:
This is my actual function. In each I'm fetching my records.

            for inv_no in each:
                if inv_no.invoice_date > '2017-06-30':
                    return {
                            'type': 'ir.actions.report.xml',
                            'report_name': 'gst_invoice_print',
                            'datas': datas,
                            }
                else:
                    return {
                            'type': 'ir.actions.report.xml',
                            'report_name': 'invoice_print',
                            'datas': datas,
                            }

Body:
I don't understand your problem, because your code works perfectly.
This code below works for me:

count = 80
a = 20
def test(a, count):
    if a > count:
        return "xyz"
    else:
        return "abc"
print test(a,count)

it returns "abc"...


问:
What the typical viewport size on a 1024x768 screen?
I am designing a web application, and I wish to know the largest size (x and y) that I can design for.

As of January 2008, about half of users are using 1024x278 screens, and probably less than 10% are using smaller screens. (Phone and palmtop users are an exception here.) So we are designing for minimum screen size of 1024x768.

However, that's the screen size, and when we are laying out our content we need to know the viewport size. There is evidence that most users have the browser maximized, but one still must subtract out space for OS decorations and browser chrome. People customize their chrome, so there is no single "right" answer; I am going for a reasonable bound that will accommodate the majority of users.

I see plenty of designers who say that they use a width of 960 pixels because it has many factors and can be divided up evenly -- but before deciding on this I want to know the maximum size that I can get away with, then I might choose to use somewhat less. I have seen max widths of 960, 974 or even 990 quoted... my own experiments seem to show a width of 1000 works OK.

Heights are even more difficult to come by: I find I can fit a vertical viewport height of 595 pixels works on the browsers that I've tried, with typical default OS and chrome settings. But I haven't tried very many, and I would rather see a more authoritative source. Surely someone else has done this research and done it better than me.

So my real question is this: What is the largest viewport size I can design for and expect it to fit without scrollbars for 80-90% of all users?

答:
For what it's worth, XP IE7 users with the default width of sidebar open at full-screen XGA get a viewport width of 862px. Heights are not so important as we expect to scroll vertically, but having to scroll horizontally as well is death.

There are of course any number of reasons why this might differ from what is actually available, which is why we're all good web designers and use proper liquid layouts, don't we.

(What's that, stackoverflow? Really? Shocking, tsk.)

OwnerDisplayName: mcherm

OwnerDisplayName: bobince