答:
I think its more a question of the objects you put in the dictionary than the dictionary itself. With myDict['myKey1'].height for example, its the object in the dict that has a height attribute.

Since you can add attributes to most objects, you just need to define a very thin class to make those objects. You can have that class add attributes by lists. Then you can use a collections.defaultdict so that the objects are created dynamically as the dictionary is used.

```<code>import collections

class Vals:

    def add(self, list_of_vals=[], list_of_names=[]):
        for val, name in zip(list_of_vals, list_of_names):
            setattr(self, name, val)

    def __str__(self):
        return str(self.__dict__)

mydict = collections.defaultdict(Vals)
mydict['Foo'].height = 1
mydict['Foo'].weight = 2
mydict['Foo'].add([1,2,3], ['a', 'b', 'c'],)
mydict['Bar'].add([10,11,12], 'def')
mydict['Baz'].something_else = 'hello'

assert mydict['Foo'].height == 1
assert mydict['Foo'].weight == 2
assert mydict['Foo'].a == 1
assert mydict['Foo'].b == 2
assert mydict['Foo'].c == 3

for name, obj in mydict.items():
    print(name, obj)
</code>```

Result

```<code>Baz {'something_else': 'hello'}
Bar {'d': 10, 'f': 12, 'e': 11}
Foo {'c': 3, 'height': 1, 'b': 2, 'weight': 2, 'a': 1}
</code>```

Title: Python--creating a class that adds a key to dictionary object + attaches specific values

Body:
First, here's my goal: I want to be able to add keys to a dictionary, and have those keys associated with a number of values. For example, I want to be able to have something like:

myDict['myKey1'].height
myDict['myKey1'].weight

I want to be able to add new keys to this, like myDict['myKey2'] such that I also have the option of attaching height and weight values to the new key as above.

Here's what I've got so far:

class Vividict(dict):
    def __missing__(self, key):
        value = self[key] = type(self)()
        return value

I've been using the above class to add new keys to dictionaries. I want to not only do this, but also input lists so that I can look up things like "height" and "weight" for the new key I add to my dictionary, by adding something like this into my class.

def __init__(self, list_of_vals, list_of_names):

    for x,y in zip(list_of_vals, list_of_names):
        self.(y) = x

I know the above is wrong, but I hope someone can see what I'm trying to achieve here. I want to define a class such that I can add a new key to a dictionary, and provide "list_of_vals" and "list_of_names" to attach some items to that dictionary key.

So, if I have "newKey" with list_of_vals=[1,2,3] and list_of_names=['height', 'weight', 'whatever'], I want to be able to do this:

myDict['newKey'].height = 1
myDict['newKey'].weight = 2
myDict['newKey'].whatever = 3

I hope this makes sense. I'm sort of trying to mimic what I can do in Matlab using structures.

Thanks!

----Update----

import collections

class Vals:

    def add(self, list_of_vals=[], list_of_names=[]):
        for val, name in zip(list_of_vals, list_of_names):
            setattr(self, name, val)

    def __str__(self):
        return str(self.__dict__)

mydict = collections.defaultdict(Vals)
mydict['Foo'].add([1,2], ['height', 'weight'])

The above from tdelaney is in the direction I want to move. Thanks!

If I take the above code to add height and weight attributes. I want to be able to add to these if they exist. For example, something like:

mydict['Foo'].add([3,4], ['height'])

Such that is results in:

mydict['Foo'].height = [1,2,3,4]

In other words, I add [3,4] to the height attribute for the 'Foo' key.

Another feature I'd like to build into this class is to concatenate new rows into a numpy array each time I add new lists of numbers. For example, if I start with this:

mydict['Foo'].add([1,2], ['height', 'weight'])

And then do this:

mydict['Foo'].add([3,4], ['height', 'weight'])

I want to end with the following:

mydict['Foo'].height = [1,3]
mydict['Foo'].weight = [2,4]
mydict['Foo'].array = [1, 2; 3, 4]

In other words, I'm adding to the height and weight attributes each time, allowing me to add to growing lists with new data. At the same time, I want to the class to initialize an empty numpy array that we will add to row by row, such that each row contains height and weight, column 1 containing multiple height values, column 2 containing multiple weight values, and each row gets concatenated to the bottom of the array each time.

Body:
I think its more a question of the objects you put in the dictionary than the dictionary itself. With myDict['myKey1'].height for example, its the object in the dict that has a height attribute.

Since you can add attributes to most objects, you just need to define a very thin class to make those objects. You can have that class add attributes by lists. Then you can use a collections.defaultdict so that the objects are created dynamically as the dictionary is used.

import collections

class Vals:

    def add(self, list_of_vals=[], list_of_names=[]):
        for val, name in zip(list_of_vals, list_of_names):
            setattr(self, name, val)

    def __str__(self):
        return str(self.__dict__)

mydict = collections.defaultdict(Vals)
mydict['Foo'].height = 1
mydict['Foo'].weight = 2
mydict['Foo'].add([1,2,3], ['a', 'b', 'c'],)
mydict['Bar'].add([10,11,12], 'def')
mydict['Baz'].something_else = 'hello'

assert mydict['Foo'].height == 1
assert mydict['Foo'].weight == 2
assert mydict['Foo'].a == 1
assert mydict['Foo'].b == 2
assert mydict['Foo'].c == 3

for name, obj in mydict.items():
    print(name, obj)

Result

Baz {'something_else': 'hello'}
Bar {'d': 10, 'f': 12, 'e': 11}
Foo {'c': 3, 'height': 1, 'b': 2, 'weight': 2, 'a': 1}


来源: stackexchange

问:
How can I take three consecutive terms of an array every nth terms?
Can anyone guide me on how to select several consecutive terms of an array (e.g. 3) every nth element from a 1D vector using MATLAB codes?

E.g if my array is array = [1 2 3 4 5 6 7 8 9 10 11 12];
I want to take three consecutive terms jumping four afterwards, so the solution would be array_solution = [1 2 3 8 9 10];

Thank you very much.

答:
If you don't want to use bsxfun (or function calls in general) for some reason, here is another way to get c consecutive elements every n elements.

```<code>x = 1:12;
c = 3;
n = 4;
% One of the two ranges in the indexing expression must be transposed
% so that MATLAB will apply vector expansion
y = x( (0:n+c:end-c) + (1:c)')

    y =
        1    2    3
        8    9   10
</code>```

You can also use this next snippet if you want the result to be a 1xm vector.

```<code>idxs = (0:n+c:end-c) + (1:c)';
y = x(idxs(:))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If you don't want to use bsxfun (or function calls in general) for some reason, here is another way to get c consecutive elements every n elements.

x = 1:12;
c = 3;
n = 4;
% One of the two ranges in the indexing expression must be transposed
% so that MATLAB will apply vector expansion
y = x( (0:n+c:end-c) + (1:c)')

    y =
        1    2    3
        8    9   10

You can also use this next snippet if you want the result to be a 1xm vector.

idxs = (0:n+c:end-c) + (1:c)';
y = x(idxs(:))


问:
Simultaneous sessions of Rstudio
Is it possible to somehow open several RStudios at the same time? I have Rstudio open, and when I try to open another one, nothing happens. What is the proper way to work on several projects simultaneously in RStudio?

答: If your work is contained in a separate RStudio project file, it should be as simple as selecting "Open Project in New Session", either from the File menu or from the project selector in the upper-right (at least on a Mac).</p>

Title: Simultaneous sessions of Rstudio


问:
Why is everything a property in iOS SDK tutorials?
In most of the iOS SDK tutorials I've read online both from Apple and elsewhere, so many instance variables are made properties, even when they are only accessed from within their own class.

E.G. in Facebook's latest iOS SDK a user is encouraged to maintain an instance of the Facebook class called facebook in the app delegate. facebook" is a property. This is then referred to throughout the sample code as "self.facebook". But the "facebook" property is not referenced anywhere from outside the app delegate.

Why is this? What am I missing? If an instance variable is only used within its own class, my inclination would be not to make it a property so that it is not publicly visible, and refer to it simply as facebook rather than self.facebook or  self->facebook from within the class.

Frankly, even if I needed the facebook property, I think I'd rather refer to it within the app delegate as simply "facebook" rather than "self.facebook".

So what gives? Why am I seeing properties everywhere?

答:
It creates the getter/setter for you automatically.
Also, here is a good post explaining it properties</p>

ContentLicense: CC BY-SA 2.5


问:
Android emulator-5554 offline
I'm having a problem with emulator-5554, it keeps telling me it is offline.

When I do a adb devices from the command line it says

emulator-5554 offline

Even after a fresh restart, I try that command and it still says it is offline.

The problem is when I try to install .apk files to the emulator using abd install <path> from the command prompt, it tells me that it is offline, if I create another device and run that one, then try to install the .apk files, it says I have too many devices connected. So in other words, I can't install my .apk files.

How can I get rid of that emulator-5554? I heard that if you do a restart, it should clear all the devices, but that does not seem to be working. It is like it is getting initialized when my computer starts up. Has anyone run into this issue?

Thanks

答:
Ensure that your enable ADB integration is marked;
go to Tools>Android>Enable ADB integration .

if doesn't checked , check this option and close your virtual device and re-open it . this worked for me.. good luck!!

ContentLicense: CC BY-SA 4.0

Title: Android emulator-5554 offline


问:
Batch file not appending and if statements not working correctly
Im at witts end trying to figure out what's wrong with my batch file

I can't seem to get some of the statements to work, and the final echo statement isn't appending tot he document. Can anyone chime in?

I want the first num to terminate if the user inputs 66

I also want the second num to jump to ZeroError if the user inputs the zero

I can't figure out why it isn't appending at the end to display the average or creating the one.txt file

```<code>@echo off

setlocal ENABLEDELAYEDEXPANSION

type NUL > results.txt

:MAIN
echo My Name is ****** > results.txt
echo The Current date is  %date% >> results.txt
echo The Current time is %time% >> results.txt
echo My name is ****, the current date is %date%  and the current time is %time%

:FirstNum

SET /P FirstNumber=Enter the First Number and press Enter :
if %FirstNumber% == "66" goto LOOP

:SecondNum

SET /P LastNumber=Enter the Second Number and press Enter:
if %LastNumber% == "0" goto ZeroError
if %LastNumber% == "66" goto LOOP
goto CALC

:ZeroError
SET /P zError =You CAN NOT divide by Zero, enter a correct number and press Enter:
if %LastNumber% == "66" goto LOOP
if %LastNumber% == "0" goto ZeroError
goto CALC

:CALC

set /A calculation = %FirstNumber% / %LastNumber%
echo %FirstNumber% divided by %LastNumber% equals %calculation%
echo %FirstNumber% divided by %LastNumber% equals %calculation% >> results.txt

pause

:LOOP

