答:
You can start by sorting the list of dictionaries on product_name, and then group items based on product_name

Then for each group, calculate the total product and total quantity, create your final dictionary and update to the list, and then make your final dictionary

```<code>from itertools import groupby

dct = {"products_list": [
    {
        "product_cost": 25,
        "product_id": 1,
        "product_name": "Coca-cola",
        "product_quantity": 14,
    },
    {
        "product_cost": 176.74,
        "product_id": 2,
        "product_name": "Apples",
        "product_quantity": 800,

    },
    {
        "product_cost": 13,
        "product_id": 1,
        "product_name": "Coca-cola",
        "product_quantity": 7,
    }
]}

result = {}
li = []

#Sort product list on product_name
sorted_prod_list = sorted(dct['products_list'], key=lambda x:x['product_name'])

#Group on product_name
for model, group in groupby(sorted_prod_list,key=lambda x:x['product_name']):

    grp = list(group)

    #Compute total cost and qty, make the dictionary and add to list
    total_cost = sum(item['product_cost'] for item in grp)
    total_qty = sum(item['product_quantity'] for item in grp)
    product_name = grp[0]['product_name']
    product_id = grp[0]['product_id']

    li.append({'product_name': product_name, 'product_id': product_id, 'product_cost': total_cost, 'product_quantity': total_qty})

#Make final dictionary
result['products_list'] = li

print(result)
</code>```

The output will be

```<code>{
    'products_list': [{
            'product_name': 'Apples',
            'product_id': 2,
            'product_cost': 176.74,
            'product_quantity': 800
        },
        {
            'product_name': 'Coca-cola',
            'product_id': 1,
            'product_cost': 38,
            'product_quantity': 21
        }
    ]
}
</code>```

Title: Group and sum list of dictionaries by parameter

Body:
You can start by sorting the list of dictionaries on product_name, and then group items based on product_name

Then for each group, calculate the total product and total quantity, create your final dictionary and update to the list, and then make your final dictionary

from itertools import groupby

dct = {"products_list": [
    {
        "product_cost": 25,
        "product_id": 1,
        "product_name": "Coca-cola",
        "product_quantity": 14,
    },
    {
        "product_cost": 176.74,
        "product_id": 2,
        "product_name": "Apples",
        "product_quantity": 800,

    },
    {
        "product_cost": 13,
        "product_id": 1,
        "product_name": "Coca-cola",
        "product_quantity": 7,
    }
]}

result = {}
li = []

#Sort product list on product_name
sorted_prod_list = sorted(dct['products_list'], key=lambda x:x['product_name'])

#Group on product_name
for model, group in groupby(sorted_prod_list,key=lambda x:x['product_name']):

    grp = list(group)

    #Compute total cost and qty, make the dictionary and add to list
    total_cost = sum(item['product_cost'] for item in grp)
    total_qty = sum(item['product_quantity'] for item in grp)
    product_name = grp[0]['product_name']
    product_id = grp[0]['product_id']

    li.append({'product_name': product_name, 'product_id': product_id, 'product_cost': total_cost, 'product_quantity': total_qty})

#Make final dictionary
result['products_list'] = li

print(result)

The output will be

{
    'products_list': [{
            'product_name': 'Apples',
            'product_id': 2,
            'product_cost': 176.74,
            'product_quantity': 800
        },
        {
            'product_name': 'Coca-cola',
            'product_id': 1,
            'product_cost': 38,
            'product_quantity': 21
        }
    ]
}


来源: stackexchange

问:
Adding a suffix to names when storing results in a loop
I am making some plots in R in a for-loop and would like to store them using a name to describe the function being plotted, but also which data it came from.

So when I have a list of 2 data sets "x" and "y" and the loop has a structure like this:

```<code>x = matrix(
  c(1,2,4,5,6,7,8,9),
  nrow=3,
  ncol=2)

y = matrix(
  c(20,40,60,80,100,120,140,160,180),
  nrow=3,
  ncol=2)

data <- list(x,y)

for (i in data){
  ??? <- boxplot(i)
}
</code>```

I would like the ??? to be "name" + (i) + "_" separator. In this case the 2 plots would be called "plot_x" and "plot_y".

I tried some stuff with paste("plot", names(i), sep = "_") but I'm not sure if this is what to use, and where and how to use it in this scenario.

答:
akrun is right, you should try to avoid setting names in the global environment.  But if you really have to, you can try this,

```<code>> y = matrix(c(20,40,60,80,100,120,140,160,180),ncol=1)
> .GlobalEnv[[paste0("plot_","y")]] <- boxplot(y)
> str(plot_y)
List of 6
 $ stats: num [1:5, 1] 20 60 100 140 180
 $ n    : num 9
 $ conf : num [1:2, 1] 57.9 142.1
 $ out  : num(0)
 $ group: num(0)
 $ names: chr "1"
</code>```

You can read up on .GlobalEnv by typing in ?.GlobalEnv, into the R command prompt.

ContentLicense: CC BY-SA 4.0

Body:
I am making some plots in R in a for-loop and would like to store them using a name to describe the function being plotted, but also which data it came from.

So when I have a list of 2 data sets "x" and "y" and the loop has a structure like this:

x = matrix(
  c(1,2,4,5,6,7,8,9),
  nrow=3,
  ncol=2)

y = matrix(
  c(20,40,60,80,100,120,140,160,180),
  nrow=3,
  ncol=2)

data <- list(x,y)

for (i in data){
  ??? <- boxplot(i)
}

I would like the ??? to be "name" + (i) + "_" separator. In this case the 2 plots would be called "plot_x" and "plot_y".

I tried some stuff with paste("plot", names(i), sep = "_") but I'm not sure if this is what to use, and where and how to use it in this scenario.

Body:
akrun is right, you should try to avoid setting names in the global environment.  But if you really have to, you can try this,

> y = matrix(c(20,40,60,80,100,120,140,160,180),ncol=1)
> .GlobalEnv[[paste0("plot_","y")]] <- boxplot(y)
> str(plot_y)
List of 6
 $ stats: num [1:5, 1] 20 60 100 140 180
 $ n    : num 9
 $ conf : num [1:2, 1] 57.9 142.1
 $ out  : num(0)
 $ group: num(0)
 $ names: chr "1"

You can read up on .GlobalEnv by typing in ?.GlobalEnv, into the R command prompt.


问:
Where are homebrew services logs
When I run brew services start mosquitto, The service does not start. When I use brew services list, the services has a yellow started status. I want to know why this service start failed, how?

答:
When you see "started" in yellow for a brew service means that the status of the service is "unknown", the started text is printed for retro compatibility.

In your case I suggest to add some log output to your .plist associated file, to edit the correct plist file check the output of "brew services list" command on the mosquitto line you will have the name of the correspondent .plist file, edit that file and add two entries, I print the plist file that I use for my apache installation, please use this file as a guide. check the lines for StandardOutPath and StandardErrorPath and create something similar for your specific case.

After saving the file try to run again the service but this time check the logs associated.
In my experience when you see a yellow started, this means that you have some permissions problem, you can try to save the data associated and reinstall the brew formulae as a second option.

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>homebrew.mxcl.httpd</string>
  <key>ProgramArguments</key>
  <array>
    <string>/usr/local/opt/httpd/bin/httpd</string>
    <string>-D</string>
    <string>FOREGROUND</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
  <key>StandardOutPath</key>
  <string>/usr/local/var/log/hombebrew/httpd/homebrew.mxcl.httpd.log</string>
  <key>StandardErrorPath</key>
  <string>/usr/local/var/log/hombebrew/httpd/homebrew.mxcl.httpd.stderr.log</string>
</dict>
</plist>
</code>```

Title: Where are homebrew services logs

Body:
When you see "started" in yellow for a brew service means that the status of the service is "unknown", the started text is printed for retro compatibility.

In your case I suggest to add some log output to your .plist associated file, to edit the correct plist file check the output of "brew services list" command on the mosquitto line you will have the name of the correspondent .plist file, edit that file and add two entries, I print the plist file that I use for my apache installation, please use this file as a guide. check the lines for StandardOutPath and StandardErrorPath and create something similar for your specific case.

After saving the file try to run again the service but this time check the logs associated.
In my experience when you see a yellow started, this means that you have some permissions problem, you can try to save the data associated and reinstall the brew formulae as a second option.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>homebrew.mxcl.httpd</string>
  <key>ProgramArguments</key>
  <array>
    <string>/usr/local/opt/httpd/bin/httpd</string>
    <string>-D</string>
    <string>FOREGROUND</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
  <key>StandardOutPath</key>
  <string>/usr/local/var/log/hombebrew/httpd/homebrew.mxcl.httpd.log</string>
  <key>StandardErrorPath</key>
  <string>/usr/local/var/log/hombebrew/httpd/homebrew.mxcl.httpd.stderr.log</string>
</dict>
</plist>


问:
how to render multiple json files during spring boot start up
I want to read multiple JSON files at once in a @PostConstruct method.

I gave the path of the parent folder as src/main/resources and I get the file list using the file.listFiles() method.

It worked on Windows but not on Unix. Unix is not able to find the parent folder path for some reason. Any suggestions will be of great help.

答:
If you are coding in Java, always use the forward slash (/) for paths.  This will work on Windows and Linux, etc.  It is OS independent.

Your paths only working on Windows probably means you used () which is Windows-specific.

Note, Windows itself does require () for paths in general, but Java is coded to correctly interpret (/) regardless of underlying OS.


问:
Calling ActionScript from Python. Is that possible?
If swf file is embedded in html it is easy to call ActionScript methods via ExternalInterface using JavaScript.
Now I want to use the swf file outside of a browser and still be able to access its methods, but now I want to use Python to call ActionScript. Is it possible?
There is so little information about it in the Internet.
Probably I can use AMF (pyAmf) for this, can I?

Thanks in advance.

答:
If you want to use the swf in such a manner outside the browser investigate AIR or localconnection.

[Edit] You can use Python to listen for ExternalInterface events. osflash.org has something you could look into, albeit a little outdate:

http://osflash.org/ext_howto

or some example Python:

```<code>def ExternalCall(self,evt):
    print "ExternalCall", evt.request
    ret = "<object><property><string>Sample data</string></property></object>"
    self.movie.SetReturnValue(ret)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If you want to use the swf in such a manner outside the browser investigate AIR or localconnection.

[Edit] You can use Python to listen for ExternalInterface events. osflash.org has something you could look into, albeit a little outdate:

http://osflash.org/ext_howto

or some example Python:

def ExternalCall(self,evt):
    print "ExternalCall", evt.request
    ret = "<object><property><string>Sample data</string></property></object>"
    self.movie.SetReturnValue(ret)


问:
Understand super() in diamond inheritance
I am learning python and started learning MRO in inheritance.

I have read the use of super and the way it can be used however I cannot place my understanding for below question. If it was not super I know B is called. D->B->C->A but when super gets added, I don't know why the output is like this

```<code>class A:
    def test(self):
        print("test of A called")
class B(A):
    def test(self):
        print("test of B called")
        super().test()
class C(A):
    def test(self):
        print("test of C called")
        super().test()
class D(B, C):
    def test2(self):
        print("test of D called")
obj=D()
obj.test()
</code>```

Output

```<code>test of B called
test of C called
test of A called
</code>```

Please help me understand how super is functioning here.

答:
Here is your inheritance hierarchy:

Most of your classes inherit from just one parent class, except D which has two parents. While not explicitly stated, A inherits implicitly from object.

For an object of any class, follow the diagram backwards toward the root to see the order in which Python will check classes to find the method you've invoked. A D instance, for example, will be visited in D, B, C, A, object order. Here B before C because it's listed first in the class definition.

It looks like you've been varying your method names slightly (test2 vs test), which is good practice to see how test is resolved if it is/is not present in various combinations of superclasses.

super() is an explicit request to "invoke the given method from the superclass(es) of the current object."

For further reading, the search terms "Python MRO" should serve you well, leading you to a number of excellent walkthroughs.

Body:
I am learning python and started learning MRO in inheritance.

I have read the use of super and the way it can be used however I cannot place my understanding for below question. If it was not super I know B is called. D->B->C->A but when super gets added, I don't know why the output is like this

class A:
    def test(self):
        print("test of A called")
class B(A):
    def test(self):
        print("test of B called")
        super().test()
class C(A):
    def test(self):
        print("test of C called")
        super().test()
class D(B, C):
    def test2(self):
        print("test of D called")
obj=D()
obj.test()

Output

test of B called
test of C called
test of A called

Please help me understand how super is functioning here.


问:
Get Session ID from login via PHP CURL
I want to login to gounlimited.to via PHP CURL and I want to get after login the value "sess_id" from this page: https://gounlimited.to/?op=upload_file

I have tried the following code without succcess. I won't login:

```<code>$ch = curl_init("http://gounlimited.to/");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1');
curl_setopt($ch, CURLOPT_REFERER, '');
$arr = array('op' => 'login', 'login' => 'XXXX', 'password' => 'XXXX');
curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);
$output = curl_exec($ch);
curl_close($ch);
print_r($output);
</code>```

答:
Try to get the headers as well, add the following options.</p>

```<code>curl_setopt($ch, CURLOPT_HEADER, 1);
</code>```

Title: Get Session ID from login via PHP CURL

Body:
I want to login to gounlimited.to via PHP CURL and I want to get after login the value "sess_id" from this page: https://gounlimited.to/?op=upload_file

I have tried the following code without succcess. I won't login:

$ch = curl_init("http://gounlimited.to/");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1');
curl_setopt($ch, CURLOPT_REFERER, '');
$arr = array('op' => 'login', 'login' => 'XXXX', 'password' => 'XXXX');
curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);
$output = curl_exec($ch);
curl_close($ch);
print_r($output);

Body:
Try to get the headers as well, add the following options.

curl_setopt($ch, CURLOPT_HEADER, 1);


问:
how to query for GET /v2/organizations/:guid/managers using cf-python-client module
I am using cf-python-client module downloaded from this link  and I am trying to get managers of an organization

I am able to get the organisation information by this

client.v2.organizations.get(org_guid) but now I want to get the managers associated with this org and the API required is GET /v2/organizations/:guid/managers but i dont know how to use it through cf-python-client module.

This is how i am connecting to Cloudfoundry

```<code>from cloudfoundry_client.client import CloudFoundryClient
client = CloudFoundryClient(target_endpoint, proxy=proxy, verify=False)
client.init_with_user_credentials( 'admin', 'password' )
</code>```

i tried this client.v2.organizations._get("/"+ORG_GUID+"/managers") and got this
error:

```<code>Traceback (most recent call last):
File "orgs.py", line 31, in <module>
print client.v2.organizations._get("/"+ORG_GUID+"/managers")
File "/usr/local/lib/python2.7/dist-
packages/cloudfoundry_client/v2/entities.py", line 54, in _get
response = self.client.get(url)
File "/usr/local/lib/python2.7/dist-
packages/cloudfoundry_client/client.py", line 167, in get
return CloudFoundryClient._check_response(response)
File "/usr/local/lib/python2.7/dist-
packages/cloudfoundry_client/client.py", line 194, in _check_response
raise InvalidStatusCode(response.status_code, body)
cloudfoundry_client.errors.InvalidStatusCode: 404 : {"code": 10000,
"error_code": "CF-NotFound", "description": "Unknown request"}
</code>```

答:
Try this :)

```<code>from cloudfoundry_client.client import CloudFoundryClient
import os
target_endpoint = '<API_URL>'
proxy = dict(http=os.environ.get('HTTP_PROXY', ''), https=os.environ.get('HTTPS_PROXY', ''))
client = CloudFoundryClient(target_endpoint, proxy=proxy, verify=False)
client.init_with_user_credentials('<EMAIL>', '<PASSWORD>')
org_get = client.v2.organizations.get('<GUID>')
print(org_get)
for m in org_get.managers():
    print(m)
</code>```

Body:
I am using cf-python-client module downloaded from this link  and I am trying to get managers of an organization

I am able to get the organisation information by this

client.v2.organizations.get(org_guid) but now I want to get the managers associated with this org and the API required is GET /v2/organizations/:guid/managers but i dont know how to use it through cf-python-client module.

This is how i am connecting to Cloudfoundry

from cloudfoundry_client.client import CloudFoundryClient
client = CloudFoundryClient(target_endpoint, proxy=proxy, verify=False)
client.init_with_user_credentials( 'admin', 'password' )

i tried this client.v2.organizations._get("/"+ORG_GUID+"/managers") and got this
error:

Traceback (most recent call last):
File "orgs.py", line 31, in <module>
print client.v2.organizations._get("/"+ORG_GUID+"/managers")
File "/usr/local/lib/python2.7/dist-
packages/cloudfoundry_client/v2/entities.py", line 54, in _get
response = self.client.get(url)
File "/usr/local/lib/python2.7/dist-
packages/cloudfoundry_client/client.py", line 167, in get
return CloudFoundryClient._check_response(response)
File "/usr/local/lib/python2.7/dist-
packages/cloudfoundry_client/client.py", line 194, in _check_response
raise InvalidStatusCode(response.status_code, body)
cloudfoundry_client.errors.InvalidStatusCode: 404 : {"code": 10000,
"error_code": "CF-NotFound", "description": "Unknown request"}

Body:
Try this :)

from cloudfoundry_client.client import CloudFoundryClient
import os
target_endpoint = '<API_URL>'
proxy = dict(http=os.environ.get('HTTP_PROXY', ''), https=os.environ.get('HTTPS_PROXY', ''))
client = CloudFoundryClient(target_endpoint, proxy=proxy, verify=False)
client.init_with_user_credentials('<EMAIL>', '<PASSWORD>')
org_get = client.v2.organizations.get('<GUID>')
print(org_get)
for m in org_get.managers():
    print(m)


问:
ReSharper Code Cleanup/Reformat Code feature vs Versioning Control Systems
ReSharper Code cleanup feature (with "reorder members" and "reformat code" enabled) is really great. You define a layout template using XML, then a simple key combination reorganizes your whole source file (or folder/project/solution) according to the rules you set in the template.

Anyway, do you think that could be a problem regarding VCS like subversion, cvs, git, etc. ? Is there a chance that it causes many undesired conflicts ?

Thank you.

答: It can definitely cause conflicts, so I would make sure you don't reformat entire files if there are people working on them in parallel.</p>

OwnerDisplayName: Romain Verdier

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: lassevk

LastEditorDisplayName: Blair Conrad


问:
How to ask user input to draw number of shapes in python turtle?
Write a program that uses turtle graphics to draw multiple equilateral triangles of increasing size, with a common starting point(vertex). The program asks the user for the initial side length, the increase between two consecutive triangles and the total number of triangles to draw. an example of the output when user enters side=50, increase=20 and number of triangles=5

```<code>import turtle
paper = turtle.Screen()
pen = turtle.Turtle()

for x in range(3):
    pen.forward(20)
    pen.left(120)

for x in range(3):
    pen.forward(40)
    pen.left(120)

for x in range(3):
    pen.forward(60)
    pen.left(120)

for x in range(3):
    pen.forward(80)
    pen.left(120)

for x in range(3):
    pen.forward(100)
    pen.left(120)
</code>```

How to ask the user for input?

答:
If you're running Python 3, there's a new way to go about this.  The more recent turtle library adds the numinput() method:

```<code>numinput(title, prompt, default=None, minval=None, maxval=None)
</code>```