FOR /L %%A IN (1,1,10) DO(

SET /A  MOD= %%A %% 6
SET /A MODPlus= !MOD! + 2
SET /A TOTAL  += !MODPlus!
SET /A AVERAGE = !TOTAL!/10

)

echo The mean of the values is %AVERAGE% >> results.txt

mkdir pgm4
cd pgm4
type NUL > one.txt
echo REM ***** >> one.txt
echo echo ****** >> one.txt
ECHO. >> one.txt
</code>```

In my FirstNum label the program just keeps going despite me entering 66 in the prompt

Similar issue in SecondNum

the echo after the :LOOP doesn't append the average value to the text file.

Can anyone point me in the direction of what Im doing wrong?

答:
You seem to need to be spoon fed sigh,

to compare for equality both sides need to be equal, if the user enters "66" and only then the command if %FirstNumber% == "66" goto LOOP could evaluate true

excessive white space doesn't make your code easier to read.

set /a calculations can be combined in one line, and don't need % or ! for vars (except for vars).

```<code>echo off
setlocal ENABLEDELAYEDEXPANSION

:MAIN
( echo My Name is ******
  echo The Current date is  %date%
  echo The Current time is %time%
) >result.txt
echo My name is ****, the current date is %date%  and the current time is %time%

:FirstNum
SET /P FirstNumber=Enter the First Number and press Enter :
if "%FirstNumber%"=="66" goto LOOP

:SecondNum
SET /P LastNumber=Enter the Second Number and press Enter:
if "%LastNumber%"=="0" goto ZeroError
if "%LastNumber%"=="66" goto LOOP
goto CALC

:ZeroError
SET /P zError =You CAN NOT divide by Zero, enter a correct number and press Enter:
if "%LastNumber%"=="66" goto LOOP
if "%LastNumber%"=="0" goto ZeroError
goto CALC

:CALC
set /A calculation=FirstNumber/LastNumber
echo %FirstNumber% divided by %LastNumber% equals %calculation%
echo %FirstNumber% divided by %LastNumber% equals %calculation% >> results.txt
pause

:LOOP
FOR /L %%A IN (1,1,10) DO (
  SET /A  "MOD= %%A %% 6, MODPlus=MOD + 2, TOTAL+=MODPlus, AVERAGE=TOTAL/10"
)
echo The mean of the values is %AVERAGE% >> results.txt
mkdir pgm4
cd pgm4

( echo REM *****
  echo echo ******
  echo.
) > one.txt
</code>```

Body:
Im at witts end trying to figure out what's wrong with my batch file

I can't seem to get some of the statements to work, and the final echo statement isn't appending tot he document. Can anyone chime in?

I want the first num to terminate if the user inputs 66

I also want the second num to jump to ZeroError if the user inputs the zero

I can't figure out why it isn't appending at the end to display the average or creating the one.txt file

@echo off

setlocal ENABLEDELAYEDEXPANSION

type NUL > results.txt

:MAIN
echo My Name is ****** > results.txt
echo The Current date is  %date% >> results.txt
echo The Current time is %time% >> results.txt
echo My name is ****, the current date is %date%  and the current time is %time%

:FirstNum

SET /P FirstNumber=Enter the First Number and press Enter :
if %FirstNumber% == "66" goto LOOP

:SecondNum

SET /P LastNumber=Enter the Second Number and press Enter:
if %LastNumber% == "0" goto ZeroError
if %LastNumber% == "66" goto LOOP
goto CALC

:ZeroError
SET /P zError =You CAN NOT divide by Zero, enter a correct number and press Enter:
if %LastNumber% == "66" goto LOOP
if %LastNumber% == "0" goto ZeroError
goto CALC

:CALC

set /A calculation = %FirstNumber% / %LastNumber%
echo %FirstNumber% divided by %LastNumber% equals %calculation%
echo %FirstNumber% divided by %LastNumber% equals %calculation% >> results.txt

pause

:LOOP

FOR /L %%A IN (1,1,10) DO(

SET /A  MOD= %%A %% 6
SET /A MODPlus= !MOD! + 2
SET /A TOTAL  += !MODPlus!
SET /A AVERAGE = !TOTAL!/10

)

echo The mean of the values is %AVERAGE% >> results.txt

mkdir pgm4
cd pgm4
type NUL > one.txt
echo REM ***** >> one.txt
echo echo ****** >> one.txt
ECHO. >> one.txt

In my FirstNum label the program just keeps going despite me entering 66 in the prompt

Similar issue in SecondNum

the echo after the :LOOP doesn't append the average value to the text file.

Can anyone point me in the direction of what Im doing wrong?

Body:
You seem to need to be spoon fed sigh,

to compare for equality both sides need to be equal, if the user enters "66" and only then the command if %FirstNumber% == "66" goto LOOP could evaluate true

excessive white space doesn't make your code easier to read.

set /a calculations can be combined in one line, and don't need % or ! for vars (except for vars).

echo off
setlocal ENABLEDELAYEDEXPANSION

:MAIN
( echo My Name is ******
  echo The Current date is  %date%
  echo The Current time is %time%
) >result.txt
echo My name is ****, the current date is %date%  and the current time is %time%

:FirstNum
SET /P FirstNumber=Enter the First Number and press Enter :
if "%FirstNumber%"=="66" goto LOOP

:SecondNum
SET /P LastNumber=Enter the Second Number and press Enter:
if "%LastNumber%"=="0" goto ZeroError
if "%LastNumber%"=="66" goto LOOP
goto CALC

:ZeroError
SET /P zError =You CAN NOT divide by Zero, enter a correct number and press Enter:
if "%LastNumber%"=="66" goto LOOP
if "%LastNumber%"=="0" goto ZeroError
goto CALC

:CALC
set /A calculation=FirstNumber/LastNumber
echo %FirstNumber% divided by %LastNumber% equals %calculation%
echo %FirstNumber% divided by %LastNumber% equals %calculation% >> results.txt
pause

:LOOP
FOR /L %%A IN (1,1,10) DO (
  SET /A  "MOD= %%A %% 6, MODPlus=MOD + 2, TOTAL+=MODPlus, AVERAGE=TOTAL/10"
)
echo The mean of the values is %AVERAGE% >> results.txt
mkdir pgm4
cd pgm4

( echo REM *****
  echo echo ******
  echo.
) > one.txt


问:
Android adb "Unable to open sync connection!"
I can run and debug my Android app on my phone just fine, most of the time. Then, seemingly randomly, when I try to run or debug my app from Eclipse, the Console in Eclipse says:

```<code>[2010-10-12 09:36:48 - myapp] Android Launch!
[2010-10-12 09:36:48 - myapp] adb is running normally.
[2010-10-12 09:36:48 - myapp] Performing com.mycompany.myapp.MyActivity activity launch
[2010-10-12 09:36:48 - myapp] Automatic Target Mode: using device 'HT01TP800561'
[2010-10-12 09:36:48 - myapp] Uploading myapp.apk onto device 'HT01TP800561'
[2010-10-12 09:36:48 - myapp] Failed to upload myapp.apk on device 'HT01TP800561'
[2010-10-12 09:36:48 - myapp] java.io.IOException: Unable to open sync connection!
[2010-10-12 09:36:48 - myapp] Launch canceled!
</code>```

Retry: doesn't help, same messages.

Restart Eclipse: doesn't help.

Restart adb (adb kill-server && adb start-server): no errors, doesn't help.

Reconnect the phone: sometimes helps.

Reboot the computer: kind of drastic, haven't tried this yet.

Using Ubuntu 10.4, Eclipse Galileo 3.5.2, Android SDK 7, ADT plugin 0.9.6, Nexus One, Android 2.2.1.

Any bright ideas?

答:
I was having exactly the same problem, but I already had my phone connected to the computer's USB port. Sometimes disconnecting and reconnecting the cord worked but then it stopped working completely.
However, disabling USB debugging on the phone and then re-enabling it has worked so far. Hopefully it keeps working! These fixes really seem like silly hacks.. I'm not sure what the underlying problem is.</p>

Body:
I can run and debug my Android app on my phone just fine, most of the time. Then, seemingly randomly, when I try to run or debug my app from Eclipse, the Console in Eclipse says:

[2010-10-12 09:36:48 - myapp] Android Launch!
[2010-10-12 09:36:48 - myapp] adb is running normally.
[2010-10-12 09:36:48 - myapp] Performing com.mycompany.myapp.MyActivity activity launch
[2010-10-12 09:36:48 - myapp] Automatic Target Mode: using device 'HT01TP800561'
[2010-10-12 09:36:48 - myapp] Uploading myapp.apk onto device 'HT01TP800561'
[2010-10-12 09:36:48 - myapp] Failed to upload myapp.apk on device 'HT01TP800561'
[2010-10-12 09:36:48 - myapp] java.io.IOException: Unable to open sync connection!
[2010-10-12 09:36:48 - myapp] Launch canceled!

Retry: doesn't help, same messages.

Restart Eclipse: doesn't help.

Restart adb (adb kill-server && adb start-server): no errors, doesn't help.

Reconnect the phone: sometimes helps.

Reboot the computer: kind of drastic, haven't tried this yet.

Using Ubuntu 10.4, Eclipse Galileo 3.5.2, Android SDK 7, ADT plugin 0.9.6, Nexus One, Android 2.2.1.

Any bright ideas?


问:
How to take url output(JSON) as Java Variable
I am trying to use the value of rate in the below JSON object as my variable.

URL is : http://rate-exchange-1.appspot.com/currency?from=USD&to=INR

Output of above URL is like " {"to": "INR", "rate": 64.806700000000006, "from": "USD"}  ". I am assuming it as JSON object. how to get the value of 64, shall i get it by parsing?

答:
Q: how to get the value of 64, shall i get it by parsing?

A: Yes.

SUGGESTION:

You can also deserialize it into a Java object.

There are many libraries that support this, including:

JSONOjbect (Android)

GSon

Jackson


问:
Configuration for Spring stomp multi-application server
I'm developing a realtime notification system in Spring 4 by using a build-in Message Broker, and STOMP over WebSocket.

I would like to handle a case when there is a multi-application server and user destination is unresolved (because user is connected to another server). Spring docs claim there is a solution:

In a multi-application server scenario a user destination may remain
  unresolved because the user is connected to a different server. In
  such cases you can configure a destination to broadcast unresolved
  messages to so that other servers have a chance to try. This can be
  done through the userDestinationBroadcast property of the
  MessageBrokerRegistry in Java config and the
  user-destination-broadcast attribute of the message-broker element in
  XML.

But there is no example of such configuration. How can I set servers to recieve these messages and authentification parameters for system channel?

答:
When dealing with multi-node applications using WebSockets over STOMP you must configure and use an external STOMP Broker (such as RabbitMQ) so that different application instances can communicate each other. Are you already doing it, right?

In order to configure the userDestinationBroadcast and the userRegistryBroadcast just assign a destination name to them. When the application starts and the system TCP connection between the app and the broker is established, these destinations will be automatically created and everything will work fine and transparently.

I've coded a Web Chat app using Spring WebSockets, RabbitMQ and much more and its configuration is available here.

I hope this helps.


答:
You can use JSONObject to convert strings into objects.

```<code>String responseString = "{'to': 'INR', 'rate': 64.806700000000006, 'from': 'USD'}";
JSONObject responseObject = new JSONObject(responseString);
Log.d("Response",responseObject.getString("rate")); //64.806700000000006
</code>```

Title: How to take url output(JSON) as Java Variable

Body:
I am trying to use the value of rate in the below JSON object as my variable.

URL is : http://rate-exchange-1.appspot.com/currency?from=USD&to=INR

Output of above URL is like " {"to": "INR", "rate": 64.806700000000006, "from": "USD"}  ". I am assuming it as JSON object. how to get the value of 64, shall i get it by parsing?

Body:
You can use JSONObject to convert strings into objects.

String responseString = "{'to': 'INR', 'rate': 64.806700000000006, 'from': 'USD'}";
JSONObject responseObject = new JSONObject(responseString);
Log.d("Response",responseObject.getString("rate")); //64.806700000000006


问:
Check whether object exists in R
I am brand new to R, so please excuse anything that may seem overly obvious.

I am using apriori to evaluate frequent item sets.  When I execute the code below and my subset call returns items, everything works great.  The problem is when there is nothing returned on the subset (the criteria returns no subset).  When it does this, I am receiving "object 'rulesMatchLHS' not found" when trying to construct a data frame for output.  Can you please tell me what I am doing wrong when checking the validity of rulesMatchLHS on the ifelse line?

```<code>rules <- apriori(trnew, parameter=list(supp=0.01, conf=0.5, minlen=2, maxlen=2))
rulesMatchLHS <- subset(rules, lhs %ain% dataset1)
ifelse(exists(rulesMatchLHS),
OutputClient <- data.frame(lhs=labels(lhs(rulesMatchLHS))$elements, rhs=labels(rhs(rulesMatchLHS))$elements,rulesMatchLHS@quality),
OutputClient <- data.frame())
View(OutputClient)
</code>```

答:
Subset returns an empty data frame.  So it does exist. Also exists requires that the parameter be a character string.  You might want to change the exists to nrow in your ifelse.  Here is a simple example to demonstrate:</p>

```<code>test <- subset(iris, Species == "Fake")
typeof(test)
exists("test")
nrow(test) == 0
</code>```

Title: Check whether object exists in R

Body:
I am brand new to R, so please excuse anything that may seem overly obvious.

I am using apriori to evaluate frequent item sets.  When I execute the code below and my subset call returns items, everything works great.  The problem is when there is nothing returned on the subset (the criteria returns no subset).  When it does this, I am receiving "object 'rulesMatchLHS' not found" when trying to construct a data frame for output.  Can you please tell me what I am doing wrong when checking the validity of rulesMatchLHS on the ifelse line?

rules <- apriori(trnew, parameter=list(supp=0.01, conf=0.5, minlen=2, maxlen=2))
rulesMatchLHS <- subset(rules, lhs %ain% dataset1)
ifelse(exists(rulesMatchLHS),
OutputClient <- data.frame(lhs=labels(lhs(rulesMatchLHS))$elements, rhs=labels(rhs(rulesMatchLHS))$elements,rulesMatchLHS@quality),
OutputClient <- data.frame())
View(OutputClient)

Body:
Subset returns an empty data frame.  So it does exist. Also exists requires that the parameter be a character string.  You might want to change the exists to nrow in your ifelse.  Here is a simple example to demonstrate:

test <- subset(iris, Species == "Fake")
typeof(test)
exists("test")
nrow(test) == 0


问:
Having trouble running an if statement on a jquery ajax output
in my check.php I have an echo "ok";

however my if statement to check if the value is ok does not work.
Basically I want to execute a javascript function after check.php looks for the email in the database.

```<code>    $.ajax({
type: "POST",
 url: "check.php",
   data: "checkit=" + $("#checkEmail").val(),
    success: function(output){
    $("#userCheck").html(output);

            if(output == "ok"){
                alert("yay");
            }
        }

    });