So you can do your prompting using a GUI instead of the console.  (There's also a similar textinput() method.)  Here's how your code might look using this approach:

```<code>from turtle import Screen, Pen

paper = Screen()

length = paper.numinput("Triangles", "Enter initial side length:", default=40, minval=10, maxval=70)

increase = paper.numinput("Triangles", "Enter size increase:", default=30, minval=10, maxval=50)

# numinput() returns a float but we need an int for range()
triangles = int(paper.numinput("Triangles", "Enter the desired number of triangles", default=3, minval=1, maxval=5))

pen = Pen()

for triangle in range(triangles):
    for _ in range(3):
        pen.forward(length + triangle * increase)
        pen.left(120)

paper.exitonclick()
</code>```

Body:
Write a program that uses turtle graphics to draw multiple equilateral triangles of increasing size, with a common starting point(vertex). The program asks the user for the initial side length, the increase between two consecutive triangles and the total number of triangles to draw. an example of the output when user enters side=50, increase=20 and number of triangles=5

import turtle
paper = turtle.Screen()
pen = turtle.Turtle()

for x in range(3):
    pen.forward(20)
    pen.left(120)

for x in range(3):
    pen.forward(40)
    pen.left(120)

for x in range(3):
    pen.forward(60)
    pen.left(120)

for x in range(3):
    pen.forward(80)
    pen.left(120)

for x in range(3):
    pen.forward(100)
    pen.left(120)

How to ask the user for input?

Body:
If you're running Python 3, there's a new way to go about this.  The more recent turtle library adds the numinput() method:

numinput(title, prompt, default=None, minval=None, maxval=None)

So you can do your prompting using a GUI instead of the console.  (There's also a similar textinput() method.)  Here's how your code might look using this approach:

from turtle import Screen, Pen

paper = Screen()

length = paper.numinput("Triangles", "Enter initial side length:", default=40, minval=10, maxval=70)

increase = paper.numinput("Triangles", "Enter size increase:", default=30, minval=10, maxval=50)

# numinput() returns a float but we need an int for range()
triangles = int(paper.numinput("Triangles", "Enter the desired number of triangles", default=3, minval=1, maxval=5))

pen = Pen()

for triangle in range(triangles):
    for _ in range(3):
        pen.forward(length + triangle * increase)
        pen.left(120)

paper.exitonclick()


问:
Python Selenium PhantomJS - Extract download link of file that is being downloaded
So as the title suggests, I am trying to get the direct link of a downloading file using PhantomJS through selenium in Python 3.7

The site I am working on is emuparadise.me, I am downloading a rom file with a request to this link after adding a cookie to avoid getting "Invalid Referer" error. When the request is made browser.current_url shows about:blank and I know that the file has started downloading by checking network usage for PhantomJS. Having been browsing the internet for over 3 hours now, I haven't found any way of retrieving the url of the downloading file.

One of my thoughts for a solution was creating a thread for tracking changes to browser.current_url but it seems like browser locks up when making the request

Here is my current code:

```<code>from selenium import webdriver

browser = webdriver.PhantomJS()
browser.add_cookie({'name': 'refexception', 'value': 1, 'domain': '.emuparadise.me', 'path': '/'})
browser.get("https://www.emuparadise.me/roms/get-download.php?gid=154652&test=true")
</code>```

Note that I don't care at all about downloading the file, neither do I know or need to know where it's being downloaded. I've discovered the actual link for that specific example file from firefox in case you need it for testing. I also really prefer using PhantomJS over Firefox or Chrome web drivers for such a simple looking task. Any help would be highly appreciated.

答:
So I finally came up to the solution. Since I know that the download url must be somewhere in the headers of my request, I searched for a way to view them for PhantomJS. It was pretty easy, indeed. All I did was change the log level from INFO(default) to DEBUG and the headers appeared in the log file under the events page.onResourceRequested and page.onResourceReceived. After making the request, I am just parsing the log file looking for the latter event and scraping out the url. Here's the complete code:

```<code>from selenium import webdriver
from json import loads

def get_direct_url_for_game(url):
    browser = webdriver.PhantomJS(service_args=["--webdriver-loglevel=DEBUG"])
    browser.add_cookie({'name': 'refexception', 'value': 1, 'domain': '.emuparadise.me', 'path': '/'})
    browser.get(download_url)

    direct_download_url = None
    with open('ghostdriver.log') as logs:
        for line in logs:
            _, _, event, event_data = line.split(" - ")
            if event == "page.onResourceReceived":
                event_data = loads(event_data)
                if event_data['contentType'] == "application/octet-stream":
                    direct_download_url = event_data['url']
                    browser.quit()
    return direct_download_url

print(get_url_for_game("https://www.emuparadise.me/roms/get-download.php?gid=154652&test=true"))
</code>```

EDIT:

I actually found out a much simpler way of achieving the exact same thing much easier and more elegantly using requests' head function. This is making a request for the HTTP Headers of the url, hence the name, and we will still pass in the same cookie. We will allow redirects since that's what we want and the url will be under the variable url of the request.

Here's a look at it:

```<code>from requests import head

def get_direct_url_for_game(url):
    request = head(game_url, allow_redirects=True, cookies={'refexception': '1'})
    return request.url

print(get_direct_url_for_game("https://www.emuparadise.me/roms/get-download.php?gid=154652&test=true"))
</code>```

Body:
So as the title suggests, I am trying to get the direct link of a downloading file using PhantomJS through selenium in Python 3.7

The site I am working on is emuparadise.me, I am downloading a rom file with a request to this link after adding a cookie to avoid getting "Invalid Referer" error. When the request is made browser.current_url shows about:blank and I know that the file has started downloading by checking network usage for PhantomJS. Having been browsing the internet for over 3 hours now, I haven't found any way of retrieving the url of the downloading file.

One of my thoughts for a solution was creating a thread for tracking changes to browser.current_url but it seems like browser locks up when making the request

Here is my current code:

from selenium import webdriver

browser = webdriver.PhantomJS()
browser.add_cookie({'name': 'refexception', 'value': 1, 'domain': '.emuparadise.me', 'path': '/'})
browser.get("https://www.emuparadise.me/roms/get-download.php?gid=154652&test=true")

Note that I don't care at all about downloading the file, neither do I know or need to know where it's being downloaded. I've discovered the actual link for that specific example file from firefox in case you need it for testing. I also really prefer using PhantomJS over Firefox or Chrome web drivers for such a simple looking task. Any help would be highly appreciated.

Body:
So I finally came up to the solution. Since I know that the download url must be somewhere in the headers of my request, I searched for a way to view them for PhantomJS. It was pretty easy, indeed. All I did was change the log level from INFO(default) to DEBUG and the headers appeared in the log file under the events page.onResourceRequested and page.onResourceReceived. After making the request, I am just parsing the log file looking for the latter event and scraping out the url. Here's the complete code:

from selenium import webdriver
from json import loads

def get_direct_url_for_game(url):
    browser = webdriver.PhantomJS(service_args=["--webdriver-loglevel=DEBUG"])
    browser.add_cookie({'name': 'refexception', 'value': 1, 'domain': '.emuparadise.me', 'path': '/'})
    browser.get(download_url)

    direct_download_url = None
    with open('ghostdriver.log') as logs:
        for line in logs:
            _, _, event, event_data = line.split(" - ")
            if event == "page.onResourceReceived":
                event_data = loads(event_data)
                if event_data['contentType'] == "application/octet-stream":
                    direct_download_url = event_data['url']
                    browser.quit()
    return direct_download_url

print(get_url_for_game("https://www.emuparadise.me/roms/get-download.php?gid=154652&test=true"))

EDIT:

I actually found out a much simpler way of achieving the exact same thing much easier and more elegantly using requests' head function. This is making a request for the HTTP Headers of the url, hence the name, and we will still pass in the same cookie. We will allow redirects since that's what we want and the url will be under the variable url of the request.

Here's a look at it:

from requests import head

def get_direct_url_for_game(url):
    request = head(game_url, allow_redirects=True, cookies={'refexception': '1'})
    return request.url

print(get_direct_url_for_game("https://www.emuparadise.me/roms/get-download.php?gid=154652&test=true"))


问:
Group and sum list of dictionaries by parameter
I have a list of dictionaries of my products (drinks, food, etc), some of the products may be added several times. I need to group my products by product_id parameter and sum product_cost and product_quantity of each group to get the total product price.

I'm a newbie in python, understand how to group list of dictionaries but can't figure out how to sum some parameter values.

```<code>"products_list": [
    {
        "product_cost": 25,
        "product_id": 1,
        "product_name": "Coca-cola",
        "product_quantity": 14,
    },
    {
        "product_cost": 176.74,
        "product_id": 2,
        "product_name": "Apples",
        "product_quantity": 800,

    },
    {
        "product_cost": 13,
        "product_id": 1,
        "product_name": "Coca-cola",
        "product_quantity": 7,
    }
]
</code>```

I need to achieve something like that:

```<code>"products_list": [
    {
        "product_cost": 38,
        "product_id": 1,
        "product_name": "Coca-cola",
        "product_quantity": 21,
    },
    {
        "product_cost": 176.74,
        "product_id": 2,
        "product_name": "Apples",
        "product_quantity": 800,

    }
]
</code>```

答:
Me personally I would reorganize it in to another dictionary by unique identifiers.  Also, if you still need it in the list format you can still reorganize it in a dictionary, but you can just convert the dict.values() in to a list.  Below is a function that does that.

```<code>def get_totals(product_dict):
    totals = {}
    for product in product_list["product_list"]:
        if product["product_name"]  not in totals:
            totals[product["product_name"]] = product
        else:

            totals[product["product_name"]]["product_cost"] += product["product_cost"]
            totals[product["product_name"]]["product_quantity"] += product["product_quantity"]

    return list(totals.values())
</code>```

output is:

```<code>[
 {
  'product_cost': 38,
  'product_id': 1,
  'product_name': 'Coca-cola',
  'product_quantity': 21
 },
 {
  'product_cost': 176.74,
  'product_id': 2,
  'product_name': 'Apples',
  'product_quantity': 800
 }
]
</code>```

Now if you need it to belong to a product list key.  Just reassign the list to the same key.  Instead of returning list(total.values()) do

```<code>product_dict["product_list"] = list(total.values())
return product_dict
</code>```

The output is a dictionary like:

```<code>{
 "products_list": [
   {
    "product_cost": 38,
    "product_id": 1,
    "product_name": "Coca-cola",
    "product_quantity": 21,
   },
   {
    "product_cost": 176.74,
    "product_id": 2,
    "product_name": "Apples",
    "product_quantity": 800,

   }
 ]
}
</code>```

Body:
I have a list of dictionaries of my products (drinks, food, etc), some of the products may be added several times. I need to group my products by product_id parameter and sum product_cost and product_quantity of each group to get the total product price.

I'm a newbie in python, understand how to group list of dictionaries but can't figure out how to sum some parameter values.

"products_list": [
    {
        "product_cost": 25,
        "product_id": 1,
        "product_name": "Coca-cola",
        "product_quantity": 14,
    },
    {
        "product_cost": 176.74,
        "product_id": 2,
        "product_name": "Apples",
        "product_quantity": 800,

    },
    {
        "product_cost": 13,
        "product_id": 1,
        "product_name": "Coca-cola",
        "product_quantity": 7,
    }
]

I need to achieve something like that:

"products_list": [
    {
        "product_cost": 38,
        "product_id": 1,
        "product_name": "Coca-cola",
        "product_quantity": 21,
    },
    {
        "product_cost": 176.74,
        "product_id": 2,
        "product_name": "Apples",
        "product_quantity": 800,

    }
]

Body:
Me personally I would reorganize it in to another dictionary by unique identifiers.  Also, if you still need it in the list format you can still reorganize it in a dictionary, but you can just convert the dict.values() in to a list.  Below is a function that does that.

def get_totals(product_dict):
    totals = {}
    for product in product_list["product_list"]:
        if product["product_name"]  not in totals:
            totals[product["product_name"]] = product
        else:

            totals[product["product_name"]]["product_cost"] += product["product_cost"]
            totals[product["product_name"]]["product_quantity"] += product["product_quantity"]

    return list(totals.values())

output is:

[
 {
  'product_cost': 38,
  'product_id': 1,
  'product_name': 'Coca-cola',
  'product_quantity': 21
 },
 {
  'product_cost': 176.74,
  'product_id': 2,
  'product_name': 'Apples',
  'product_quantity': 800
 }
]

Now if you need it to belong to a product list key.  Just reassign the list to the same key.  Instead of returning list(total.values()) do

product_dict["product_list"] = list(total.values())
return product_dict

The output is a dictionary like:

{
 "products_list": [
   {
    "product_cost": 38,
    "product_id": 1,
    "product_name": "Coca-cola",
    "product_quantity": 21,
   },
   {
    "product_cost": 176.74,
    "product_id": 2,
    "product_name": "Apples",
    "product_quantity": 800,

   }
 ]
}


问:
modifying class private variable using reference variable
I was playing with reference variable. And I learned that I am able to directly modify class private variable from outside of class using its reference.
Here's the code:

```<code>#include <iostream>
using namespace std;
#define print(x) cout<<x<<endl;

class prison
{
private:
    int victim;

public:
    prison(int ele)
    {
        victim = ele;
    }

    int & lophol()
    {
        return victim;
    }

    void info()
    {
        print(victim)
    }
};

int main()
{
    prison sam{0};
    int &culprit = sam.lophol();
    culprit++;
    culprit++;
    sam.info();
}
Output:
$$ g++ -std=c++11 exp.cpp && ./a.out
2
</code>```

I can access private variable via reference.
Is this behavior OK?

答: Technically, accessing a private variable through a reference works - even from outside the class. However, keep in mind that leaking a reference to a private variable to the outside world is in conflict with the idea of "private". Read the section about minimizing exposure to members in the C++ Core Guidelines for some reasons why you want to keep members private.</p>

Body:
I was playing with reference variable. And I learned that I am able to directly modify class private variable from outside of class using its reference.
Here's the code:

#include <iostream>
using namespace std;
#define print(x) cout<<x<<endl;

class prison
{
private:
    int victim;

public:
    prison(int ele)
    {
        victim = ele;
    }

    int & lophol()
    {
        return victim;
    }

    void info()
    {
        print(victim)
    }
};

int main()
{
    prison sam{0};
    int &culprit = sam.lophol();
    culprit++;
    culprit++;
    sam.info();
}
Output:
$$ g++ -std=c++11 exp.cpp && ./a.out
2

I can access private variable via reference.
Is this behavior OK?


问:
Unable to read serial/uart pins on NodeMCU
I am unable to read the serial pins in the NodeMCU Lua environment. I have only been able to read the USB serial port.

I have connected a serial adapter to the rx, tx, and g pins.

I have tried this code:

```<code>uart.on("data","\n",function(data) print("receive from uart:", data) end, 0)
</code>```

I enter text in the ESplorer console and it does read that. It doesn't read anything I send over a serial adapter plugged into the rx/tx/g pins.

uart.write(0, "hello")
```

I disconnected the USB cable and powered it with the serial adapter. Nothing was sent using this code. I tried uart.write(0, and uart.write(1,.

How do I read the pin serial ports instead of the usb serial port?

答:
I needed to unplug the USB cable. The device gets confused if the USB cable is plugged in and you're trying to use the pin serial port.

See my question on the esp forums:
https://www.esp8266.com/viewtopic.php?f=22&t=19768

Body:
I am unable to read the serial pins in the NodeMCU Lua environment. I have only been able to read the USB serial port.

I have connected a serial adapter to the rx, tx, and g pins.

I have tried this code:

uart.on("data","\n",function(data) print("receive from uart:", data) end, 0)

I enter text in the ESplorer console and it does read that. It doesn't read anything I send over a serial adapter plugged into the rx/tx/g pins.

uart.write(0, "hello")

I disconnected the USB cable and powered it with the serial adapter. Nothing was sent using this code. I tried uart.write(0, and uart.write(1,.

How do I read the pin serial ports instead of the usb serial port?


问:
Core Data `deleteObject:` problem!
I have the following entities in core data as shown in the figure below.

The delete rule for all the relationship is cascade.

Questions:
When ever i delete the any one of the entity object at level 2 and do [context save:&error]; all other objects in Table Entity1 gets the data fault and the app crashes due to not able to read the Entity1 object any more, giving EXC_BAD_ACCESS error.

I am using this code

```<code>for(Entity1 *entity in listOfEntitys)
{
    if(entity.Relation1)
        [context deleteObject:entity.Relation1];

    if(entity.Relation2)
        [context deleteObject:entity.Relation2];

    if(entity.Relation3)
        [context deleteObject:entity.Relation3];
}
[context save:&error];
</code>```

Its not like I have never deleted any object from core data but this is the only place where problem is occurring. Can anyone Help.

Thanks.

PS. I have seen other questions on SO but none has the same kind of situation as i do.

Edit:

My problem is that when I try to delete any one object from level 2 then all the objects in the entity1 are getting data fault. some thing like this.

```<code>Printing description of listOfEntitys:
(
    "<Entity1: 0x4dc3d80> (entity: Entity1; id: 0x4dc2d60 <x-coredata://DF11191D-0BE9-4A63-955D-0A43153290A4/Entity1/p5> ; data: <fault>)",
    "<Entity1: 0x5b06ea0> (entity: Entity1; id: 0x5b077d0 <x-coredata://DF11191D-0BE9-4A63-955D-0A43153290A4/Entity1/p6> ; data: <fault>)",
    "<Entity1: 0x4dc2cf0> (entity: Entity1; id: 0x4dc2df0 <x-coredata://DF11191D-0BE9-4A63-955D-0A43153290A4/Entity1/p7> ; data: <fault>)",
    "<Entity1: 0x4dc2b80> (entity: Entity1; id: 0x4dc3640 <x-coredata://DF11191D-0BE9-4A63-955D-0A43153290A4/Entity1/p8> ; data: <fault>)"
)
</code>```

答: Don't set the inverses to cascade, cause it's like a lit fuse burning down in every direction. Set them to nullify. </p>

Title: Core Data `deleteObject:` problem!

Body:
I have the following entities in core data as shown in the figure below.

The delete rule for all the relationship is cascade.

Questions:
When ever i delete the any one of the entity object at level 2 and do [context save:&error]; all other objects in Table Entity1 gets the data fault and the app crashes due to not able to read the Entity1 object any more, giving EXC_BAD_ACCESS error.

I am using this code

for(Entity1 *entity in listOfEntitys)
{
    if(entity.Relation1)
        [context deleteObject:entity.Relation1];

    if(entity.Relation2)
        [context deleteObject:entity.Relation2];

    if(entity.Relation3)
        [context deleteObject:entity.Relation3];
}
[context save:&error];

Its not like I have never deleted any object from core data but this is the only place where problem is occurring. Can anyone Help.

Thanks.

PS. I have seen other questions on SO but none has the same kind of situation as i do.

Edit:

My problem is that when I try to delete any one object from level 2 then all the objects in the entity1 are getting data fault. some thing like this.

Printing description of listOfEntitys:
(
    "<Entity1: 0x4dc3d80> (entity: Entity1; id: 0x4dc2d60 <x-coredata://DF11191D-0BE9-4A63-955D-0A43153290A4/Entity1/p5> ; data: <fault>)",
    "<Entity1: 0x5b06ea0> (entity: Entity1; id: 0x5b077d0 <x-coredata://DF11191D-0BE9-4A63-955D-0A43153290A4/Entity1/p6> ; data: <fault>)",
    "<Entity1: 0x4dc2cf0> (entity: Entity1; id: 0x4dc2df0 <x-coredata://DF11191D-0BE9-4A63-955D-0A43153290A4/Entity1/p7> ; data: <fault>)",
    "<Entity1: 0x4dc2b80> (entity: Entity1; id: 0x4dc3640 <x-coredata://DF11191D-0BE9-4A63-955D-0A43153290A4/Entity1/p8> ; data: <fault>)"
)


问:
Is there any good way to read numbers in square brackets in Lua?
In Lua, Is there any good way to read Only numbers from input like "[1,2,3,4]" if i know the number of the numbers

I did io.read("*n") for each, but that just returns nil values

```<code>local num = io.read()
for i = 1, num do
    print(io.read("*n"))
end
</code>```

for that code inputs are

```<code>4
[1,1,15,54]
</code>```

outputs are

```<code>nil
nil
nil
nil
</code>```

I expect

```<code>1
1
15
54
</code>```

Should I just use string.find and sub with ',' ?

答:
If you're sure that there are no spaces in the input, you can use this code:

```<code>local num = io.read()
for i = 1, num do
    io.read(1)
    print(io.read("*n"))
end
</code>```

The first io.read(1) reads [, the next ones read the commas. The closing ] is left unread.

Reading the whole line and parsing it is more robust:

```<code>local num = io.read()
local lin = io.read()
local i=0
for w in lin:gmatch("%d+") do
    i=i+1
    print(i,w)
end
</code>```

Body:
In Lua, Is there any good way to read Only numbers from input like "[1,2,3,4]" if i know the number of the numbers

I did io.read("*n") for each, but that just returns nil values

local num = io.read()
for i = 1, num do
    print(io.read("*n"))
end

for that code inputs are

4
[1,1,15,54]

outputs are

nil
nil
nil
nil

I expect

1
1
15
54

Should I just use string.find and sub with ',' ?

Body:
If you're sure that there are no spaces in the input, you can use this code:

local num = io.read()
for i = 1, num do
    io.read(1)
    print(io.read("*n"))
end

The first io.read(1) reads [, the next ones read the commas. The closing ] is left unread.

Reading the whole line and parsing it is more robust:

local num = io.read()
local lin = io.read()
local i=0
for w in lin:gmatch("%d+") do
    i=i+1
    print(i,w)
end


问:
Ruby/Minitest Spec: How to test that a method returns a value within a given array?
I have the following class:

  class State
    def self.alive
      :alive
    end

    def self.dead
      :dead
    end
  end
```

<p>Testing is simple:</p>

```it 'should report the expected state for alive' do
  State.alive.must_equal :alive
end

it 'should report the expected state for dead' do
  State.dead.must_equal :dead
end
```

<p>I want to add a class method which returns a random state.</p>

<pre class="lang-rb prettyprint-override"><code>class State
# ...
    def self.random
      [alive, dead].sample
    end
</code>```

However, I'm unsure of which assertion I need to use.

Currently, I am testing it as follows:

  it 'should return a random state' do
    %i[dead alive].must_include State.random
  end
```

Which is back to front. The test above is testing the literal array rather that the State class.

Is there a better way to test that a method returns a value included within a specified array?

答:
Before I offer you a solution, I want to unravel some details about the Spec DSL and Minitest. The must_include methods is the Spec DSL expectation for the assert_includes assertion. That method has the following signature:

assert_includes collection, obj, msg = nil
```

<p>When the expectation is created, the signature is:</p>

<pre class="lang-rb prettyprint-override"><code>Collection#must_include obj, msg = nil
</code>```

So what you are really asking is for a way of calling these methods with the argument order reversed. This is pretty simple to do by creating new methods that use your desired argument order. First, we must create the assertion:

module Minitest::Assertions
  ##
  # Fails unless +obj+ is included in +collection+.

  def assert_included_in obj, collection, msg = nil
    msg = message(msg) {
      "Expected #{mu_pp(obj)} to be included in #{mu_pp(collection)}"
    }
    assert_respond_to collection, :include?
    assert collection.include?(obj), msg
  end
end
```

<p>Now that we have the assertion method, we can create the Spec DSL expectation:</p>

<pre class="lang-rb prettyprint-override"><code>module Minitest::Expectations
  ##
  # See Minitest::Assertions#assert_included_in
  #
  #    collection.must_be_one_of obj
  #
  # :method: must_be_one_of

  infect_an_assertion :assert_included_in, :must_be_one_of, :reverse
end
</code>```

Now that we have defined the expectation, and the assertion it uses, we can use it in the test:

it "should return a random state" do
  State.random.must_be_one_of %i[dead alive]
end
```

<p>I would take it one step further, and use the value monad to call the expectation:</p>

<pre class="lang-rb prettyprint-override"><code>it "should return a random state" do
  value(State.random).must_be_one_of %i[dead alive]
end
</code>```

Body:
I have the following class:

  class State
    def self.alive
      :alive
    end

    def self.dead
      :dead
    end
  end

Testing is simple:

it 'should report the expected state for alive' do
  State.alive.must_equal :alive
end

it 'should report the expected state for dead' do
  State.dead.must_equal :dead
end

I want to add a class method which returns a random state.

class State
# ...
    def self.random
      [alive, dead].sample
    end

However, I'm unsure of which assertion I need to use.

Currently, I am testing it as follows:

  it 'should return a random state' do
    %i[dead alive].must_include State.random
  end

Which is back to front. The test above is testing the literal array rather that the State class.

Is there a better way to test that a method returns a value included within a specified array?

Body:
Before I offer you a solution, I want to unravel some details about the Spec DSL and Minitest. The must_include methods is the Spec DSL expectation for the assert_includes assertion. That method has the following signature:

assert_includes collection, obj, msg = nil

When the expectation is created, the signature is:

Collection#must_include obj, msg = nil

So what you are really asking is for a way of calling these methods with the argument order reversed. This is pretty simple to do by creating new methods that use your desired argument order. First, we must create the assertion:

module Minitest::Assertions
  ##
  # Fails unless +obj+ is included in +collection+.

  def assert_included_in obj, collection, msg = nil
    msg = message(msg) {
      "Expected #{mu_pp(obj)} to be included in #{mu_pp(collection)}"
    }
    assert_respond_to collection, :include?
    assert collection.include?(obj), msg
  end
end

Now that we have the assertion method, we can create the Spec DSL expectation:

module Minitest::Expectations
  ##
  # See Minitest::Assertions#assert_included_in
  #
  #    collection.must_be_one_of obj
  #
  # :method: must_be_one_of

  infect_an_assertion :assert_included_in, :must_be_one_of, :reverse
end

Now that we have defined the expectation, and the assertion it uses, we can use it in the test:

it "should return a random state" do
  State.random.must_be_one_of %i[dead alive]
end

I would take it one step further, and use the value monad to call the expectation:

it "should return a random state" do
  value(State.random).must_be_one_of %i[dead alive]
end


问:
How do I update UITableViewCell background color when changing themes?
I'm implementing dark and black themes in my app using UIAppearance, everything is working well apart from in the tableview I am using control the active theme.

I'm Implementing themes and the switching method is based on this tutorial:

Image 1

Image 2

Screen recording

I've tried calling tableView.reloadData() & setNeedsDisplay on the selected cell in the tableView didSelectRowAt function.

Code I am using the apply the theme is:

Theme.current.apply()

```<code>    let windows = UIApplication.shared.windows
    for window in windows {
        for view in window.subviews {
            view.removeFromSuperview()
            window.addSubview(view)
        }
    }
</code>```

When applying the new theme the background of the selected cell animated back to the previous themes color once deselectRow completes.

Any help greatly appreciated!

答: Found the solution to this, setting the Cell background colour to clear resolved the issue.</p>

Body:
I'm implementing dark and black themes in my app using UIAppearance, everything is working well apart from in the tableview I am using control the active theme.

I'm Implementing themes and the switching method is based on this tutorial:

Image 1

Image 2

Screen recording

I've tried calling tableView.reloadData() & setNeedsDisplay on the selected cell in the tableView didSelectRowAt function.

Code I am using the apply the theme is:

Theme.current.apply()

    let windows = UIApplication.shared.windows
    for window in windows {
        for view in window.subviews {
            view.removeFromSuperview()
            window.addSubview(view)
        }
    }

When applying the new theme the background of the selected cell animated back to the previous themes color once deselectRow completes.

Any help greatly appreciated!


问:
IndProp: ev_plus_plus
```<code>(** **** Exercise: 3 stars, standard, optional (ev_plus_plus)

    This exercise just requires applying existing lemmas.  No
    induction or even case analysis is needed, though some of the
    rewriting may be tedious. *)

Theorem ev_plus_plus : forall n m p,
  even (n+m) -> even (n+p) -> even (m+p).
Proof.
  intros n m p H1 H2.
</code>```

Here is what I got:

```<code>1 subgoal (ID 89)

n, m, p : nat
H1 : even (n + m)
H2 : even (n + p)
============================
even (m + p)
</code>```

I have proven the previous theorem:

```<code>Theorem ev_ev__ev : forall n m,
  even (n+m) -> even n -> even m.
</code>```

And wanted to apply it to H1, but

```<code>apply ev_ev__ev in H1.
</code>```

gives an error:

```<code>Error: Unable to find an instance for the variable m.
</code>```

Why can't it find "m" in the expression even (n + m)? How to fix?

Update

```<code>apply ev_ev__ev with (m:=m) in H1.
</code>```

gives a very strange result:

```<code>2 subgoals (ID 90)

n, m, p : nat
H1 : even m
H2 : even (n + p)
============================
even (m + p)

subgoal 2 (ID 92) is:
 even (n + m + m)
</code>```

I thought that it will transform H1 to 2 hypothesis:

```<code>H11 : even n
H12 : even m
</code>```

But instead it gave 2 subgoals, the second that we need to prove is more complicated than the initial one:

```<code>even (n + m + m)
</code>```

What's happening here?

答:
The statement forall n m,  even (n+m) -> even n -> even m. does not mean "if we have that (n + m) is even then we have both that n is even and that m is even" (this is false, consider n = m = 1).  Instead it means "if we have that (n+m) is even, and we have that n is even, then we have that m is even".

There is no way to get H11 : even n and H12 : even m just from H1 : even (n + m) without assuming a contradiction.  I would suggest figuring out how to prove your theorem with pen and paper before trying to prove it in Coq.

Title: IndProp: ev_plus_plus

Body:
(** **** Exercise: 3 stars, standard, optional (ev_plus_plus)

    This exercise just requires applying existing lemmas.  No
    induction or even case analysis is needed, though some of the
    rewriting may be tedious. *)

Theorem ev_plus_plus : forall n m p,
  even (n+m) -> even (n+p) -> even (m+p).
Proof.
  intros n m p H1 H2.

Here is what I got:

1 subgoal (ID 89)

n, m, p : nat
H1 : even (n + m)
H2 : even (n + p)
============================
even (m + p)

I have proven the previous theorem:

Theorem ev_ev__ev : forall n m,
  even (n+m) -> even n -> even m.

And wanted to apply it to H1, but

apply ev_ev__ev in H1.

gives an error:

Error: Unable to find an instance for the variable m.

Why can't it find "m" in the expression even (n + m)? How to fix?

Update

apply ev_ev__ev with (m:=m) in H1.

gives a very strange result:

2 subgoals (ID 90)

n, m, p : nat
H1 : even m
H2 : even (n + p)
============================
even (m + p)

subgoal 2 (ID 92) is:
 even (n + m + m)

I thought that it will transform H1 to 2 hypothesis:

H11 : even n
H12 : even m

But instead it gave 2 subgoals, the second that we need to prove is more complicated than the initial one:

even (n + m + m)

What's happening here?


问:
Authentication/Authorization in Gmail API
I am creating an app to extract user's emails once they arrive at the uesr' Gmail account (automatically).

After reading Gmail API, I conclude that each extraction (of a Gmail) would require a user authorization through the Oauth 2.0 flow.

I am wondering if there is a way to extract an (G)email by providing an api_key (each gmail account would have its own api_key, obtained by gmail account user registering the app with Google)? The key is to extract (g)email without requiring manual authorizations by gmail account owners.

答:
After looking into the issue carefully, I have drawn a conclusion that Gmail (Hotmail, Yahoo mail are the same) does not support api_key authentication method for email accesses,
i.e. each time before an app accesses a gmail count, manual authentication is needed.</p>


问:
"An established connection was aborted by the software in your host machine" while copying file to Hadoop HDFS from Java code
I am trying out some simple Java code to copy file from my local system to HDFS. This is how my simple method looks like:

```<code>private static void copyFileToHDFS() throws IOException
{
    config.set("fs.defaultFS","hdfs://127.0.0.1:9000");
    FileSystem hdfs = FileSystem.get(config);
    Path localfsSourceDir = new Path("D:\\file1");
    Path hdfsTargetDir = new Path ("hdfs://127.0.0.1:9000/dir/");
    hdfs.copyFromLocalFile(localfsSourceDir, hdfsTargetDir);      //throws Exception
}
</code>```

This is giving me following Exception on last line:

```<code>Exception in thread "main" java.io.IOException: Failed on local exception: java.io.IOException: An established connection was aborted by the software in your host machine; Host Details : local host is: "01hw713648/10.163.5.139"; destination host is: "127.0.0.1":9000;
    at org.apache.hadoop.net.NetUtils.wrapException(NetUtils.java:773)
    at org.apache.hadoop.ipc.Client.call(Client.java:1479)
    at org.apache.hadoop.ipc.Client.call(Client.java:1412)
    at org.apache.hadoop.ipc.ProtobufRpcEngine$Invoker.invoke(ProtobufRpcEngine.java:229)
    at $Proxy9.getFileInfo(Unknown Source)
    at org.apache.hadoop.hdfs.protocolPB.ClientNamenodeProtocolTranslatorPB.getFileInfo(ClientNamenodeProtocolTranslatorPB.java:771)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invokeMethod(RetryInvocationHandler.java:191)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invoke(RetryInvocationHandler.java:102)
    at $Proxy10.getFileInfo(Unknown Source)
    at org.apache.hadoop.hdfs.DFSClient.getFileInfo(DFSClient.java:2108)
    at org.apache.hadoop.hdfs.DistributedFileSystem$22.doCall(DistributedFileSystem.java:1305)
    at org.apache.hadoop.hdfs.DistributedFileSystem$22.doCall(DistributedFileSystem.java:1301)
    at org.apache.hadoop.fs.FileSystemLinkResolver.resolve(FileSystemLinkResolver.java:81)
    at org.apache.hadoop.hdfs.DistributedFileSystem.getFileStatus(DistributedFileSystem.java:1301)
    at org.apache.hadoop.fs.FileSystem.exists(FileSystem.java:1424)
    at org.apache.hadoop.fs.FileUtil.checkDest(FileUtil.java:496)
    at org.apache.hadoop.fs.FileUtil.copy(FileUtil.java:348)
    at org.apache.hadoop.fs.FileUtil.copy(FileUtil.java:338)
    at org.apache.hadoop.fs.FileSystem.copyFromLocalFile(FileSystem.java:1965)
    at org.apache.hadoop.fs.FileSystem.copyFromLocalFile(FileSystem.java:1933)
    at org.apache.hadoop.fs.FileSystem.copyFromLocalFile(FileSystem.java:1898)
    at HBaseImportTsvBulkLoader.copyFileToHDFS(HBaseImportTsvBulkLoader.java:64)
    at HBaseImportTsvBulkLoader.main(HBaseImportTsvBulkLoader.java:37)
Caused by: java.io.IOException: An established connection was aborted by the software in your host machine
    at sun.nio.ch.SocketDispatcher.read0(Native Method)
    at sun.nio.ch.SocketDispatcher.read(Unknown Source)
    at sun.nio.ch.IOUtil.readIntoNativeBuffer(Unknown Source)
    at sun.nio.ch.IOUtil.read(Unknown Source)
    at sun.nio.ch.SocketChannelImpl.read(Unknown Source)
    at org.apache.hadoop.net.SocketInputStream$Reader.performIO(SocketInputStream.java:57)
    at org.apache.hadoop.net.SocketIOWithTimeout.doIO(SocketIOWithTimeout.java:142)
    at org.apache.hadoop.net.SocketInputStream.read(SocketInputStream.java:161)
    at org.apache.hadoop.net.SocketInputStream.read(SocketInputStream.java:131)
    at java.io.FilterInputStream.read(Unknown Source)
    at java.io.FilterInputStream.read(Unknown Source)
    at org.apache.hadoop.ipc.Client$Connection$PingInputStream.read(Client.java:520)
    at java.io.BufferedInputStream.fill(Unknown Source)
    at java.io.BufferedInputStream.read(Unknown Source)
    at java.io.DataInputStream.readInt(Unknown Source)
    at org.apache.hadoop.ipc.Client$Connection.receiveRpcResponse(Client.java:1084)
    at org.apache.hadoop.ipc.Client$Connection.run(Client.java:979)
</code>```

My Setup

I am running Hadoop cluster in Ubuntu VM running on VirtualBox (which is in turn running on Windows). I have cluster up running perfectly. I am running this java code on Windows. I have set up port forwarding rules on Virtual Box as follows:

```<code>   Name                    Protocol      Host-ip          Host-port       Guest-Ip       Guest-port
   datanode                tcp           <left empty>     50075           <guest-ip>     50075
   dfs web ui              tcp           <left empty>     50070           <guest-ip>     50070
   mapred apps             tcp           <left empty>     8088            <guest-ip>     8088
   hbase web ui            tcp           <left empty>     16010           <guest-ip>     16010
   hdfs                    tcp           <left empty>     9000            <guest-ip>     9000
   regionserver web ui     tcp           <left empty>     16301           <guest-ip>     16301
   ssh                     tcp           <left empty>     22              <guest-ip>     22
</code>```

which allows me to connect to various services on VM:

I am able to connect to VM using putty

Also able to open various hadoop web uis in browser inside Windows: Namenode web ui, HMaster webui, Regionserver webui

Update

Some online solutions for similar error but not in Hadoop context suggested to restart eclipse. So I just tried that. Now getting slightly different error:

```<code>Exception in thread "main" java.io.IOException: Failed on local exception: java.io.IOException: An existing connection was forcibly closed by the remote host; Host Details : local host is: "01hw713648/10.163.5.139"; destination host is: "127.0.0.1":9000;
</code>```

with exactly same stack trace.

答:
I recently got exactly this error when the port specified was wrong. I had specified 50070 instead of 9000.

I used a host-only adapter, hence no port-forwarding was required. I connected to 192.168.x.x in the Linux VM from the windows host. I also made sure the name node was listening on 0.0.0.0:9000 in the core-site.xml. Firewall and SE linux were disabled in the VM. I have the setup now working.

Body:
I am trying out some simple Java code to copy file from my local system to HDFS. This is how my simple method looks like:

private static void copyFileToHDFS() throws IOException
{
    config.set("fs.defaultFS","hdfs://127.0.0.1:9000");
    FileSystem hdfs = FileSystem.get(config);
    Path localfsSourceDir = new Path("D:\\file1");
    Path hdfsTargetDir = new Path ("hdfs://127.0.0.1:9000/dir/");
    hdfs.copyFromLocalFile(localfsSourceDir, hdfsTargetDir);      //throws Exception
}

This is giving me following Exception on last line:

Exception in thread "main" java.io.IOException: Failed on local exception: java.io.IOException: An established connection was aborted by the software in your host machine; Host Details : local host is: "01hw713648/10.163.5.139"; destination host is: "127.0.0.1":9000;
    at org.apache.hadoop.net.NetUtils.wrapException(NetUtils.java:773)
    at org.apache.hadoop.ipc.Client.call(Client.java:1479)
    at org.apache.hadoop.ipc.Client.call(Client.java:1412)
    at org.apache.hadoop.ipc.ProtobufRpcEngine$Invoker.invoke(ProtobufRpcEngine.java:229)
    at $Proxy9.getFileInfo(Unknown Source)
    at org.apache.hadoop.hdfs.protocolPB.ClientNamenodeProtocolTranslatorPB.getFileInfo(ClientNamenodeProtocolTranslatorPB.java:771)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invokeMethod(RetryInvocationHandler.java:191)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invoke(RetryInvocationHandler.java:102)
    at $Proxy10.getFileInfo(Unknown Source)
    at org.apache.hadoop.hdfs.DFSClient.getFileInfo(DFSClient.java:2108)
    at org.apache.hadoop.hdfs.DistributedFileSystem$22.doCall(DistributedFileSystem.java:1305)
    at org.apache.hadoop.hdfs.DistributedFileSystem$22.doCall(DistributedFileSystem.java:1301)
    at org.apache.hadoop.fs.FileSystemLinkResolver.resolve(FileSystemLinkResolver.java:81)
    at org.apache.hadoop.hdfs.DistributedFileSystem.getFileStatus(DistributedFileSystem.java:1301)
    at org.apache.hadoop.fs.FileSystem.exists(FileSystem.java:1424)
    at org.apache.hadoop.fs.FileUtil.checkDest(FileUtil.java:496)
    at org.apache.hadoop.fs.FileUtil.copy(FileUtil.java:348)
    at org.apache.hadoop.fs.FileUtil.copy(FileUtil.java:338)
    at org.apache.hadoop.fs.FileSystem.copyFromLocalFile(FileSystem.java:1965)
    at org.apache.hadoop.fs.FileSystem.copyFromLocalFile(FileSystem.java:1933)
    at org.apache.hadoop.fs.FileSystem.copyFromLocalFile(FileSystem.java:1898)
    at HBaseImportTsvBulkLoader.copyFileToHDFS(HBaseImportTsvBulkLoader.java:64)
    at HBaseImportTsvBulkLoader.main(HBaseImportTsvBulkLoader.java:37)
Caused by: java.io.IOException: An established connection was aborted by the software in your host machine
    at sun.nio.ch.SocketDispatcher.read0(Native Method)
    at sun.nio.ch.SocketDispatcher.read(Unknown Source)
    at sun.nio.ch.IOUtil.readIntoNativeBuffer(Unknown Source)
    at sun.nio.ch.IOUtil.read(Unknown Source)
    at sun.nio.ch.SocketChannelImpl.read(Unknown Source)
    at org.apache.hadoop.net.SocketInputStream$Reader.performIO(SocketInputStream.java:57)
    at org.apache.hadoop.net.SocketIOWithTimeout.doIO(SocketIOWithTimeout.java:142)
    at org.apache.hadoop.net.SocketInputStream.read(SocketInputStream.java:161)
    at org.apache.hadoop.net.SocketInputStream.read(SocketInputStream.java:131)
    at java.io.FilterInputStream.read(Unknown Source)
    at java.io.FilterInputStream.read(Unknown Source)
    at org.apache.hadoop.ipc.Client$Connection$PingInputStream.read(Client.java:520)
    at java.io.BufferedInputStream.fill(Unknown Source)
    at java.io.BufferedInputStream.read(Unknown Source)
    at java.io.DataInputStream.readInt(Unknown Source)
    at org.apache.hadoop.ipc.Client$Connection.receiveRpcResponse(Client.java:1084)
    at org.apache.hadoop.ipc.Client$Connection.run(Client.java:979)

My Setup

I am running Hadoop cluster in Ubuntu VM running on VirtualBox (which is in turn running on Windows). I have cluster up running perfectly. I am running this java code on Windows. I have set up port forwarding rules on Virtual Box as follows:

   Name                    Protocol      Host-ip          Host-port       Guest-Ip       Guest-port
   datanode                tcp           <left empty>     50075           <guest-ip>     50075
   dfs web ui              tcp           <left empty>     50070           <guest-ip>     50070
   mapred apps             tcp           <left empty>     8088            <guest-ip>     8088
   hbase web ui            tcp           <left empty>     16010           <guest-ip>     16010
   hdfs                    tcp           <left empty>     9000            <guest-ip>     9000
   regionserver web ui     tcp           <left empty>     16301           <guest-ip>     16301
   ssh                     tcp           <left empty>     22              <guest-ip>     22

which allows me to connect to various services on VM:

I am able to connect to VM using putty

Also able to open various hadoop web uis in browser inside Windows: Namenode web ui, HMaster webui, Regionserver webui

Update

Some online solutions for similar error but not in Hadoop context suggested to restart eclipse. So I just tried that. Now getting slightly different error:

Exception in thread "main" java.io.IOException: Failed on local exception: java.io.IOException: An existing connection was forcibly closed by the remote host; Host Details : local host is: "01hw713648/10.163.5.139"; destination host is: "127.0.0.1":9000;

with exactly same stack trace.


问:
split string each x characters in dataframe
I know there are some answers here about splitting a string every nth character, such as this one and this one,  However these are pretty question specific and mostly related to a single string and not to a data frame of multiple strings.

Example data

```<code>df <- data.frame(id = 1:2, seq = c('ABCDEFGHI', 'ZABCDJHIA'))
</code>```

Looks like this:

```<code>  id       seq
1  1 ABCDEFGHI
2  2 ZABCDJHIA
</code>```

Splitting on every third character

I want to split the string in each row every thrid character, such that the resulting data frame looks like this:

```<code>id  1   2   3
1   ABC DEF GHI
2   ZAB CDJ HIA
</code>```

What I tried

I used the splitstackshape before to split a string on a single character, like so: df %>% cSplit('seq', sep = '', stripWhite = FALSE, type.convert = FALSE) I would love to have a similar function (or perhaps it is possbile with cSplit) to split on every third character.

答:
An option would be separate

```<code>library(tidyverse)
df %>%
    separate(seq, into = paste0("x", 1:3), sep = c(3, 6))
# id  x1  x2  x3
#1  1 ABC DEF GHI
#2  2 ZAB CDJ HIA
</code>```

If we want to create it more generic

```<code>n1 <- nchar(as.character(df$seq[1])) - 3
s1 <- seq(3, n1, by = 3)
nm1 <- paste0("x", seq_len(length(s1) +1))
df %>%
    separate(seq, into = nm1, sep = s1)
</code>```

Or using base R, using strsplit, split the 'seq' column for each instance of 3 characters by passing a regex lookaround into a list and then rbind the list elements

```<code>df[paste0("x", 1:3)] <- do.call(rbind,
           strsplit(as.character(df$seq), "(?<=.{3})", perl = TRUE))
</code>```

NOTE: It is better to avoid column names that start with non-standard labels such as numbers.  For that reason, appended 'x' at the beginning of the names

Body:
I know there are some answers here about splitting a string every nth character, such as this one and this one,  However these are pretty question specific and mostly related to a single string and not to a data frame of multiple strings.

Example data

df <- data.frame(id = 1:2, seq = c('ABCDEFGHI', 'ZABCDJHIA'))

Looks like this:

  id       seq
1  1 ABCDEFGHI
2  2 ZABCDJHIA

Splitting on every third character

I want to split the string in each row every thrid character, such that the resulting data frame looks like this:

id  1   2   3
1   ABC DEF GHI
2   ZAB CDJ HIA

What I tried

I used the splitstackshape before to split a string on a single character, like so: df %>% cSplit('seq', sep = '', stripWhite = FALSE, type.convert = FALSE) I would love to have a similar function (or perhaps it is possbile with cSplit) to split on every third character.

Body:
An option would be separate

library(tidyverse)
df %>%
    separate(seq, into = paste0("x", 1:3), sep = c(3, 6))
# id  x1  x2  x3
#1  1 ABC DEF GHI
#2  2 ZAB CDJ HIA

If we want to create it more generic

n1 <- nchar(as.character(df$seq[1])) - 3
s1 <- seq(3, n1, by = 3)
nm1 <- paste0("x", seq_len(length(s1) +1))
df %>%
    separate(seq, into = nm1, sep = s1)

Or using base R, using strsplit, split the 'seq' column for each instance of 3 characters by passing a regex lookaround into a list and then rbind the list elements

df[paste0("x", 1:3)] <- do.call(rbind,
           strsplit(as.character(df$seq), "(?<=.{3})", perl = TRUE))

NOTE: It is better to avoid column names that start with non-standard labels such as numbers.  For that reason, appended 'x' at the beginning of the names


问:
type cast in c compiler
Consider the following example the mixed mode expression is supported:
c = a + b*10.5 where a and b are integers and c is a float.
Describe how the data is typecast to its appropriate format

答:
You need to look up the 'usual arithmetic conversions' in your text book, or in the C standard (§6.3.1.8 in C11 — ISO/IEC 9899:2011), which reads:

6.3.1.8 Usual arithmetic conversions

1 Many operators that expect operands of arithmetic type cause conversions and yield result
  types in a similar way. The purpose is to determine a common real type for the operands
  and result. For the specified operands, each operand is converted, without change of type
  domain, to a type whose corresponding real type is the common real type. Unless
  explicitly stated otherwise, the common real type is also the corresponding real type of
  the result, whose type domain is the type domain of the operands if they are the same,
  and complex otherwise. This pattern is called the usual arithmetic conversions:

First, if the corresponding real type of either operand is long double, the other
  operand is converted, without change of type domain, to a type whose corresponding real type is long double.

Otherwise, if the corresponding real type of either operand is double, the other
  operand is converted, without change of type domain, to a type whose
  corresponding real type is double.

Otherwise, if the corresponding real type of either operand is float, the other
  operand is converted, without change of type domain, to a type whose
  corresponding real type is float.62)

Otherwise, the integer promotions are performed on both operands. Then the
  following rules are applied to the promoted operands:

If both operands have the same type, then no further conversion is needed.

Otherwise, if both operands have signed integer types or both have unsigned
  integer types, the operand with the type of lesser integer conversion rank is
  converted to the type of the operand with greater rank.

Otherwise, if the operand that has unsigned integer type has rank greater or
  equal to the rank of the type of the other operand, then the operand with
  signed integer type is converted to the type of the operand with unsigned
  integer type.

Otherwise, if the type of the operand with signed integer type can represent
  all of the values of the type of the operand with unsigned integer type, then
  the operand with unsigned integer type is converted to the type of the
  operand with signed integer type.

Otherwise, both operands are converted to the unsigned integer type
  corresponding to the type of the operand with signed integer type.

2 The values of floating operands and of the results of floating expressions may be
  represented in greater range and precision than that required by the type; the types are not
  changed thereby.63)

62) For example, addition of a double _Complex and a float entails just the conversion of the
  float operand to double (and yields a double _Complex result).

63) The cast and assignment operators are still required to remove extra range and precision.

And the integer promotions are defined in §6.3.1.1:

6.3.1.1 Boolean, characters, and integers

1 Every integer type has an integer conversion rank defined as follows:

No two signed integer types shall have the same rank, even if they have the same
  representation.

The rank of a signed integer type shall be greater than the rank of any signed integer
  type with less precision.

The rank of long long int shall be greater than the rank of long int, which
  shall be greater than the rank of int, which shall be greater than the rank of short
  int, which shall be greater than the rank of signed char.

The rank of any unsigned integer type shall equal the rank of the corresponding
  signed integer type, if any.

The rank of any standard integer type shall be greater than the rank of any extended
  integer type with the same width.

The rank of char shall equal the rank of signed char and unsigned char.

The rank of _Bool shall be less than the rank of all other standard integer types.

The rank of any enumerated type shall equal the rank of the compatible integer type (see 6.7.2.2).

The rank of any extended signed integer type relative to another extended signed
  integer type with the same precision is implementation-defined, but still subject to the
  other rules for determining the integer conversion rank.

For all integer types T1, T2, and T3, if T1 has greater rank than T2 and T2 has
  greater rank than T3, then T1 has greater rank than T3.