</code>```

答:
I would suggest returning a JSON string rather than plain text. So your check.php should echo

```<code>{status: 'ok'}
</code>```

then change your ajax handler to:

```<code>$.ajax({
    type: "POST",
    url: "check.php",
    data: "checkit=" + $("#checkEmail").val(),
    success: function(response){
        $("#userCheck").html(response.status);
        if(response.status == "ok"){
            alert("yay");
        }
    }
}, 'json');
</code>```

or you could even just return a boolean value:

```<code>{success:true}
</code>```

Body:
in my check.php I have an echo "ok";

however my if statement to check if the value is ok does not work.
Basically I want to execute a javascript function after check.php looks for the email in the database.

    $.ajax({
type: "POST",
 url: "check.php",
   data: "checkit=" + $("#checkEmail").val(),
    success: function(output){
    $("#userCheck").html(output);

            if(output == "ok"){
                alert("yay");
            }
        }

    });

Body:
I would suggest returning a JSON string rather than plain text. So your check.php should echo

{status: 'ok'}

then change your ajax handler to:

$.ajax({
    type: "POST",
    url: "check.php",
    data: "checkit=" + $("#checkEmail").val(),
    success: function(response){
        $("#userCheck").html(response.status);
        if(response.status == "ok"){
            alert("yay");
        }
    }
}, 'json');

or you could even just return a boolean value:

{success:true}


问:
Difference between logistic regression and softmax regression
I know that logistic regression is for binary classification and softmax regression for multi-class problem. Would it be any differences if I train several logistic regression models with the same data and normalize their results to get a multi-class classifier instead of using one softmax model. I assume the result is of the same. Can I say : "all the multi-class classifier is the cascading result of binary classifiers". (except neuron network) </p>

答:
Echoing on what others have already conveyed.

Softmax Regression is a generalization of Logistic Regression that
summarizes a 'k' dimensional vector of arbitrary values to a 'k'
dimensional vector of values bounded in the range (0, 1).

In Logistic Regression we assume that the labels are binary (0 or 1).
However, Softmax Regression allows one to handle  classes.

Hypothesis function:

LR:

Softmax Regression:

Reference: http://ufldl.stanford.edu/tutorial/supervised/SoftmaxRegression/


问:
(PROLOG) Applying no repetition in "flatten" function
I have this function that flatten a list:

```<code>flatten([], []) :- !.
flatten([L|Ls], FlatL) :-
    !,
    flatten(L, NewL),
    flatten(Ls, NewLs),
    append(NewL, NewLs, FlatL),
flatten(L, [L]).
</code>```

and "no duplicates" :

```<code>my_compress([], []):- !.

my_compress([X|Xs], Ys):-
          my_member(X, Xs),
          !,
          my_compress(Xs, Ys).

my_compress([X|Xs], [X|Ys]):-
          my_compress(Xs, Ys).
</code>```

I have no idea how I can make a function with these two functions. I want to flatten a list without repetitions but in 1 function.

答:
You could apply my_compress/2 predicate to the flattened list recursively like:

```<code>flatten([], []) :- !.
flatten([L|Ls], FlatL) :-
    !,
    flatten(L, NewL),
    flatten(Ls, NewLs),
    append(NewL, NewLs, FL),
    my_compress(FL,FlatL).
flatten(L, [L]).
</code>```

Example:

```<code> ?- flatten([1,1,1,[[2],2],2,[3],3],L).
L = [1, 2, 3].
</code>```

OwnerDisplayName: Andrew Fells

Body:
I have this function that flatten a list:

flatten([], []) :- !.
flatten([L|Ls], FlatL) :-
    !,
    flatten(L, NewL),
    flatten(Ls, NewLs),
    append(NewL, NewLs, FlatL),
flatten(L, [L]).

and "no duplicates" :

my_compress([], []):- !.

my_compress([X|Xs], Ys):-
          my_member(X, Xs),
          !,
          my_compress(Xs, Ys).

my_compress([X|Xs], [X|Ys]):-
          my_compress(Xs, Ys).

I have no idea how I can make a function with these two functions. I want to flatten a list without repetitions but in 1 function.

Body:
You could apply my_compress/2 predicate to the flattened list recursively like:

flatten([], []) :- !.
flatten([L|Ls], FlatL) :-
    !,
    flatten(L, NewL),
    flatten(Ls, NewLs),
    append(NewL, NewLs, FL),
    my_compress(FL,FlatL).
flatten(L, [L]).

Example:

 ?- flatten([1,1,1,[[2],2],2,[3],3],L).
L = [1, 2, 3].


问:
How to distinguish NoneType with regex function?
Here are two very basic examples of the problem that I am currently encountering in my work:

```<code>import re
type(re.search('(Bob)(.*)(Builder)', "Bob the Builder" , re.IGNORECASE))
</code>```

returns _sre.SRE_Match and

```<code>import re
type(re.search('(Bob)(.*)(Builder)', "the Builder" , re.IGNORECASE))
</code>```

returns NoneType. How can I test for the condition whether the data type is _sre.SRE_Match or NoneType? When I try implementing the code

```<code>import re
type(re.search('(Bob)(.*)(Builder)', "the Builder" , re.IGNORECASE)) is None
</code>```

it returns False when it should be returning True. What am I doing incorrect here? Thank you!

答:
type(None) is not None, it's NoneType. But you don't need type here, just use a bool:

```<code>if re.search(....):
  print 'found!'