2 The following may be used in an expression wherever an int or unsigned int may
  be used:

An object or expression with an integer type (other than int or unsigned int)
  whose integer conversion rank is less than or equal to the rank of int and
  unsigned int.

A bit-field of type _Bool, int, signed int, or unsigned int.

If an int can represent all values of the original type (as restricted by the width, for a
  bit-field), the value is converted to an int; otherwise, it is converted to an unsigned
  int. These are called the integer promotions.58) All other types are unchanged by the
  integer promotions.

3 The integer promotions preserve value including sign. As discussed earlier, whether a
  ‘‘plain’’ char is treated as signed is implementation-defined.

58) The integer promotions are applied only: as part of the usual arithmetic conversions, to certain
  argument expressions, to the operands of the unary +, -, and ~ operators, and to both operands of the
  shift operators, as specified by their respective subclauses.

Title: type cast in c compiler


问:
Not getting the desired output (conditionals+functions)
I'm a new to Python and a piece of code doesn't seem to work as desired.
Here is the code:

```<code>#Create a function that takes any string as argument and returns the length of that string. Provided it can't take integers.

def length_function(string):
    length = len(string)
    return length

string_input=input("Enter the string: ")
if type(string_input) == int:
    print("Input can not be an integer")
else:
    print(length_function(string_input))
</code>```

Whenever I type an integer in the result, it gives me the the number of digits in that integer. However, I want to display a message that "Input can not be an integer".

Is there any error in my code or is there another way of doing this. Please respond. Thank You!

答:
Any input entered is always string. It cannot be checked for int. It will always fail. You can do something like below.

```<code>def length_function(string):
    length = len(string)
    return length

string_input=input("Enter the string: ")
if string_input.isdigit():
    print("Input can not be an integer")
else:
    print(length_function(string_input))
</code>```

Output:

```<code>Enter the string: Check
5

Enter the string: 1
Input can not be an integer
</code>```

Body:
I'm a new to Python and a piece of code doesn't seem to work as desired.
Here is the code:

#Create a function that takes any string as argument and returns the length of that string. Provided it can't take integers.

def length_function(string):
    length = len(string)
    return length

string_input=input("Enter the string: ")
if type(string_input) == int:
    print("Input can not be an integer")
else:
    print(length_function(string_input))

Whenever I type an integer in the result, it gives me the the number of digits in that integer. However, I want to display a message that "Input can not be an integer".

Is there any error in my code or is there another way of doing this. Please respond. Thank You!

Body:
Any input entered is always string. It cannot be checked for int. It will always fail. You can do something like below.

def length_function(string):
    length = len(string)
    return length