</code>```

Body:
Here are two very basic examples of the problem that I am currently encountering in my work:

import re
type(re.search('(Bob)(.*)(Builder)', "Bob the Builder" , re.IGNORECASE))

returns _sre.SRE_Match and

import re
type(re.search('(Bob)(.*)(Builder)', "the Builder" , re.IGNORECASE))

returns NoneType. How can I test for the condition whether the data type is _sre.SRE_Match or NoneType? When I try implementing the code

import re
type(re.search('(Bob)(.*)(Builder)', "the Builder" , re.IGNORECASE)) is None

it returns False when it should be returning True. What am I doing incorrect here? Thank you!

Body:
type(None) is not None, it's NoneType. But you don't need type here, just use a bool:

if re.search(....):
  print 'found!'


问:
Expected expression before token
Here is the code I got, when trying to compile it, I get two errors which unfortunately I fail to spot at the moment, hopefully another pair of eye would point out some insights.

The error falls at these two lines

```<code>print_all_paths(graph, int source_id, int destination_id, visited_arr, path, path_counter);
</code>```

Error for this one is:

```<code>error: expected expression before 'int'
</code>```

Second error falls at:

```<code>void print_all_paths(Graph* graph, int source_id, int destination_id, int visited_arr[], int path[], int &path_counter)
</code>```

Shows:

```<code>error: expected ';', ',' or ')' before '&' token
</code>```

Thank you!

答: I expect you want an * instead of the &</p>

Title: Expected expression before token

Body:
Here is the code I got, when trying to compile it, I get two errors which unfortunately I fail to spot at the moment, hopefully another pair of eye would point out some insights.

The error falls at these two lines

print_all_paths(graph, int source_id, int destination_id, visited_arr, path, path_counter);

Error for this one is:

error: expected expression before 'int'

Second error falls at:

void print_all_paths(Graph* graph, int source_id, int destination_id, int visited_arr[], int path[], int &path_counter)

Shows:

error: expected ';', ',' or ')' before '&' token

Thank you!

Body: I expect you want an * instead of the &


问:
Mysql dump restore fails: Cannot add foreign key constraint
I'm trying to restore a dump that I created using mysqldump. On restoring the same, I get this

ERROR 1215 (HY000) at line 63: Cannot add foreign key constraint

```<code>DROP TABLE IF EXISTS `channel_tags`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `channel_tags` (
  `channel_tag_id` bigint(20) NOT NULL AUTO_INCREMENT,
  `channel_id` bigint(20) NOT NULL,
  `tag_name` varchar(60) NOT NULL,
  PRIMARY KEY (`channel_tag_id`),
  KEY `channel_id_idx` (`channel_id`),
  KEY `tag_name_idx` (`tag_name`),
  CONSTRAINT `ct_channel_fk` FOREIGN KEY (`channel_id`) REFERENCES `channel_shard` (`channel_id`),
  CONSTRAINT `ct_tag_fk` FOREIGN KEY (`tag_name`) REFERENCES `tags` (`tag_name`)
) ENGINE=InnoDB AUTO_INCREMENT=833 DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;

DROP TABLE IF EXISTS `tags`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tags` (
  `tag_name` varchar(60) NOT NULL,
  `created_at` datetime DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  PRIMARY KEY (`tag_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
</code>```

The order of the create table statements is the same.

SHOW ENGINE INNODB STATUS\G gives me this:

```<code>------------------------
LATEST FOREIGN KEY ERROR
------------------------
2015-12-07 17:20:16 1ac30b000 Error in foreign key constraint of table sde/channel_tags:
 FOREIGN KEY (`tag_name`) REFERENCES `tags` (`tag_name`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8mb4:
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
</code>```

Can someone let me know what's going on here?

答:
I got this error too.

I guess you did the same thing as me: setup the whole DB as UTF8 and change some columns/tables to UTF8MB4 after that.

I have no idea how to resolve it.
But, there's a workaround: change all UTF8MB4 back to UTF8 in the dump SQL file, restore it into DB, and alter the specific column to UTF8MB4 manually by these command:

```<code>ALTER DATABASE [dbname] CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;

ALTER TABLE [tablename] CHANGE [colname] [colname] VARCHAR(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;

SET FOREIGN_KEY_CHECKS=0;

ALTER TABLE [tablename] CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

SET FOREIGN_KEY_CHECKS=1;
</code>```

Body:
I'm trying to restore a dump that I created using mysqldump. On restoring the same, I get this

ERROR 1215 (HY000) at line 63: Cannot add foreign key constraint

DROP TABLE IF EXISTS `channel_tags`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `channel_tags` (
  `channel_tag_id` bigint(20) NOT NULL AUTO_INCREMENT,
  `channel_id` bigint(20) NOT NULL,
  `tag_name` varchar(60) NOT NULL,
  PRIMARY KEY (`channel_tag_id`),
  KEY `channel_id_idx` (`channel_id`),
  KEY `tag_name_idx` (`tag_name`),
  CONSTRAINT `ct_channel_fk` FOREIGN KEY (`channel_id`) REFERENCES `channel_shard` (`channel_id`),
  CONSTRAINT `ct_tag_fk` FOREIGN KEY (`tag_name`) REFERENCES `tags` (`tag_name`)
) ENGINE=InnoDB AUTO_INCREMENT=833 DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;

DROP TABLE IF EXISTS `tags`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tags` (
  `tag_name` varchar(60) NOT NULL,
  `created_at` datetime DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  PRIMARY KEY (`tag_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;

The order of the create table statements is the same.

SHOW ENGINE INNODB STATUS\G gives me this:

------------------------
LATEST FOREIGN KEY ERROR
------------------------
2015-12-07 17:20:16 1ac30b000 Error in foreign key constraint of table sde/channel_tags:
 FOREIGN KEY (`tag_name`) REFERENCES `tags` (`tag_name`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8mb4:
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
for correct foreign key definition.

Can someone let me know what's going on here?

Body:
I got this error too.

I guess you did the same thing as me: setup the whole DB as UTF8 and change some columns/tables to UTF8MB4 after that.

I have no idea how to resolve it.
But, there's a workaround: change all UTF8MB4 back to UTF8 in the dump SQL file, restore it into DB, and alter the specific column to UTF8MB4 manually by these command:

ALTER DATABASE [dbname] CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;

ALTER TABLE [tablename] CHANGE [colname] [colname] VARCHAR(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;

SET FOREIGN_KEY_CHECKS=0;

ALTER TABLE [tablename] CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

SET FOREIGN_KEY_CHECKS=1;


答:
Actually, I was able to figure it out after attempting to search for solutions online:</p>

```<code>import re
if re.search('(Bob)(.*)(Builder)', "the Builder" , re.IGNORECASE):
    print 1
else:
    print 2
</code>```

Title: How to distinguish NoneType with regex function?

Body:
Actually, I was able to figure it out after attempting to search for solutions online:

import re
if re.search('(Bob)(.*)(Builder)', "the Builder" , re.IGNORECASE):
    print 1
else:
    print 2


问:
How to dynamically increment dates using strtotime?
I need to get 26 dates from a starting point. The next date starting from the previous one. It would be insane to hard code everything... So I was wondering how can I do this dynamically? Is there a smarter way? I'm looking to increment after the second date. Maybe with a for loop?</p>

```<code>    <?php
    //incrementing dates for bi-weekly (26 periods// 26 dates)
    $firstdate = strtotime("+17 days", strtotime("2017-04-03"));//1
    $i = date("Y-m-d", $firstdate); echo date("Y-m-d", $firstdate);//echo for testing
    echo'<br>';
    $seconddate =strtotime("+14 days", strtotime($i));//2
    $ii = date("Y-m-d", $seconddate); echo date("Y-m-d", $seconddate);//echo for testing
    echo'<br>';
    ?>
</code>```

答:
How about this:</p>

```<code>// initialize an array with your first date
$dates = array(strtotime("+17 days", strtotime("2017-04-03")));

// now loop 26 times to get the next 26 dates
for ($i = 1; $i <= 26; $i++) {
    // add 14 days to previous date in the array
    $dates[] = strtotime("+14 days", $dates[$i-1]);
}

// echo the results
foreach ($dates as $date) {
    echo date("Y-m-d", $date) . PHP_EOL;
}
</code>```

Body:
I need to get 26 dates from a starting point. The next date starting from the previous one. It would be insane to hard code everything... So I was wondering how can I do this dynamically? Is there a smarter way? I'm looking to increment after the second date. Maybe with a for loop?

    <?php
    //incrementing dates for bi-weekly (26 periods// 26 dates)
    $firstdate = strtotime("+17 days", strtotime("2017-04-03"));//1
    $i = date("Y-m-d", $firstdate); echo date("Y-m-d", $firstdate);//echo for testing
    echo'
';
    $seconddate =strtotime("+14 days", strtotime($i));//2
    $ii = date("Y-m-d", $seconddate); echo date("Y-m-d", $seconddate);//echo for testing
    echo'
';
    ?>

Body:
How about this:

// initialize an array with your first date
$dates = array(strtotime("+17 days", strtotime("2017-04-03")));

// now loop 26 times to get the next 26 dates
for ($i = 1; $i <= 26; $i++) {
    // add 14 days to previous date in the array
    $dates[] = strtotime("+14 days", $dates[$i-1]);
}

// echo the results
foreach ($dates as $date) {
    echo date("Y-m-d", $date) . PHP_EOL;
}


问:
How Do We Leave Picture-In-Picture Mode?
We have enterPictureInPictureMode() to move an activity from its current form into a picture-in-picture representation.

What is the means by which we revert that, returning the activity to its normal state, besides destroying the activity? There is no exitPictureInPictureMode(), leavePictureInPictureMode(), or janeGetMeOffThisCrazyPictureInPictureModeThing() method on Activity, and the documentation does not seem to cover an alternative.

I am interested in a solution for Android O, for picture-in-picture mode on mobile devices, though if that works for Android TV too, wonderful!

UPDATE 2017-04-08: If what you want is to return to normal mode when the user clicks the X button to exit picture-in-picture mode, you can do something like this:

```<code>  @Override
  public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode) {
    super.onPictureInPictureModeChanged(isInPictureInPictureMode);

    if (!isInPictureInPictureMode) {
      getApplication().startActivity(new Intent(this, getClass())
        .addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
    }
  }
</code>```

The key bits are to call startActivity() to start the current activity again with FLAG_ACTIVITY_REORDER_TO_FRONT. With a singleTask activity, you need to call that on some non-Activity context, such as the Application singleton. This does not appear to trigger onStop() or onStart(), but it does trigger onNewIntent() (with whatever Intent you pass to startActivity()).

答:
Official documentation says PIP window comes up with menu which let you toggle to full screen.

The PIP window is 240x135 dp and is shown at the top-most layer in one
  of the four corners of the screen, chosen by the system. The user can
  bring up a PIP menu that lets them toggle the PIP window to
  full-screen, or close the PIP window, by holding down the Home button
  on the remote. If another video starts playing on the main screen, the
  PIP window is automatically closed.

And you can override PIP changed event to handle UI elements whenever the user toggles PIP mode.

link to onPictureInPictureModeChanged

```<code>@Override
public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode) {
    if (isInPictureInPictureMode) {
        // Hide the controls in picture-in-picture mode.
        ...
    } else {
        // Restore the playback UI based on the playback status.
        ...
    }
}
</code>```

Body:
We have enterPictureInPictureMode() to move an activity from its current form into a picture-in-picture representation.

What is the means by which we revert that, returning the activity to its normal state, besides destroying the activity? There is no exitPictureInPictureMode(), leavePictureInPictureMode(), or janeGetMeOffThisCrazyPictureInPictureModeThing() method on Activity, and the documentation does not seem to cover an alternative.

I am interested in a solution for Android O, for picture-in-picture mode on mobile devices, though if that works for Android TV too, wonderful!

UPDATE 2017-04-08: If what you want is to return to normal mode when the user clicks the X button to exit picture-in-picture mode, you can do something like this:

  @Override
  public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode) {
    super.onPictureInPictureModeChanged(isInPictureInPictureMode);

    if (!isInPictureInPictureMode) {
      getApplication().startActivity(new Intent(this, getClass())
        .addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
    }
  }

The key bits are to call startActivity() to start the current activity again with FLAG_ACTIVITY_REORDER_TO_FRONT. With a singleTask activity, you need to call that on some non-Activity context, such as the Application singleton. This does not appear to trigger onStop() or onStart(), but it does trigger onNewIntent() (with whatever Intent you pass to startActivity()).

Body:
Official documentation says PIP window comes up with menu which let you toggle to full screen.

The PIP window is 240x135 dp and is shown at the top-most layer in one
  of the four corners of the screen, chosen by the system. The user can
  bring up a PIP menu that lets them toggle the PIP window to
  full-screen, or close the PIP window, by holding down the Home button
  on the remote. If another video starts playing on the main screen, the
  PIP window is automatically closed.

And you can override PIP changed event to handle UI elements whenever the user toggles PIP mode.

link to onPictureInPictureModeChanged

@Override
public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode) {
    if (isInPictureInPictureMode) {
        // Hide the controls in picture-in-picture mode.
        ...
    } else {
        // Restore the playback UI based on the playback status.
        ...
    }
}


问:
Tensorflow Restore Model and Predict
I have trained a Tensorflow model and saved the output layer's tensor. When restoring, I restored the output layer's tensor and tried predicting with it but got an error saying I never assigned to a placeholder. My code is below, please assist.</p>

```<code>with tf.Session() as sess:
model_saver = tf.train.import_meta_graph(model_save_folder + '/my-model.meta')
model_saver.restore(sess, model_save_folder + '/my-model')
x = tf.placeholder('float')
output = tf.get_collection("output")[0] #output will be the tensor for model's last layer
print("Model restored.")
print('Initialized')
#print(sess.run(tf.get_default_graph().get_tensor_by_name('w_conv1:0')))

#collect list of preprocessed data on submission set
inputData = []
with open('stage1_sample_submission.csv') as f:
    reader = csv.reader(f)
    num = 0

    for row in reader:
        if num > 0:
            patient = row[0]
            #print(patient)
            inputData.append(process_data(patient, img_px_size=IMG_SIZE_PX, hm_slices=SLICE_COUNT))
        num += 1

#prediction!
prediction = sess.run(output, feed_dict={x: inputData})
print(prediction)
</code>```

答:
you need to restore the placeholder the same way.

```<code>x = tf.get_collection("placeholder")[0]
</code>```

replace placeholder with whatever it's name is in the original graph

Title: Tensorflow Restore Model and Predict

Body:
I have trained a Tensorflow model and saved the output layer's tensor. When restoring, I restored the output layer's tensor and tried predicting with it but got an error saying I never assigned to a placeholder. My code is below, please assist.

with tf.Session() as sess:
model_saver = tf.train.import_meta_graph(model_save_folder + '/my-model.meta')
model_saver.restore(sess, model_save_folder + '/my-model')
x = tf.placeholder('float')
output = tf.get_collection("output")[0] #output will be the tensor for model's last layer
print("Model restored.")
print('Initialized')
#print(sess.run(tf.get_default_graph().get_tensor_by_name('w_conv1:0')))

#collect list of preprocessed data on submission set
inputData = []
with open('stage1_sample_submission.csv') as f:
    reader = csv.reader(f)
    num = 0

    for row in reader:
        if num > 0:
            patient = row[0]
            #print(patient)
            inputData.append(process_data(patient, img_px_size=IMG_SIZE_PX, hm_slices=SLICE_COUNT))
        num += 1

#prediction!
prediction = sess.run(output, feed_dict={x: inputData})
print(prediction)

Body:
you need to restore the placeholder the same way.

x = tf.get_collection("placeholder")[0]

replace placeholder with whatever it's name is in the original graph


问:
if else statement in map function reactjs
You don't have to read the whole code, just read the comment in the editQuantity function and in showOrderItem function, specially in the showOrderItem function and my problem is i think just silly, as both of my function are working as they supposed to work,

*editQuantity function supposed to change the state, it changing it, i checked by adding the console line.

*showOrderItem function supposed display the item, he is doing that job as well.

My problem is, i try to add conditional rendering in the showOrderItem function that not working, even though i am able to change the state.

Please read the comment in showOrderItem function, to see where is the problem:

```<code>import React from 'react';

export default class ShowOrder extends React.Component{
    constructor(props){
        super(props);
        this.state={
            quantityEditing:this.props.orderItems,

        }
    }

    editQuantity(item){
        const order=this.state.quantityEditing;
        for(var i =0; i<order.length; i++){

            if(order[i].item==item){
                console.log(order[i].orderQuantityEditing)
                order[i].orderQuantityEditing=true;
                this.setState({order:this.state.quantityEditing})
                console.log(order[i].orderQuantityEditing)

            }
        }
    }
    showOrderItem(){

        const style = {cursor:'pointer'}
        const orderItems=this.state.quantityEditing;
        console.log(orderItems)
        const orderItem=orderItems.map((item,index)=>

        <p>
        {orderItems.orderQuantityEditing ? 'some':
        <span style={style} onClick={this.editQuantity.bind(this,item.item)}>
//as you can see in here i added conditional rendering, that if orderItems.orderQuantityEditing is true display me some, but that's not working --orderItems.orderQuantityEditing ? 'some'(this part) does not matter how many times i click on property it never display me my string 'some'
            {item.quantity}</span>}
        <span style={style}> {item.item}</span>
        <span style={style}> Q</span>
        <span style={style}> N</span>
        <span style={style}> X</span>
        </p>

        );

        return orderItem;
    }
    render(){

        return(
        <div>
        {this.showOrderItem()}

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

答:
Instead of

```<code>{orderItems.orderQuantityEditing ?
    'some'
     :
     <span style={style} onClick{this.editQuantity.bind(this,item.item)}>
</code>```

I think you need to write this:

```<code>{item.orderQuantityEditing ?
     'some'
      :
      <span style={style} onClick={this.editQuantity.bind(this,item.item)}>
</code>```

Because you are using map, and item will be each object of array, so you need to use item to access that property. During the for loop, when changing the state you wrote:

```<code>order[i].orderQuantityEditing=true;
</code>```

That it proper, order will be an array and you need to provide the index to access particular object of that.

Body:
You don't have to read the whole code, just read the comment in the editQuantity function and in showOrderItem function, specially in the showOrderItem function and my problem is i think just silly, as both of my function are working as they supposed to work,

*editQuantity function supposed to change the state, it changing it, i checked by adding the console line.

*showOrderItem function supposed display the item, he is doing that job as well.

My problem is, i try to add conditional rendering in the showOrderItem function that not working, even though i am able to change the state.

Please read the comment in showOrderItem function, to see where is the problem:

import React from 'react';

export default class ShowOrder extends React.Component{
    constructor(props){
        super(props);
        this.state={
            quantityEditing:this.props.orderItems,

        }
    }

    editQuantity(item){
        const order=this.state.quantityEditing;
        for(var i =0; i<order.length; i++){

            if(order[i].item==item){
                console.log(order[i].orderQuantityEditing)
                order[i].orderQuantityEditing=true;
                this.setState({order:this.state.quantityEditing})
                console.log(order[i].orderQuantityEditing)

            }
        }
    }
    showOrderItem(){

        const style = {cursor:'pointer'}
        const orderItems=this.state.quantityEditing;
        console.log(orderItems)
        const orderItem=orderItems.map((item,index)=>

        {orderItems.orderQuantityEditing ? 'some':

//as you can see in here i added conditional rendering, that if orderItems.orderQuantityEditing is true display me some, but that's not working --orderItems.orderQuantityEditing ? 'some'(this part) does not matter how many times i click on property it never display me my string 'some'
            {item.quantity}}
         {item.item}
         Q
         N
         X

        );

        return orderItem;
    }
    render(){

        return(

        {this.showOrderItem()}

        );
    }
}

Body:
Instead of

{orderItems.orderQuantityEditing ?
    'some'
     :
     <span style={style} onClick{this.editQuantity.bind(this,item.item)}>

I think you need to write this:

{item.orderQuantityEditing ?
     'some'
      :
      <span style={style} onClick={this.editQuantity.bind(this,item.item)}>

Because you are using map, and item will be each object of array, so you need to use item to access that property. During the for loop, when changing the state you wrote:

order[i].orderQuantityEditing=true;

That it proper, order will be an array and you need to provide the index to access particular object of that.


问:
Exporting Git release branch
I'm using TFS-GIT and I was wondering if its possible to extract everything that's been committed into a release branch to a ZIP. I've looked at an example and it insinuates everything in that branch would be extracted. I'm just looking to extract the files which have been added/updated with the folder structure of where the changes reside.

The reason I need to do this is because I cannot automatically deploy my code via TFS deploy, Jenkins or any other means to the live servers due to organisation rules, therefore I can only upload the files manually.

I've used the following command, the zip file is created but nothing is added to the zip.

```<code>git archive --format zip --output c:\zipfile.zip release_1.1
</code>```

Thanking you in advance

答:
I've found this which does what I needed.</p>

```<code>git archive -o update.zip HEAD $(git diff --name-only HEAD@{"2016-01-15 00:00:00"} --diff-filter=ACMRTUXB)
</code>```

Title: Exporting Git release branch

Body:
I'm using TFS-GIT and I was wondering if its possible to extract everything that's been committed into a release branch to a ZIP. I've looked at an example and it insinuates everything in that branch would be extracted. I'm just looking to extract the files which have been added/updated with the folder structure of where the changes reside.

The reason I need to do this is because I cannot automatically deploy my code via TFS deploy, Jenkins or any other means to the live servers due to organisation rules, therefore I can only upload the files manually.

I've used the following command, the zip file is created but nothing is added to the zip.

git archive --format zip --output c:\zipfile.zip release_1.1

Thanking you in advance

Body:
I've found this which does what I needed.

git archive -o update.zip HEAD $(git diff --name-only HEAD@{"2016-01-15 00:00:00"} --diff-filter=ACMRTUXB)


问:
Dynamic memory allocation for char***
I was trying to dynamically allocate memory for a char***.

```<code>char*** tas;
</code>```

With char*** i want to describe a table of strings with 2 columns only.

Main problem i had trying to achieve that is not to compile the program but make it run without a segmentation fault.

The issue i think is the not proper use of realloc.
Checking man page of realloc/calloc/malloc

```<code>void *realloc(void *ptr, size_t size);
void *malloc(size_t size);
void *calloc(size_t nmemb, size_t size);
</code>```

I found out that i have to generate the proper size_t vars to send to allocate functions.

The crucial lines of code for this are the following:

```<code>tas         = (char ***)realloc(tas,sizeof(char **)*(i+1));
tas[i]      = (char **)calloc(2,sizeof(char *));
tas[i][0]   = (char *)calloc(lenKey+1,sizeof(char));
tas[i][1]   = (char *)calloc(lenValue+1,sizeof(char));
++i;
</code>```

With tas beeing the char***.

--------EDIT-------

Piece by piece I compiled an answer and i am posting the solution i found to the problem here.

答:
Your initial allocation should be done with malloc or calloc instead of realloc; otherwise, your initial pointer argument needs to be NULL:

```<code>char ***tas = malloc( (i+1) * sizeof *tas );
</code>```

or

```<code>char ***tas = calloc( i+1, sizeof *tas );
</code>```

or

```<code>char ***tas = realloc( NULL, (i+1) * sizeof *tas );
</code>```

or

```<code>char ***tas = NULL;
tas = realloc( tas, (i+1) * sizeof *tas );
</code>```

You're pretty close otherwise - just lose the extraneous casts.

```<code>tas[i] = calloc( 2 * sizeof *tas[i] );
</code>```

and

```<code>tas[i][0] = calloc( lenKey + 1, sizeof *tas[i][0] );
tas[i][1] = calloc( lenValue + 1, sizeof *tas[i][1] );
</code>```

As always, check the result of every *alloc call.

Title: Dynamic memory allocation for char***

Body:
I was trying to dynamically allocate memory for a char***.

char*** tas;

With char*** i want to describe a table of strings with 2 columns only.

Main problem i had trying to achieve that is not to compile the program but make it run without a segmentation fault.

The issue i think is the not proper use of realloc.
Checking man page of realloc/calloc/malloc

void *realloc(void *ptr, size_t size);
void *malloc(size_t size);
void *calloc(size_t nmemb, size_t size);

I found out that i have to generate the proper size_t vars to send to allocate functions.

The crucial lines of code for this are the following:

tas         = (char ***)realloc(tas,sizeof(char **)*(i+1));
tas[i]      = (char **)calloc(2,sizeof(char *));
tas[i][0]   = (char *)calloc(lenKey+1,sizeof(char));
tas[i][1]   = (char *)calloc(lenValue+1,sizeof(char));
++i;

With tas beeing the char***.

--------EDIT-------

Piece by piece I compiled an answer and i am posting the solution i found to the problem here.

Body:
Your initial allocation should be done with malloc or calloc instead of realloc; otherwise, your initial pointer argument needs to be NULL:

char ***tas = malloc( (i+1) * sizeof *tas );

or

char ***tas = calloc( i+1, sizeof *tas );

or

char ***tas = realloc( NULL, (i+1) * sizeof *tas );

or

char ***tas = NULL;
tas = realloc( tas, (i+1) * sizeof *tas );

You're pretty close otherwise - just lose the extraneous casts.

tas[i] = calloc( 2 * sizeof *tas[i] );

and

tas[i][0] = calloc( lenKey + 1, sizeof *tas[i][0] );
tas[i][1] = calloc( lenValue + 1, sizeof *tas[i][1] );

As always, check the result of every *alloc call.


问: How to remove only one inline

答:
wp_enqueue_style takes 5 parameter

$handle
(string) (Required) Name of the stylesheet. Should be unique.

$src
(string) (Optional) Full URL of the stylesheet, or path of the stylesheet relative to the WordPress root directory.
Default value: ''

$deps
(array) (Optional) An array of registered stylesheet handles this stylesheet depends on.
Default value: array()
$ver
(string|bool|null) (Optional) String specifying stylesheet version number, if it has one, which is added to the URL as a query string for cache busting purposes. If version is set to false, a version number is automatically added equal to current installed WordPress version. If set to null, no version is added.

Default value: false
$media
(string) (Optional) The media for which this stylesheet has been defined. Accepts media types like 'all', 'print' and 'screen', or media queries like '(orientation: portrait)' and '(max-width: 640px)'.
Default value: 'all'

You can change your code in function.php file

```<code>wp_enqueue_style( 'mycustom_css', get_template_directory_uri() . '/custom.css', array(), '1.0.0', true );
</code>```

it will be work. check that you have only one custom.css file in your theme root .

Title: How to remove only one inline <style> from Wordpress head

Body:
I'm designing a Wordpress site that's not yet live. There is a block of inline css in the head of the home page that needs to go. I'm not sure where it's being generated from but the I've modified the css since and the inline css isn't updating to match it.

I've tried overruling it by using !important in my custom.css.

I've tried adding my style sheet just above the  so it loads last.

<link rel='stylesheet' href='http://mywebsite/wpnew/wp-content/themes/mytheme/custom.css?counter=1491147962' type='text/css' media='all' />

I've tried adding this to my functions.php:

wp_enqueue_style( 'customcss', get_template_directory_uri() . '/custom.css', array(), time() );

I've deleted the widget that the css belongs to thinking the page might render without the inline css since the widget was gone but it's still there.

I'm at a loss. I'm not a programmer and not entirely comfortable with php. I found a plugin that strips all inline tags but I only want to get rid of this one block of css.

Any help would be appreciated!

Body:
wp_enqueue_style takes 5 parameter

$handle
(string) (Required) Name of the stylesheet. Should be unique.

$src
(string) (Optional) Full URL of the stylesheet, or path of the stylesheet relative to the WordPress root directory.
Default value: ''

$deps
(array) (Optional) An array of registered stylesheet handles this stylesheet depends on.
Default value: array()
$ver
(string|bool|null) (Optional) String specifying stylesheet version number, if it has one, which is added to the URL as a query string for cache busting purposes. If version is set to false, a version number is automatically added equal to current installed WordPress version. If set to null, no version is added.

Default value: false
$media
(string) (Optional) The media for which this stylesheet has been defined. Accepts media types like 'all', 'print' and 'screen', or media queries like '(orientation: portrait)' and '(max-width: 640px)'.
Default value: 'all'

You can change your code in function.php file

wp_enqueue_style( 'mycustom_css', get_template_directory_uri() . '/custom.css', array(), '1.0.0', true );

it will be work. check that you have only one custom.css file in your theme root .


问:
ListSelectionListener not changing panel
I want a ListSelectionListener event to change a JPanel. I know it is getting fired properly because the print statement is working, however the panel does not change at all.

```<code>DefaultListModel leftList = new DefaultListModel();
JList order = new JList(leftList);
order.addListSelectionListener(this);
JPanel configPanel = new JPanel();

public void valueChanged(ListSelectionEvent e) {
 if(e.getValueIsAdjusting()){
        int index = order.getSelectedIndex();
        System.out.println(leftList.getElementAt(index).toString());
        configPanel.removeAll();
        configPanel.repaint();
        configPanel.add(new JLabel("nice"));
        configPanel.repaint();
        }
    }
</code>```

I threw in the second repaint simply because I was out of things to try, however it still did not work.

答:
When you add components to a visible GUI the basic logic is:

```<code>panel.remove(...);
panel.add(...);
panel.revalidate();
panel.repaint();
</code>```

Basically all components have a size of (0, 0) when they are created so there is nothing to paint. You need to invoke revalidate() so the layout manager can give the components a size and location on the panel.

Body:
I want a ListSelectionListener event to change a JPanel. I know it is getting fired properly because the print statement is working, however the panel does not change at all.

DefaultListModel leftList = new DefaultListModel();
JList order = new JList(leftList);
order.addListSelectionListener(this);
JPanel configPanel = new JPanel();

public void valueChanged(ListSelectionEvent e) {
 if(e.getValueIsAdjusting()){
        int index = order.getSelectedIndex();
        System.out.println(leftList.getElementAt(index).toString());
        configPanel.removeAll();
        configPanel.repaint();
        configPanel.add(new JLabel("nice"));
        configPanel.repaint();
        }
    }

I threw in the second repaint simply because I was out of things to try, however it still did not work.

Body:
When you add components to a visible GUI the basic logic is:

panel.remove(...);
panel.add(...);
panel.revalidate();
panel.repaint();

Basically all components have a size of (0, 0) when they are created so there is nothing to paint. You need to invoke revalidate() so the layout manager can give the components a size and location on the panel.


问:
Alternative to Akka for handling tasks sequentially
I have a system which may generate certain events in the lifecycle of a transaction. On every even I need to update a row in a DB and also send out a UI event over websocket.

One option I have is to implement the event processing (DB and UI) in actors thus avoiding any locking issues - also I can afford minor delays so handling this sequentially will greatly simplify matters.

What are alternative ways of handling this in Scala as I feel maybe Actors might be overkill in this case?
There are those blogs stating that actors should be used for "concurrency with state" - though I would like to see a more appropriate mechanism in order to eliminate this option.

答:
Ultimately the main unique benefit for using actors is that they are great for encapsulating mutable variables so that you avoid race conditions.

To do what you describe, you could just use classic threads. In your (possibly simplified) description, I don't see the potential for deadlocks. If you want to something a bit more composable, e.g. a sequence of asynchronous tasks, you can use Scala's Futures.


问:
Accessing Variable inside Inner Class
I have a listener and I want to access variable outside the listener method. But even after initializing the variable globally its showing "0" outside scope.

Can anyone explain the reason

```<code>public class MapsActivity{
   double origin_lat;
   //
   @Override
   public void onMapReady(GoogleMap googleMap) {
       //
       srcLat.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            double value = (double) dataSnapshot.getValue();
            origin_lat=value;  -- > value shows here
            Log.d("SourceLatitude",Double.toString(value));

        }
       });
   Log.d("OutsideScope",Double.toString(origin_lat)); -- > shows "0"
   }
 }
</code>```

答:
This is what you are telling the app to do:

When Map is ready, add a ListenerForSingleValueEvent to srcLat and print the current value of origin_lat

From now on, when data changes (onDataChange is called on that newly added listener), you want to change the value of origin_lat and print that.

Note that in step 1, the value of origin_lat has not (necessarily) yet been modified by onDataChange because onDataChange has not been called yet. Once that happens,  origin_lat will change.

As Blackbelt says, you seem to  think the code runs sequentially because it is written sequentially. Buy you added an async listener of some sort, and that will run whenever it wants.

Title: Accessing Variable inside Inner Class

Body:
I have a listener and I want to access variable outside the listener method. But even after initializing the variable globally its showing "0" outside scope.

Can anyone explain the reason

public class MapsActivity{
   double origin_lat;
   //
   @Override
   public void onMapReady(GoogleMap googleMap) {
       //
       srcLat.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            double value = (double) dataSnapshot.getValue();
            origin_lat=value;  -- > value shows here
            Log.d("SourceLatitude",Double.toString(value));

        }
       });
   Log.d("OutsideScope",Double.toString(origin_lat)); -- > shows "0"
   }
 }


问:
How can get Note's position which in SketchBlock(SolidWorks)
I trying to get text and position of all Notes from draw.
I could that except what be in block.

When i get Notes from block, To get text is successful But coordinates are weird.

```<code>      SketchManager swSketch = swModel.SketchManager;
      var blocks = swSketch.GetSketchBlockDefinitions();
      for (int z = 0; z < blocks.Length; z++)
      {
           SketchBlockDefinition block = blocks[z];
           var swNotes = block.GetNotes();

           for (int x = 0; x < swNotes.Length; x++)
           {
               PosX = "";
               PosY = "";
               displayText = "";
               Note swBlockNote = swNotes[x];

               swAnn = swBlockNote.GetAnnotation();
               swDispData = swAnn.GetDisplayData();

               dPoint = swDispData.GetTextPositionAtIndex(0);
               dPoint[0] = dPoint[0] * 1000;
               dPoint[1] = dPoint[1] * 1000;
               PosX_num = dPoint[0].ToString("########0.#########");
               PosY_num = dPoint[1].ToString("########0.#########");
           }
      }
</code>```

That triangle is block and have note text "A123"
also have position 72.29mm, 227.559mm

But The triangle's position is X:0.002375 Y:-0.02656 When i try getting in program.

Can i get some idea, Waiting your help sincerely. Thank you.

答:
BlockDefinitions is just definition.
I had to get BlockInstances like this.

```<code>Sketch sktch = swView.GetSketch();
var blockInstance = sktch.GetSketchBlockInstances();
</code>```

Then i could get Block's position.
But we should be careful that block position which get from block instance based view's position.

for example, if you range a block to view which have position 0, 0 you can get right block position just try to get position from blockinstance.

But if you range a block to view which have position, you must sum view's position to blocinstance's position.
Also, Note's Positions are same. Notes in block are have position based BlcokDefinition.

Just refer this sample code because i can't explain well with English.

```<code>Sketch sktch = swView.GetSketch();
var blockInstance = sktch.GetSketchBlockInstances();
if (blockInstance != null)
{
    double[] blockPos = null;
    double[] viewPos = null;
    for (int instanceCnt = 0; instanceCnt < blockInstance.Length; instanceCnt++)
    {
         SketchBlockInstance instance = blockInstance[instanceCnt];
         SketchBlockDefinition block = instance.Definition;
         MathPoint InstanceMP = instance.InstancePosition;
         blockPos = InstanceMP.ArrayData;
         viewPos = swView.Position;
         var swNotes = block.GetNotes();
         for (int x = 0; x < swNotes.Length; x++)
         {
              Note swBlockNote = swNotes[x];

              swAnn = swBlockNote.GetAnnotation();
              swDispData = swAnn.GetDisplayData();
              dPoint = swDispData.GetTextPositionAtIndex(0);
              dPoint[0] = (dPoint[0] * 1000) + (blockPos[0] * 1000) + (viewPos[0] * 1000);
              dPoint[1] = (dPoint[1] * 1000) + (blockPos[1] * 1000) + (viewPos[1] * 1000);
         }
     }
}
</code>```

Body:
I trying to get text and position of all Notes from draw.
I could that except what be in block.

When i get Notes from block, To get text is successful But coordinates are weird.

      SketchManager swSketch = swModel.SketchManager;
      var blocks = swSketch.GetSketchBlockDefinitions();
      for (int z = 0; z < blocks.Length; z++)
      {
           SketchBlockDefinition block = blocks[z];
           var swNotes = block.GetNotes();

           for (int x = 0; x < swNotes.Length; x++)
           {
               PosX = "";
               PosY = "";
               displayText = "";
               Note swBlockNote = swNotes[x];

               swAnn = swBlockNote.GetAnnotation();
               swDispData = swAnn.GetDisplayData();

               dPoint = swDispData.GetTextPositionAtIndex(0);
               dPoint[0] = dPoint[0] * 1000;
               dPoint[1] = dPoint[1] * 1000;
               PosX_num = dPoint[0].ToString("########0.#########");
               PosY_num = dPoint[1].ToString("########0.#########");
           }
      }

That triangle is block and have note text "A123"
also have position 72.29mm, 227.559mm

But The triangle's position is X:0.002375 Y:-0.02656 When i try getting in program.

Can i get some idea, Waiting your help sincerely. Thank you.

Body:
BlockDefinitions is just definition.
I had to get BlockInstances like this.

Sketch sktch = swView.GetSketch();
var blockInstance = sktch.GetSketchBlockInstances();

Then i could get Block's position.
But we should be careful that block position which get from block instance based view's position.

for example, if you range a block to view which have position 0, 0 you can get right block position just try to get position from blockinstance.

But if you range a block to view which have position, you must sum view's position to blocinstance's position.
Also, Note's Positions are same. Notes in block are have position based BlcokDefinition.

Just refer this sample code because i can't explain well with English.

Sketch sktch = swView.GetSketch();
var blockInstance = sktch.GetSketchBlockInstances();
if (blockInstance != null)
{
    double[] blockPos = null;
    double[] viewPos = null;
    for (int instanceCnt = 0; instanceCnt < blockInstance.Length; instanceCnt++)
    {
         SketchBlockInstance instance = blockInstance[instanceCnt];
         SketchBlockDefinition block = instance.Definition;
         MathPoint InstanceMP = instance.InstancePosition;
         blockPos = InstanceMP.ArrayData;
         viewPos = swView.Position;
         var swNotes = block.GetNotes();
         for (int x = 0; x < swNotes.Length; x++)
         {
              Note swBlockNote = swNotes[x];

              swAnn = swBlockNote.GetAnnotation();
              swDispData = swAnn.GetDisplayData();
              dPoint = swDispData.GetTextPositionAtIndex(0);
              dPoint[0] = (dPoint[0] * 1000) + (blockPos[0] * 1000) + (viewPos[0] * 1000);
              dPoint[1] = (dPoint[1] * 1000) + (blockPos[1] * 1000) + (viewPos[1] * 1000);
         }
     }
}


问:
Laravel: Where selection for Eloquent Eager Loading relationship
I got two DB tables:

Posts

```<code>$table->increments('id');
$table->integer('country_id')->unsigned();
$table->foreign('country_id')->references('id')->on('countries');
</code>```

Countries

```<code>$table->increments('id');
$table->string('name', 70);
</code>```

I use laravel as back-end. Now I want to implement filtering data for my front-end. So the user can select a country name and laravel should answer the request only with posts that have a country with the specified name.

How could I add this condition to my existing pagination query? I tried this:

```<code>$query = app(Post::class)->with('country')->newQuery();
// ...
if ($request->exists('country')) {
        $query->where('country.name', $request->country);
}
// ...
</code>```

... resulting in the following error:

```<code>Column not found: 1054 Unknown column 'country.name' in 'where clause' (SQL: select count(*) as aggregate from `posts` where `country`.`name` = Albania)
</code>```

答:
whereHas method accepts parameter as per Laravel code base,

```<code> /**
 * Add a relationship count / exists condition to the query with where clauses.
 *
 * @param  string  $relation
 * @param  \Closure|null  $callback
 * @param  string  $operator
 * @param  int     $count
 * @return \Illuminate\Database\Eloquent\Builder|static
 */
public function whereHas($relation, Closure $callback = null, $operator = '>=', $count = 1)
{
    return $this->has($relation, $operator, $count, 'and', $callback);
}
</code>```

so Changing the code a little as,

```<code>$query = ""

if ($request->has('country'){
$query = Post::with("country")->whereHas("country",function($q) use($request){
    $q->where("name","=",$request->country);
})->get()
}else{
    $query = Post::with("country")->get();
}
</code>```

By the way above code can be a little simplified as follow;

```<code>$query = ""

if ($request->has('country'){
  $query = Post::with(["country" => function($q) use($request){
  $q->where("name","=",$request->country);
}])->first()
}else{
  $query = Post::with("country")->get();
</code>```

}

Body:
I got two DB tables:

Posts

$table->increments('id');
$table->integer('country_id')->unsigned();
$table->foreign('country_id')->references('id')->on('countries');

Countries

$table->increments('id');
$table->string('name', 70);

I use laravel as back-end. Now I want to implement filtering data for my front-end. So the user can select a country name and laravel should answer the request only with posts that have a country with the specified name.

How could I add this condition to my existing pagination query? I tried this:

$query = app(Post::class)->with('country')->newQuery();
// ...
if ($request->exists('country')) {
        $query->where('country.name', $request->country);
}
// ...

... resulting in the following error:

Column not found: 1054 Unknown column 'country.name' in 'where clause' (SQL: select count(*) as aggregate from `posts` where `country`.`name` = Albania)

Body:
whereHas method accepts parameter as per Laravel code base,

 /**
 * Add a relationship count / exists condition to the query with where clauses.
 *
 * @param  string  $relation
 * @param  \Closure|null  $callback
 * @param  string  $operator
 * @param  int     $count
 * @return \Illuminate\Database\Eloquent\Builder|static
 */
public function whereHas($relation, Closure $callback = null, $operator = '>=', $count = 1)
{
    return $this->has($relation, $operator, $count, 'and', $callback);
}

so Changing the code a little as,

$query = ""

if ($request->has('country'){
$query = Post::with("country")->whereHas("country",function($q) use($request){
    $q->where("name","=",$request->country);
})->get()
}else{
    $query = Post::with("country")->get();
}

By the way above code can be a little simplified as follow;

$query = ""

if ($request->has('country'){
  $query = Post::with(["country" => function($q) use($request){
  $q->where("name","=",$request->country);
}])->first()
}else{
  $query = Post::with("country")->get();

}


问:
benefits of "HTTP authentication with PHP"
what are the benefits of using HTTP authentication with PHP (HTTP 401 headers)

instead of using a normal form submit authentication??

答:
Your question is a bit vague, but the general answer is that using this method gives you a more "RESTful" implementation that follows what HTTP is already good at.  In this case, throwing a 401 is something that other web servers, web proxies and web browsers know how to handle.  If you're just spitting out an HTML form it is only actionable by an end user whereas using the HTTP status codes allow machine interaction.

I'd recommend checking out http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol to understand what HTTP really is.  I think that should make all of this make more sense.

OwnerDisplayName: revolutiontrigger


问:
I need help with forms submit, please read for details
I would like to create a form where the user can put a number in like "12345" and when the submit button is clicked have the result be http://www.URL.com/12345</p>

答:
Here's the jQuery version separating the events from the markup. Demo can be seen here

```<code><html>
<head>
    <script type="text/javascript" src="jquery-1.4.2.js"></script>
    <script>
      var url="http://www.url.com/";
      $(document).ready(function(){$("#go").click(function(){
           url+=$("#parameter").val()
           window.location=url;
           });
       });
    </script>
</head>
<body>
    <input type="text" id="parameter"/>
    <button id="go">Go</button>
</body>
</code>```

Body:
Here's the jQuery version separating the events from the markup. Demo can be seen here

<html>
<head>
    <script type="text/javascript" src="jquery-1.4.2.js"></script>
    <script>
      var url="http://www.url.com/";
      $(document).ready(function(){$("#go").click(function(){
           url+=$("#parameter").val()
           window.location=url;
           });
       });
    </script>
</head>
<body>
    <input type="text" id="parameter"/>
    <button id="go">Go</button>
</body>


问:
move backButton from default UINavigationbar to customNavigationbar in swift
In viewWillAppear i hide my navigationController and navigationBar like this:

```<code>override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: true)
        self.navigationController?.interactivePopGestureRecognizer?.delegate = nil
}
</code>```

Then i added a navigationBar in my Storyboard and connected it to an IBOutlet in my UIViewController to customize it from IB.

Everything is working fine except i can not move default backButton from the original hidden navigatioBar to my new custom navigationBar.

Question:

Is there a way to move backButton from default navigationBar to this new custom navigationBar?**

Note: I don't want to add a customized back button.

答:
You can't. You'd need to create your own UIBarButtonItem</p>

```<code>let backItem = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(yourSelector))
self.navigationItem.leftBarButtonItem = backItem
</code>```

Body:
In viewWillAppear i hide my navigationController and navigationBar like this:

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: true)
        self.navigationController?.interactivePopGestureRecognizer?.delegate = nil
}

Then i added a navigationBar in my Storyboard and connected it to an IBOutlet in my UIViewController to customize it from IB.

Everything is working fine except i can not move default backButton from the original hidden navigatioBar to my new custom navigationBar.

Question:

Is there a way to move backButton from default navigationBar to this new custom navigationBar?**

Note: I don't want to add a customized back button.

Body:
You can't. You'd need to create your own UIBarButtonItem

let backItem = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(yourSelector))
self.navigationItem.leftBarButtonItem = backItem


问:
UGLY BORDER bug, position:relative > position:absolute > border-radius:50% , see fiddle
https://jsfiddle.net/0h3rqqru/

```<code><div style="position:relative; width:500px; height:500px; background:blue; border-radius:50%;">
     <span style="position:absolute; width:100%; height:100%; background:white; border-radius:50%;"></span>
</div>
</code>```

My problem is that an odd border is showing up when having a position:absolute inside of a position:relative with border-radius:50%.

Been searching for hours for a solution for this but been unable to find an answer.

Ive been working for Days building something slightly more advanced, a "pie chart". Everything works besides this border issue. Without a solution to the border problem, i might aswell throw it all in the trash ;'(.

Bug visible in: Edge and Chrome, and also visible in firefox if you apply: transform:rotate(90deg), to the absolute element.

UPDATE

Ive created a codepen with the pie chart to show more specifically what I'm trying solve:
https://codepen.io/anon/pen/evXJPw

答:
Remove background:blue; from your outer container.
Or if you really want that background color there. Make sure the positioning is dead on then use a 1px border to hide the background gap. Looking good in FF here http://codepen.io/anon/pen/MpLqPd

Alternatively use SVG, much better for circles.

```<code>.outer{
  position:relative;
  width:500px;
  height:500px;
  background:blue;
  border-radius:50%;
}
.inner{
  position:absolute;
  top: 50%;
  left: 50%;
  transform: ;
  width:100%;
  height:100%;
  background:#e3e3e3;
  border-radius:50%;
  border: 1px solid #e3e3e3;
}
.seeInfirefox{
  transform-origin: 50% 50%;
  transform:translateX(-50%)translateY(-50%)rotate(90deg);
}
</code>```

Body:
https://jsfiddle.net/0h3rqqru/

My problem is that an odd border is showing up when having a position:absolute inside of a position:relative with border-radius:50%.

Been searching for hours for a solution for this but been unable to find an answer.

Ive been working for Days building something slightly more advanced, a "pie chart". Everything works besides this border issue. Without a solution to the border problem, i might aswell throw it all in the trash ;'(.

Bug visible in: Edge and Chrome, and also visible in firefox if you apply: transform:rotate(90deg), to the absolute element.

UPDATE

Ive created a codepen with the pie chart to show more specifically what I'm trying solve:
https://codepen.io/anon/pen/evXJPw

Body:
Remove background:blue; from your outer container.
Or if you really want that background color there. Make sure the positioning is dead on then use a 1px border to hide the background gap. Looking good in FF here http://codepen.io/anon/pen/MpLqPd

Alternatively use SVG, much better for circles.

.outer{
  position:relative;
  width:500px;
  height:500px;
  background:blue;
  border-radius:50%;
}
.inner{
  position:absolute;
  top: 50%;
  left: 50%;
  transform: ;
  width:100%;
  height:100%;
  background:#e3e3e3;
  border-radius:50%;
  border: 1px solid #e3e3e3;
}
.seeInfirefox{
  transform-origin: 50% 50%;
  transform:translateX(-50%)translateY(-50%)rotate(90deg);
}


问:
Excel Combine two columns in call to function?
My spreadsheet looks like this:

I have two lists of dates, I want to get all unique dates between Dates1 and Dates2 and put them in column C.

I can get unique dates in column A with UNIQUE(A2:A4), but I want all unique dates between both columnms. When I try to do =UNIQUE(A2:A4,B2:B5) I get the error:

Wrong number of arguments to UNIQUE. Expected 1 arguments, but got 2 arguments.

How can I get all unique dates between both? I've also tried concatenate, but that just gives me a huge number, not a row of dates.

Thanks!

答:
Use iferror to pass processing to a second version of a 'unique list' formula with different columns.

```<code>=IFERROR(INDEX(A$2:INDEX(A:A, MATCH(1E+99, A:A)), MATCH(0, COUNTIF(D$1:D1, A$2:INDEX(A:A, MATCH(1E+99, A:A))), 0)),
 IFERROR(INDEX(B$2:INDEX(B:B, MATCH(1E+99, B:B)), MATCH(0, COUNTIF(D$1:D1, B$2:INDEX(B:B, MATCH(1E+99, B:B))), 0)), TEXT(,)))
</code>```

Turns out (thanks to Keatinge) that UNIQUE takes an array of ranges separated by a semi-colon and wrapped in braces. Putting the range limiters from my own solution in achieves:

```<code>=unique({A$2:INDEX(A:A, MATCH(1E+99, A:A));C$2:INDEX(C:C, MATCH(1E+99, C:C))})
</code>```

That sample google-sheets is here.

Body:
Use iferror to pass processing to a second version of a 'unique list' formula with different columns.

=IFERROR(INDEX(A$2:INDEX(A:A, MATCH(1E+99, A:A)), MATCH(0, COUNTIF(D$1:D1, A$2:INDEX(A:A, MATCH(1E+99, A:A))), 0)),
 IFERROR(INDEX(B$2:INDEX(B:B, MATCH(1E+99, B:B)), MATCH(0, COUNTIF(D$1:D1, B$2:INDEX(B:B, MATCH(1E+99, B:B))), 0)), TEXT(,)))

Turns out (thanks to Keatinge) that UNIQUE takes an array of ranges separated by a semi-colon and wrapped in braces. Putting the range limiters from my own solution in achieves:

=unique({A$2:INDEX(A:A, MATCH(1E+99, A:A));C$2:INDEX(C:C, MATCH(1E+99, C:C))})

That sample google-sheets is here.


问:
Xcode 8 hangs / unresponsive when opening storyboard
I've recently upgraded to Xcode 8 and updated my project to Swift 3. All worked fine for a little while. Storyboard loading has always been slow (even when still running Xcode 7) and was about the same 'slow' with Xcode 8. I always imagined this is because I'm on a older (late 2011) Macbook Pro.

But recently sometimes Xcode would just hang when I tried to open the storyboard. And since yesterday it's ALWAYS 'hanging'. Xcode becomes unresponsive and I have to Force Quit it.

In Activity Monitor I see Xcode using 102% CPU and Memory usage just keeps on growing (over 10GB if I let it).

Now I'm really stuck because when I open Xcode it immediately opens my project and wants to open the storyboard. I can't even change to a swift file. I'm not getting the window where I choose my project anymore. So, can't open my project anymore without Xcode turning unresponsive. Even when I double click another project to open Xcode it still tries to open my project (on the storyboard).

I've tried a number of things (based on SO threads I could find on similar problems with older versions of Xcode):

Removed Xcode and removed contents of ˜/Library/Developer. Then reinstalled Xcode.

Removed contents of var/folders

Removed contents of derived data folder

Restart Macbook

My next try is going to be to download the Xcode 8.1 beta. But really rather not do that.

Any other suggestions on things I could try?

SMALL UPDATE:
Managed to clear the 'state' of Xcode where it opens my project by default and also opens it on the storyboard. Did this by:

Removing the ~/Library/Saved Application State/com.apple.dt.Xcode.savedState folder (this will show the recent project window again on startup)

To also prevent the project from loading a specific file upon opening I went to the contents of .xcworkspace (in my project folder) and then removed /xcuserdata/myusername.xcuserdatad/UserInterfaceState.xcuserstate. Now the project opened without any file selected.

Still... the main problem remains. When I click on my storyboard Xcode becomes unresponsive.

答:
I just upgraded to Xcode 8.3 and this storyboard hanging issue came...I've tried all that mentioned above, none of them works.

Finally I noticed there's some auto-layout warning saying that one of the navigation controller scene's navigation bar size is not correct. It insists that its width should be 320 while the chosen device is iPhone 7. I switched back to Xcode 8.2.1(8.3 is just too slow to change anything!), then changed the viewing device to iPhone SE...all fixed!


问:
want to hide image when image is not found at the src location?
```<code>jQuery('img').bind('error',function(){
            alert('hi');
        jQuery(this).hide();
        });
</code>
```

I have written this code but non available images are not hiding and still showing cross sign. Can anybody point out what can be wrong. I am writing this under document.ready and i have tried it under window.onload as well.

答:
The problem seems to be that by the time you bind your error event, the image's onerror has already fired. You can fire it again by resetting the img.src after binding the event. The following worked on IE8, FF, and Chrome.

```<code>$('img').error(function(){
    alert('hi');
    $(this).hide();
});

$('img').each(function() { this.src = this.src; });
</code>```

jsFiddle is here: http://jsfiddle.net/7cnQN/

Body:
jQuery('img').bind('error',function(){
            alert('hi');
        jQuery(this).hide();
        });

I have written this code but non available images are not hiding and still showing cross sign. Can anybody point out what can be wrong. I am writing this under document.ready and i have tried it under window.onload as well.

Body:
The problem seems to be that by the time you bind your error event, the image's onerror has already fired. You can fire it again by resetting the img.src after binding the event. The following worked on IE8, FF, and Chrome.

$('img').error(function(){
    alert('hi');
    $(this).hide();
});

$('img').each(function() { this.src = this.src; });

jsFiddle is here: http://jsfiddle.net/7cnQN/


问:
What is the best way to delete a component with CLI
I tried using "ng destroy component foo" and it tells me "The destroy command is not supported by Angular-CLI"

How do we properly delete components with Angular CLI?

答:
Currently Angular CLI doesn't support an option to remove the component, you need to do it manually.

Remove import references for every component from app.module

Delete component folders.

You also need to remove the component declaration from @NgModule declaration array in app.module.ts file