string_input=input("Enter the string: ")
if string_input.isdigit():
    print("Input can not be an integer")
else:
    print(length_function(string_input))

Output:

Enter the string: Check
5

Enter the string: 1
Input can not be an integer


问:
Communicate with client side printer and print A4 sheet
Java web application installed in server. The client's can access the application using browser through URL.
The application need to communicate with local printers or network printers which is directly connected to client and print pdf file in A4 sheet.

Here the print operation done by automatically without user interaction. User will just click print button, we need to find the default print setup in client machine and print pdf file in A4 sheet in that printer.

Multiple client machine and multiple default printer based on user setup.

How to do it using Java or JavaScript?

答:
You can just use method print on window object.

The print() method prints the contents of the current window.

The print() method opens the Print Dialog Box, which lets the user to select preferred printing options.

Example of usage:

<!DOCTYPE html>

Click the button to print the current page.

<button onclick="myFunction()">Print this page</button>

```

Body:
You can just use method print on window object.

The print() method prints the contents of the current window.

The print() method opens the Print Dialog Box, which lets the user to select preferred printing options.

Example of usage:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to print the current page.</p>

<button onclick="myFunction()">Print this page</button>

<script>
function myFunction() {
  window.print();
}
</script>

</body>
</html>


问:
Why is assert of range( 0, 0 ) return true for any one-element array regardless of its value?
These are as expected (per https://php.net/manual/en/language.operators.array.php):

```<code>assert( range( 0, 0 ) == [0] );
assert( range( 0, 0 ) == ['0'] );
assert( range( 0, 0 ) !== ['not zero'] );
assert( range( 0, 1 ) != ['not zero', 'not zero'] );
</code>```

But why is range( 0, 0 ) apparently considered == equal to any one-element array regardless of its value?

```<code>assert( range( 0, 0 ) == ['not zero'] ); // return TRUE??
</code>```

答:
Better explanation is the == operator convert the array element to int as the left side of the operator was array with int.

Because both intval('not zero') and (int) 'not zero' will return 0 the compare will return true as it is 0 (as one can see here).

When using === PHP is not doing type casting so the string stays string so the compare fails (from PHP operators):

===: TRUE if $a and $b have the same key/value pairs in the same order and of the same types.

Body:
These are as expected (per https://php.net/manual/en/language.operators.array.php):

assert( range( 0, 0 ) == [0] );
assert( range( 0, 0 ) == ['0'] );
assert( range( 0, 0 ) !== ['not zero'] );
assert( range( 0, 1 ) != ['not zero', 'not zero'] );

But why is range( 0, 0 ) apparently considered == equal to any one-element array regardless of its value?

assert( range( 0, 0 ) == ['not zero'] ); // return TRUE??


答:
I'm not sure why you're wrapping len() in your length_function  but that's not necessary. The result of input() will always be a string so your if cannot evalue to true. To turn it into a number use int(). This will fail if the input can't be parsed into an integer, so rather than an if...else you probably want to do sth like

```<code>try:
    int(string_input)
    print("Input cannot be an integer")
except ValueError:
    print(length_function(string_input))
</code>```

Title: Not getting the desired output (conditionals+functions)

Body:
I'm not sure why you're wrapping len() in your length_function  but that's not necessary. The result of input() will always be a string so your if cannot evalue to true. To turn it into a number use int(). This will fail if the input can't be parsed into an integer, so rather than an if...else you probably want to do sth like

try:
    int(string_input)
    print("Input cannot be an integer")
except ValueError:
    print(length_function(string_input))


问:
Java [unchecked] unchecked case warning
Ok, I've been looking around and done alot of google searching, but I still can't find a way to avoid this warning.

```<code>Integer result = chooser.showOpenDialog(null);
if (result.equals(0))
{
    String tempHolder = chooser.getSelectedFile().getPath();
    filenameLoad = new File(tempHolder);
    filenameSave = filenameLoad;
    FileInputStream fis = null;
    ObjectInputStream in = null;
    try
    {
        fis = new FileInputStream(filenameLoad);
        in = new ObjectInputStream(fis);;
    }
    catch(IOException ex)
    {
        ex.printStackTrace();
    }

    try
    {
        loadFile = (ArrayList<Dot>)in.readObject();
    }
    catch(IOException ex)
    {
        System.out.println("Cast fail");
    }
    catch(ClassNotFoundException ex)
    {
        System.out.println("Cast fail");
    }
    catch (ClassCastException ex)
    {
        System.out.println("Cast fail");
    }

    try
    {
        in.close();
    }
    catch(Exception ex)
    {
        System.out.println("failed to close in");
    }
    save.setEnabled(true);
      gpanel.setDotList(loadFile);
  }
</code>```

It gives me the warning at the line loadFile = (ArrayList)in.readObject();  I've added in the catchs so i'm not sure why it still says its uncatched.  Any help?  thanks?

答:
It doesn't say uncatched (which correctly is spelled uncaught), but unchecked. You cannot avoid this warning when casting to a generic type, you can only suppress it. Or you can work around it:

```<code>@SuppressWarnings("unchecked")
public static <T> T castToAnything(Object obj) {
  return (T) obj;
}
</code>```

With this method you can write:

```<code>loadFile = castToAnything(in.readObject());
</code>```

Title: Java [unchecked] unchecked case warning

Body:
Ok, I've been looking around and done alot of google searching, but I still can't find a way to avoid this warning.

Integer result = chooser.showOpenDialog(null);
if (result.equals(0))
{
    String tempHolder = chooser.getSelectedFile().getPath();
    filenameLoad = new File(tempHolder);
    filenameSave = filenameLoad;
    FileInputStream fis = null;
    ObjectInputStream in = null;
    try
    {
        fis = new FileInputStream(filenameLoad);
        in = new ObjectInputStream(fis);;
    }
    catch(IOException ex)
    {
        ex.printStackTrace();
    }

    try
    {
        loadFile = (ArrayList<Dot>)in.readObject();
    }
    catch(IOException ex)
    {
        System.out.println("Cast fail");
    }
    catch(ClassNotFoundException ex)
    {
        System.out.println("Cast fail");
    }
    catch (ClassCastException ex)
    {
        System.out.println("Cast fail");
    }

    try
    {
        in.close();
    }
    catch(Exception ex)
    {
        System.out.println("failed to close in");
    }
    save.setEnabled(true);
      gpanel.setDotList(loadFile);
  }

It gives me the warning at the line loadFile = (ArrayList)in.readObject();  I've added in the catchs so i'm not sure why it still says its uncatched.  Any help?  thanks?

Body:
It doesn't say uncatched (which correctly is spelled uncaught), but unchecked. You cannot avoid this warning when casting to a generic type, you can only suppress it. Or you can work around it:

@SuppressWarnings("unchecked")
public static <T> T castToAnything(Object obj) {
  return (T) obj;
}

With this method you can write:

loadFile = castToAnything(in.readObject());


问:
How do I place the image beneath the paragraph when I resize the browser screen?
So I have a paragraph on the left side of the screen and my image on the right side of the screen. It is responsive but not the way I want it to be. When I resize the browser screen, I want the picture to display beneath the paragraph i.e. I want the paragraph to be on top of the image and the image should be below the paragraph. When I try to resize the window, the image just becomes short but does not move to the next line.

I am currently using  CSS grid system to display the paragraph on the left and the image on the right. I also have the whole thing inside a container. I am also using flex box to make it responsive but that just wont help. I have also tried to use media queries but I just don't know how to tell the media query to move the image below the paragraph.

答:
Check this out:
https://medium.com/@PavelLaptev/css-weekly-2-an-image-on-the-left-text-on-the-left-a5e59b2acdb5. It explains how to do exactly this.

You could also use a table but that would overcomplicate things.

(edit) To answer your question, using +Ray Butterworth's answer, yes that would mean the image would go beneath the text. (Or, vice versa if you just switched the order of the tags.)
I put his code in a codepen with a border around the image so you can see where it would be. I tried resizing the browser and it works: https://codepen.io/anon/pen/vwjPzP.

    .text  { width: 50%; min-width: 20em; float: left; }
    .image { width: 50%; min-width: 20em; }
```

<pre class="lang-html prettyprint-override"><code><p class="text">
    Blah blah blah.
    Blah blah blah.
    Blah blah blah.
    Blah blah blah.
    Blah blah blah.
    Blah blah blah.
</p>
<img class="image" src="./image.jpeg" border="4"/>
</code>```

Body:
Check this out:
https://medium.com/@PavelLaptev/css-weekly-2-an-image-on-the-left-text-on-the-left-a5e59b2acdb5. It explains how to do exactly this.

You could also use a table but that would overcomplicate things.

(edit) To answer your question, using +Ray Butterworth's answer, yes that would mean the image would go beneath the text. (Or, vice versa if you just switched the order of the tags.)
I put his code in a codepen with a border around the image so you can see where it would be. I tried resizing the browser and it works: https://codepen.io/anon/pen/vwjPzP.

    .text  { width: 50%; min-width: 20em; float: left; }
    .image { width: 50%; min-width: 20em; }

<p class="text">
    Blah blah blah.
    Blah blah blah.
    Blah blah blah.
    Blah blah blah.
    Blah blah blah.
    Blah blah blah.
</p>
<img class="image" src="./image.jpeg" border="4"/>


问:
Generating div and input tags using javascript
I am trying to generate textFields dynamically, but as I am using material design-lite, I don't understand how to generate div class and input class attributes and label tags.

Here, is the code in HTML :

```<code><div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
        <input class="mdl-textfield__input" type="text" id="sample3" name="passengername">
        <label class="mdl-textfield__label" for="sample3">Passenger Name :</label>
</div>
</code>```

Did some searching and found the below script but have no idea how to generate label tags and class attribute for the tags:

```<code>function addFields(){
    var number = document.getElementById("member").value;
    var container = document.getElementById("container");
    while (container.hasChildNodes()) {
        container.removeChild(container.lastChild);
    }
    for (i=0;i<number;i++){
        var div = document.createElement('div');
        container.appendChild(document.createTextNode("passengername " + (i+1)));
        var input = document.createElement("input");
        input.type = "text";
        container.appendChild(input);
        container.appendChild(document.createElement("br"));
    }
}
</code>```

The code generates text fields but doesn't have the design i applied in css because i did not generate class attribute using js.

答: You can use a similar approach to generate label tags too , and for the div you can create a container div add the static class names to it and append your input and label to it.

Body:
I am trying to generate textFields dynamically, but as I am using material design-lite, I don't understand how to generate div class and input class attributes and label tags.

Here, is the code in HTML :

        <input class="mdl-textfield__input" type="text" id="sample3" name="passengername">
        Passenger Name :

Did some searching and found the below script but have no idea how to generate label tags and class attribute for the tags:

function addFields(){
    var number = document.getElementById("member").value;
    var container = document.getElementById("container");
    while (container.hasChildNodes()) {
        container.removeChild(container.lastChild);
    }
    for (i=0;i<number;i++){
        var div = document.createElement('div');
        container.appendChild(document.createTextNode("passengername " + (i+1)));
        var input = document.createElement("input");
        input.type = "text";
        container.appendChild(input);
        container.appendChild(document.createElement("br"));
    }
}

The code generates text fields but doesn't have the design i applied in css because i did not generate class attribute using js.


问:
Which MySQL data type to use for storing boolean values
Since MySQL doesn't seem to have any 'boolean' data type, which data type do you 'abuse' for storing true/false information in MySQL?

Especially in the context of writing and reading from/to a PHP script.

Over time I have used and seen several approaches:

tinyint, varchar fields containing the values 0/1,

varchar fields containing the strings '0'/'1' or 'true'/'false'

and finally enum Fields containing the two options 'true'/'false'.

None of the above seems optimal. I tend to prefer the tinyint 0/1 variant, since automatic type conversion in PHP gives me boolean values rather simply.

So which data type do you use? Is there a type designed for boolean values which I have overlooked? Do you see any advantages/disadvantages by using one type or another?

答:
Since MySQL (8.0.16) and MariaDB (10.2.1) both implemented the CHECK constraint, I would now use

```<code>bool_val TINYINT CHECK(bool_val IN(0,1))
</code>```

You will only be able to store 0, 1 or NULL, as well as values which can be converted to 0 or 1 without errors like '1', 0x00, b'1' or TRUE/FALSE.

If you don't want to permit NULLs, add the NOT NULL option

```<code>bool_val TINYINT NOT NULL CHECK(bool_val IN(0,1))
</code>```

Note that there is virtually no difference if you use TINYINT, TINYINT(1) or TINYINT(123).

If you want your schema to be upwards compatible, you can also use BOOL or BOOLEAN

```<code>bool_val BOOL CHECK(bool_val IN(TRUE,FALSE))
</code>```

db<>fiddle demo

OwnerDisplayName: Beat

Body:
Since MySQL (8.0.16) and MariaDB (10.2.1) both implemented the CHECK constraint, I would now use

bool_val TINYINT CHECK(bool_val IN(0,1))

You will only be able to store 0, 1 or NULL, as well as values which can be converted to 0 or 1 without errors like '1', 0x00, b'1' or TRUE/FALSE.

If you don't want to permit NULLs, add the NOT NULL option

bool_val TINYINT NOT NULL CHECK(bool_val IN(0,1))

Note that there is virtually no difference if you use TINYINT, TINYINT(1) or TINYINT(123).

If you want your schema to be upwards compatible, you can also use BOOL or BOOLEAN

bool_val BOOL CHECK(bool_val IN(TRUE,FALSE))

db<>fiddle demo