问:
How to get all elements in nested collection with streams
I have a class which contains different nested collections, now I want to receive all the elements of the nested collections, concrete I want to collect all the StrokePoints of the collections. I can solve it with "old" java but how to do it with streams?

```<code>    int strokesCounter = 0;
    List<StrokePoint> pointList = new ArrayList<>();
    if (!strokesData.getListOfSessions().isEmpty()) {
        for (SessionStrokes session : strokesData.getListOfSessions()) {
            List<Strokes> strokes = session.getListOfStrokes();
            for (Strokes stroke : strokes) {
                strokesCounter++;
                List<StrokePoint> points = stroke.getListOfStrokePoints();
                pointList.addAll(stroke.getListOfStrokePoints());
            }
        }
    }
</code>```

I am looking for a way to fill the pointList with the stream functionality.

答:
Since the primary aim is to solve for collecting the List<StrokePoint>, you can perform it using the flatMap operation as:

```<code>List<StrokePoint> points = strokesData.getListOfSessions()
        .stream()
        .flatMap(ss -> ss.getListOfStrokes().stream()
                .flatMap(s -> s.getListOfStrokePoints().stream()))
        .collect(Collectors.toList());
</code>```

Alongside, the count of Strokes can also be evaluated using the streams by summing the size of the lists as:

```<code>long strokeCount = strokesData.getListOfSessions()
        .stream()
        .mapToLong(ss -> ss.getListOfStrokes().size())
        .sum();
</code>```

To merge these operations, you can construct a AbstractMap.SimpleEntry while reducing the entries as:

```<code>AbstractMap.SimpleEntry<Integer, Stream<StrokePoint>> reduce = strokesData.getListOfSessions()
        .stream()
        .map(ss -> new AbstractMap.SimpleEntry<>(ss.getListOfStrokes().size(),
                ss.getListOfStrokes()
                        .stream()
                        .flatMap(s -> s.getListOfStrokePoints().stream())))
        .reduce(new AbstractMap.SimpleEntry<>(1, Stream.empty()),
                (e1, e2) -> new AbstractMap.SimpleEntry<>(
                        Integer.sum(e1.getKey(), e2.getKey()),
                        Stream.concat(e1.getValue(), e2.getValue())));
</code>```

Using this entry, you can attain the count of Strokes and the list of StrokePoints as :

```<code>long strokeCount = reduce.getKey();
List<StrokePoint> strokePoints = reduce.getValue().collect(Collectors.toList());
</code>```

Body:
I have a class which contains different nested collections, now I want to receive all the elements of the nested collections, concrete I want to collect all the StrokePoints of the collections. I can solve it with "old" java but how to do it with streams?

    int strokesCounter = 0;
    List<StrokePoint> pointList = new ArrayList<>();
    if (!strokesData.getListOfSessions().isEmpty()) {
        for (SessionStrokes session : strokesData.getListOfSessions()) {
            List<Strokes> strokes = session.getListOfStrokes();
            for (Strokes stroke : strokes) {
                strokesCounter++;
                List<StrokePoint> points = stroke.getListOfStrokePoints();
                pointList.addAll(stroke.getListOfStrokePoints());
            }
        }
    }

I am looking for a way to fill the pointList with the stream functionality.

Body:
Since the primary aim is to solve for collecting the List<StrokePoint>, you can perform it using the flatMap operation as:

List<StrokePoint> points = strokesData.getListOfSessions()
        .stream()
        .flatMap(ss -> ss.getListOfStrokes().stream()
                .flatMap(s -> s.getListOfStrokePoints().stream()))
        .collect(Collectors.toList());

Alongside, the count of Strokes can also be evaluated using the streams by summing the size of the lists as:

long strokeCount = strokesData.getListOfSessions()
        .stream()
        .mapToLong(ss -> ss.getListOfStrokes().size())
        .sum();

To merge these operations, you can construct a AbstractMap.SimpleEntry while reducing the entries as:

AbstractMap.SimpleEntry<Integer, Stream<StrokePoint>> reduce = strokesData.getListOfSessions()
        .stream()
        .map(ss -> new AbstractMap.SimpleEntry<>(ss.getListOfStrokes().size(),
                ss.getListOfStrokes()
                        .stream()
                        .flatMap(s -> s.getListOfStrokePoints().stream())))
        .reduce(new AbstractMap.SimpleEntry<>(1, Stream.empty()),
                (e1, e2) -> new AbstractMap.SimpleEntry<>(
                        Integer.sum(e1.getKey(), e2.getKey()),
                        Stream.concat(e1.getValue(), e2.getValue())));

Using this entry, you can attain the count of Strokes and the list of StrokePoints as :

long strokeCount = reduce.getKey();
List<StrokePoint> strokePoints = reduce.getValue().collect(Collectors.toList());


来源: stackexchange

问:
"HTTP Error 502.5 - Process Failure" for dotnet core 2.1 app
From error log:-
Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'System.Runtime, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

As I understand, I need to make changes in app.config to match the versions, but I cannot find app.config.

My web.config (Posting the entire file incase any error is found)

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <modules>

      <!-- Remove WebDAV module so that we can make DELETE requests -->
      <remove name="WebDAVModule" />
    </modules>
    <handlers>
      <!-- Remove WebDAV module so that we can make DELETE requests -->
      <remove name="WebDAV" />
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
    </handlers>
    <!-- When deploying on Azure, make sure that "dotnet" is installed and the path to it is registered in the PATH environment variable or specify the full path to it -->
    <aspNetCore requestTimeout="23:00:00" processPath="D:\******ini_nc\Presentation\Nop.Web\bin\Release\netcoreapp2.1\Nop.Core.dll" arguments="dotnet" forwardWindowsAuthToken="false" stdoutLogEnabled="True" stdoutLogFile=".\logs\stdout" startupTimeLimit="3600">
      <environmentVariables />
    </aspNetCore>
    <httpProtocol>
      <customHeaders>
        <remove name="X-Powered-By" />
      </customHeaders>
    </httpProtocol>
        <directoryBrowse enabled="true" />
  </system.webServer>
    <system.web>
        <identity impersonate="true" />
    </system.web>

</configuration>
</code>```

答:
I would not recommend making changes on files such as web.config that are auto-generated on publishing. Here is a small example of how the web.config of .net framework is replaced in .net core

Project level configuration (such as .net core or c# version) can be set from the .csproj file

Web launch related configurations (such as linking your IConfiguration to a custom source) can be set up from the program.cs

The middleware and application related configurations (such as mapping your db connection string) can be set up from the startup cs class

In your case, check if your server has the required runtime. If possible install the required .net core runtime from dot.net/core in the server. If you can't install this due to permissions or something, you can either downgrade your app version or use a self-contained publish.

Downgrading app version

Keep in mind this means you would lose version specific code. This isn't recommended if you already have a lot of code that might be version specific. This can be done by updating your .csprog file. Unlike .net framework. It is considered clean and safe to update this file in .net core.

** self-contained publish**

This option designed to work on systems without any .net core installed. It works by creating published files that contain all .net core runtime related files into a huge publish folder. So, keep in mind the publish folder would be huge. Have a look at this for more info https://learn.microsoft.com/en-us/dotnet/core/deploying/

ContentLicense: CC BY-SA 4.0

Body:
From error log:-
Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'System.Runtime, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

As I understand, I need to make changes in app.config to match the versions, but I cannot find app.config.

My web.config (Posting the entire file incase any error is found)

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <modules>

      <remove name="WebDAVModule" />
    </modules>
    <handlers>

      <remove name="WebDAV" />
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
    </handlers>

    <aspNetCore requestTimeout="23:00:00" processPath="D:\******ini_nc\Presentation\Nop.Web\bin\Release\netcoreapp2.1\Nop.Core.dll" arguments="dotnet" forwardWindowsAuthToken="false" stdoutLogEnabled="True" stdoutLogFile=".\logs\stdout" startupTimeLimit="3600">
      <environmentVariables />
    </aspNetCore>
    <httpProtocol>
      <customHeaders>
        <remove name="X-Powered-By" />
      </customHeaders>
    </httpProtocol>
        <directoryBrowse enabled="true" />
  </system.webServer>
    <system.web>
        <identity impersonate="true" />
    </system.web>

</configuration>


问:
Can I remotely access web browser tabs in my Oculus Quest/Oculus Go from a program running on my computer?
Currently the Oculus Quest headset's browser seems pretty basic, and doesn't have features such as copy/paste, etc. It also doesn't seem like it can't handle launching other apps via 'deep links'. I don't personally have an Oculus Go, but I assume it would be a pretty similar experience?

Is there any way we can access the URL's/history/etc in the headset's browser from a computer (eg. programatically)? At least that way we could copy the relevant parts, and maybe programatically 'type' them back into the headset in the area we need them.

答:
It seems this is possible using Chrome DevTools Remote Debugging if you have developer mode enabled on your headset.

You can find the official documentation on the Oculus developer website.

Once developer mode is enabled, plug your headset into your computer with the USB-C cable.

While the headset is connected to your computer:

Open Google Chrome on the computer

Access the special chrome://inspect/#devices URL

Locate the headset under the 'Remote Target' heading

Click 'inspect' on the page you want to interact with

There seems to be an 'inspect' option for each 'tab' open within the headset web browser:

From there, you have access to the browser window like you normally would with DevTools, so can access things from the JavaScript console like the URL, or to manipulate fields:

As far as doing this programatically, the DevTools protocol is documented, and there are many SDK's for it in various languages.

The DevTools protocol docs talk about the DOM Domain (among other things), which seems to give similar features as the above 'inspect' functionality. By using DOM.getDocument you can get the equivalent of accessing document from the Chrome DevTools console. This returns a Node object which contains values such as documentURL.


问:
How to use a lis of parameterized property names and type for a java bean
Say I have a bean

```<code>public class SomeBean{
     List<String> messages;
     List<Integer> scores;
     String id;
     int  number;
</code>```

....
    }

I am using the following code to process or dump the propreties

```<code>        BeanInfo beanInfo = Introspector.getBeanInfo(beanClass, Object.class);
        PropertyDescriptor descriptors[] = beanInfo.getPropertyDescriptors();
        int stop = descriptors.length;
        for (int i = 0; i < stop; ++i) {
            PropertyDescriptor descriptor = descriptors[i];
            logger.info(descriptor.getName() + " : " + descriptor.getPropertyType().getName() + ", writemethod :" + descriptor.getWriteMethod());

        }
</code>```

That I want to be able to get the parameterized type for the "scores" and "messages".
When I ruin the code, the value for the " descriptor.getPropertyType().getName()"  is "java.util.List" for both messages and scores .

How do I tell if the property descriptor for "message" is referring to List<String> and for "scores" is referring to List<Integer> ?

答:
As long as the fields have fully specified compile-time types like in your example (List<String> and not something like List<T>, that is) you can use reflection to get this information:

```<code>for (Field field : SomeBean.class.getDeclaredFields()) {
  Type type = field.getGenericType();
  System.out.println(field.getName() + ": " + type);
  if (type instanceof ParameterizedType) {
    ParameterizedType parameterized = (ParameterizedType) type;
    Type raw = parameterized.getRawType(); // This would be Class<List>, say
    Type[] typeArgs = parameterized.getActualTypeArguments();
    System.out.println(Arrays.toString(typeArgs));
  }
}
</code>```

Wasn't sure if you could do this with the bean-related code, but it looks like you can.

ContentLicense: CC BY-SA 3.0

Body:
Say I have a bean

public class SomeBean{
     List<String> messages;
     List<Integer> scores;
     String id;
     int  number;

....
    }

I am using the following code to process or dump the propreties

        BeanInfo beanInfo = Introspector.getBeanInfo(beanClass, Object.class);
        PropertyDescriptor descriptors[] = beanInfo.getPropertyDescriptors();
        int stop = descriptors.length;
        for (int i = 0; i < stop; ++i) {
            PropertyDescriptor descriptor = descriptors[i];
            logger.info(descriptor.getName() + " : " + descriptor.getPropertyType().getName() + ", writemethod :" + descriptor.getWriteMethod());

        }

That I want to be able to get the parameterized type for the "scores" and "messages".
When I ruin the code, the value for the " descriptor.getPropertyType().getName()"  is "java.util.List" for both messages and scores .

How do I tell if the property descriptor for "message" is referring to List<String> and for "scores" is referring to List<Integer> ?

Body:
As long as the fields have fully specified compile-time types like in your example (List<String> and not something like List<T>, that is) you can use reflection to get this information:

for (Field field : SomeBean.class.getDeclaredFields()) {
  Type type = field.getGenericType();
  System.out.println(field.getName() + ": " + type);
  if (type instanceof ParameterizedType) {
    ParameterizedType parameterized = (ParameterizedType) type;
    Type raw = parameterized.getRawType(); // This would be Class<List>, say
    Type[] typeArgs = parameterized.getActualTypeArguments();
    System.out.println(Arrays.toString(typeArgs));
  }
}

Wasn't sure if you could do this with the bean-related code, but it looks like you can.


问:
delay caused by fat argument in python multiprocessing
i am using multiprocessing in python to parallel some computing-heavy functions. but i found that there is a delay in process creating if passing a fat argument (e.g., a 1000-note networkx graph or a 1000000-item list). i experiment on two multiprocessing modules "multiprocessing" and "pathos", get the similar results. my question is how to avoid this kind of delay because it ruins the benefit brought by parallel computing.

in my sample code, i just pass a fat argument to the function for multiprocessing - the function body does not touch the argument as all.

the sample code using "multiprocessing"

```<code>import multiprocessing
import time

def f(args):
    (x, conn, t0, graph) = args
    ans = 1
    x0 = x
    t = time.time() - t0
    conn.send('factorial of %d: start@%.2fs' % (x0, t))
    while x > 1:
        ans *= x
        time.sleep(0.5)
        x -= 1
    t = time.time() - t0
    conn.send('factorial of %d: finish@%.2fs, res = %d' %(x0, t, ans))
    return ans

def main():
    var = (4, 8, 12, 20, 16)
    p = multiprocessing.Pool(processes = 4)
    p_conn, c_conn = multiprocessing.Pipe()
    params = []
    t0 = time.time()
    N = 1000
    import networkx as nx
    G = nx.complete_graph(N, nx.DiGraph())

    import random
    for (start, end) in G.edges:
        G.edges[start, end]['weight'] = random.random()

    for i in var:
        params.append((i, c_conn, t0, G))
    res = list(p.imap(f, params))
    p.close()
    p.join()

    print('output:')
    while p_conn.poll():
        print(p_conn.recv())
    t = time.time() - t0
    print('factorial of %s@%.2fs: %s' % (var, t, res))

if __name__ == '__main__':
    main()
</code>```

the output of the above sample code

```<code>output:
factorial of 4: start@29.78s
factorial of 4: finish@31.29s, res = 24
factorial of 8: start@53.56s
factorial of 8: finish@57.07s, res = 40320
factorial of 12: start@77.25s
factorial of 12: finish@82.75s, res = 479001600
factorial of 20: start@100.39s
factorial of 20: finish@109.91s, res = 2432902008176640000
factorial of 16: start@123.55s
factorial of 16: finish@131.05s, res = 20922789888000
factorial of (4, 8, 12, 20, 16)@131.06s: [24, 40320, 479001600, 2432902008176640000, 20922789888000]

Process finished with exit code 0
</code>```

according to the above output, there is around 24 second delays between two process creating

the sample code using "pathos"

```<code>import pathos
import multiprocess
import time

def f(x, conn, t0, graph):
    ans = 1
    x0 = x
    t = time.time() - t0
    conn.send('factorial of %d: start@%.2fs' % (x0, t))
    while x > 1:
        ans *= x
        time.sleep(0.5)
        x -= 1
    t = time.time() - t0
    conn.send('factorial of %d: finish@%.2fs, res = %d' %(x0, t, ans))
    return ans

def main():
    var = (4, 8, 12, 20, 16)
    p = pathos.multiprocessing.ProcessPool(nodes=4)
    p_conn, c_conn = multiprocess.Pipe()
    t0 = time.time()
    conn_s = [c_conn] * len(var)
    t0_s = [t0] * len(var)
    N = 1000
    import networkx as nx
    G = nx.complete_graph(N, nx.DiGraph())

    import random
    for (start, end) in G.edges:
        G.edges[start, end]['weight'] = random.random()

    res = list(p.imap(f, var, conn_s, t0_s, [G] * len(var)))

    print('output:')
    while p_conn.poll():
        print(p_conn.recv())
    t = time.time() - t0
    print('factorial of %s@%.2fs: %s' % (var, t, res))

if __name__ == '__main__':
    main()

</code>```

the output of the above sample code,

```<code>output:
factorial of 4: start@29.63s
factorial of 4: finish@31.13s, res = 24
factorial of 8: start@53.50s
factorial of 8: finish@57.00s, res = 40320
factorial of 12: start@76.94s
factorial of 12: finish@82.44s, res = 479001600
factorial of 20: start@100.72s
factorial of 20: finish@110.23s, res = 2432902008176640000
factorial of 16: start@123.69s
factorial of 16: finish@131.20s, res = 20922789888000
factorial of (4, 8, 12, 20, 16)@131.20s: [24, 40320, 479001600, 2432902008176640000, 20922789888000]

Process finished with exit code 0
</code>```

similarly, according to the above output, there is around 24 second delays between two process creating.

if i reduce the graph size (smaller node number), the delay decreases accordingly. i guess it is due to the extra time used for pickling/dilling the networkx graph as an argument.
ideally, first 4 processes should be created at the same time. how to avoid this cost? thank you!

UPDATE

Thanks to Alexander's kind answer, i remove the pipe in both "multiprocessing" and "pathos" codes. the "multiprocessing" code performs as Alexander's - delay reduced to 1 second, but the "pathos" code still has more than 20 seconds delay. the revised "pathos" code is posted below,

```<code>import pathos
import multiprocess
import time
from pympler import asizeof
import sys

def f(args):
    (x, graph) = args
    t = time.ctime()
    print('factorial of %d: start@%s' % (x, t))
    time.sleep(4)
    return x

def main():
    t0 = time.time()
    params = []

    var = (4, 8, 12, 20, 16)
    p = pathos.multiprocessing.ProcessPool(nodes=4)
    N = 1000
    import networkx as nx
    G = nx.complete_graph(N, nx.DiGraph())

    import random
    for (start, end) in G.edges:
        G.edges[start, end]['weight'] = random.random()

    print('Size of G by sys', sys.getsizeof(G), 'asizeof', asizeof.asizeof(G))
    print('G created in %.2f' %  (time.time() - t0))

    for i in var:
        params.append((i, G))
    res = list(p.imap(f, params))
    p.close()
    p.join()

if __name__ == '__main__':
    main()
</code>```

the output goes as

```<code>Size of G by sys 56 asizeof 338079824
G created in 17.36
factorial of 4: start@Fri May 31 11:39:26 2019
factorial of 8: start@Fri May 31 11:39:53 2019
factorial of 12: start@Fri May 31 11:40:19 2019
factorial of 20: start@Fri May 31 11:40:44 2019
factorial of 16: start@Fri May 31 11:41:10 2019

Process finished with exit code 0
</code>```

答:
I changed N to 50 and ran the "pathos" code with a debugger in PyCharm. Stopped after 'G created in 7.79'. The output below confirmed my suspicion about why it is slower with "pathos". Pathos uses connection and socket objects (depending on a platform) to pass arguments and start subprocess. This is why it is so much slower: in about 30 times. On the bright side: it works over the network.

Debug output:

/usr/local/bin/python3.7 "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py" --multiproc --qt-support=auto --client 127.0.0.1 --port 51876 --file /Users/alex/PycharmProjects/game/object_type.py
pydev debugger: process 1526 is connecting

Connected to pydev debugger (build 191.6605.12)
Size of G by sys 56 asizeof 57126904
G created in 7.79
Process ForkPoolWorker-3:
Process ForkPoolWorker-2:
Process ForkPoolWorker-1:
Process ForkPoolWorker-4:
Traceback (most recent call last):
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/multiprocess/process.py", line 297, in _bootstrap
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/multiprocess/process.py", line 297, in _bootstrap
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/multiprocess/process.py", line 99, in run
    self._target(*self._args, **self._kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/multiprocess/pool.py", line 110, in worker
    task = get()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/multiprocess/process.py", line 99, in run
    self._target(*self._args, **self._kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/multiprocess/queues.py", line 354, in get
    with self._rlock:
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/multiprocess/pool.py", line 110, in worker
    task = get()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/multiprocess/synchronize.py", line 102, in __enter__
    return self._semlock.__enter__()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/multiprocess/queues.py", line 354, in get
    with self._rlock:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/multiprocess/synchronize.py", line 102, in __enter__
    return self._semlock.__enter__()
KeyboardInterrupt
KeyboardInterrupt
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/multiprocess/process.py", line 297, in _bootstrap
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/multiprocess/process.py", line 99, in run
    self._target(*self._args, **self._kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/multiprocess/pool.py", line 110, in worker
    task = get()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/multiprocess/queues.py", line 355, in get
    res = self._reader.recv_bytes()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/multiprocess/connection.py", line 219, in recv_bytes
    buf = self._recv_bytes(maxlength)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/multiprocess/connection.py", line 410, in _recv_bytes
    buf = self._recv(4)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/multiprocess/connection.py", line 382, in _recv
    chunk = read(handle, remaining)
Traceback (most recent call last):
KeyboardInterrupt
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/multiprocess/process.py", line 297, in _bootstrap
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/multiprocess/process.py", line 99, in run
    self._target(*self._args, **self._kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/multiprocess/pool.py", line 110, in worker
    task = get()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/multiprocess/queues.py", line 354, in get
    with self._rlock:
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/multiprocess/synchronize.py", line 102, in __enter__
    return self._semlock.__enter__()
KeyboardInterrupt
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/multiprocess/pool.py", line 733, in next
    item = self._items.popleft()
IndexError: pop from an empty deque

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 1741, in <module>
    main()
  File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 1735, in main
    globals = debugger.run(setup['file'], None, None, is_module)
  File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 1135, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/Applications/PyCharm CE.app/Contents/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/Users/alex/PycharmProjects/game/object_type.py", line 100, in <module>
    outputs = list(p.imap(factorial, [(i, t0, G) for i in (4, 8, 12, 20, 16)]))
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/multiprocess/pool.py", line 737, in next
    self._cond.wait(timeout)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 296, in wait
    waiter.acquire()
KeyboardInterrupt
```

Body:
i am using multiprocessing in python to parallel some computing-heavy functions. but i found that there is a delay in process creating if passing a fat argument (e.g., a 1000-note networkx graph or a 1000000-item list). i experiment on two multiprocessing modules "multiprocessing" and "pathos", get the similar results. my question is how to avoid this kind of delay because it ruins the benefit brought by parallel computing.

in my sample code, i just pass a fat argument to the function for multiprocessing - the function body does not touch the argument as all.

the sample code using "multiprocessing"

import multiprocessing
import time

def f(args):
    (x, conn, t0, graph) = args
    ans = 1
    x0 = x
    t = time.time() - t0
    conn.send('factorial of %d: start@%.2fs' % (x0, t))
    while x > 1:
        ans *= x
        time.sleep(0.5)
        x -= 1
    t = time.time() - t0
    conn.send('factorial of %d: finish@%.2fs, res = %d' %(x0, t, ans))
    return ans

def main():
    var = (4, 8, 12, 20, 16)
    p = multiprocessing.Pool(processes = 4)
    p_conn, c_conn = multiprocessing.Pipe()
    params = []
    t0 = time.time()
    N = 1000
    import networkx as nx
    G = nx.complete_graph(N, nx.DiGraph())

    import random
    for (start, end) in G.edges:
        G.edges[start, end]['weight'] = random.random()

    for i in var:
        params.append((i, c_conn, t0, G))
    res = list(p.imap(f, params))
    p.close()
    p.join()

    print('output:')
    while p_conn.poll():
        print(p_conn.recv())
    t = time.time() - t0
    print('factorial of %s@%.2fs: %s' % (var, t, res))

if __name__ == '__main__':
    main()

the output of the above sample code

output:
factorial of 4: start@29.78s
factorial of 4: finish@31.29s, res = 24
factorial of 8: start@53.56s
factorial of 8: finish@57.07s, res = 40320
factorial of 12: start@77.25s
factorial of 12: finish@82.75s, res = 479001600
factorial of 20: start@100.39s
factorial of 20: finish@109.91s, res = 2432902008176640000
factorial of 16: start@123.55s
factorial of 16: finish@131.05s, res = 20922789888000
factorial of (4, 8, 12, 20, 16)@131.06s: [24, 40320, 479001600, 2432902008176640000, 20922789888000]

Process finished with exit code 0

according to the above output, there is around 24 second delays between two process creating

the sample code using "pathos"

import pathos
import multiprocess
import time

def f(x, conn, t0, graph):
    ans = 1
    x0 = x
    t = time.time() - t0
    conn.send('factorial of %d: start@%.2fs' % (x0, t))
    while x > 1:
        ans *= x
        time.sleep(0.5)
        x -= 1
    t = time.time() - t0
    conn.send('factorial of %d: finish@%.2fs, res = %d' %(x0, t, ans))
    return ans

def main():
    var = (4, 8, 12, 20, 16)
    p = pathos.multiprocessing.ProcessPool(nodes=4)
    p_conn, c_conn = multiprocess.Pipe()
    t0 = time.time()
    conn_s = [c_conn] * len(var)
    t0_s = [t0] * len(var)
    N = 1000
    import networkx as nx
    G = nx.complete_graph(N, nx.DiGraph())

    import random
    for (start, end) in G.edges:
        G.edges[start, end]['weight'] = random.random()

    res = list(p.imap(f, var, conn_s, t0_s, [G] * len(var)))

    print('output:')
    while p_conn.poll():
        print(p_conn.recv())
    t = time.time() - t0
    print('factorial of %s@%.2fs: %s' % (var, t, res))

if __name__ == '__main__':
    main()

the output of the above sample code,

output:
factorial of 4: start@29.63s
factorial of 4: finish@31.13s, res = 24
factorial of 8: start@53.50s
factorial of 8: finish@57.00s, res = 40320
factorial of 12: start@76.94s
factorial of 12: finish@82.44s, res = 479001600
factorial of 20: start@100.72s
factorial of 20: finish@110.23s, res = 2432902008176640000
factorial of 16: start@123.69s
factorial of 16: finish@131.20s, res = 20922789888000
factorial of (4, 8, 12, 20, 16)@131.20s: [24, 40320, 479001600, 2432902008176640000, 20922789888000]

Process finished with exit code 0

similarly, according to the above output, there is around 24 second delays between two process creating.

if i reduce the graph size (smaller node number), the delay decreases accordingly. i guess it is due to the extra time used for pickling/dilling the networkx graph as an argument.
ideally, first 4 processes should be created at the same time. how to avoid this cost? thank you!

UPDATE

Thanks to Alexander's kind answer, i remove the pipe in both "multiprocessing" and "pathos" codes. the "multiprocessing" code performs as Alexander's - delay reduced to 1 second, but the "pathos" code still has more than 20 seconds delay. the revised "pathos" code is posted below,

import pathos
import multiprocess
import time
from pympler import asizeof
import sys

def f(args):
    (x, graph) = args
    t = time.ctime()
    print('factorial of %d: start@%s' % (x, t))
    time.sleep(4)
    return x

def main():
    t0 = time.time()
    params = []

    var = (4, 8, 12, 20, 16)
    p = pathos.multiprocessing.ProcessPool(nodes=4)
    N = 1000
    import networkx as nx
    G = nx.complete_graph(N, nx.DiGraph())

    import random
    for (start, end) in G.edges:
        G.edges[start, end]['weight'] = random.random()

    print('Size of G by sys', sys.getsizeof(G), 'asizeof', asizeof.asizeof(G))
    print('G created in %.2f' %  (time.time() - t0))

    for i in var:
        params.append((i, G))
    res = list(p.imap(f, params))
    p.close()
    p.join()

if __name__ == '__main__':
    main()

the output goes as

Size of G by sys 56 asizeof 338079824
G created in 17.36
factorial of 4: start@Fri May 31 11:39:26 2019
factorial of 8: start@Fri May 31 11:39:53 2019
factorial of 12: start@Fri May 31 11:40:19 2019
factorial of 20: start@Fri May 31 11:40:44 2019
factorial of 16: start@Fri May 31 11:41:10 2019

Process finished with exit code 0


问:
Get value from Bottom Sheet Dialog Fragment
I'm starting bottomSheetDialogFragment from a fragment A.
I want to select the date from that bottomSheetDialogFragment then set it in the fragment A.

The select date is already done, I just want to get it in the fragment A to set it in some fields.

How can I get the value?
Any suggestions how to do it?

答: You can also use LocalBroadcastManager. And as hglf said, it is better to keep the empty constructor for your fragment and use newInstance(Type value) instead to instantiate your fragment if you still want to use the interface callBack way.</p>


问:
Wonders whether there's some principled way to define classes with getter/setter with less boilerplate
In Python world, IIUC, you generally have two kinds of options, every attribute is constant and frozen, like namedtuple, vs every attribute is modifiable.

You can write lots of getter/setter with @property. However, it's lots of boilerplates.

I like approaches like class Child(namedtuple(...)), however, it has the following downsides:

If in the inheritance you set __slots__ = (), then you can't add additional attribute into the child class.

If you don't set __slots__, then you can add additional attribute, however, there's no protection on assigning wrong attribute child.some_non_exist = some_value

Moreover, there's no way to optionally allow some attribute to be accessible and some attribute not.

I can have the following proposal, however, I don't know whether there's existing library for this.

Thanks!!

(I know attrs but I think it's focusing another set of problems.)

```<code>### The following is a proposal

@attr_acl
class A(object):
   x = attr_acl.frozen()    # x must be specified in __init__
   y = attr_acl.frozen(default = 5)
   z = attr_acl.mutable(default = 5)
   zz = attr_acl.mutable_freezable()
   g = attr_acl.mutable(is_final=True)

@attr_acl
class AA(X):
   o = attr_acl.mutable()

aa = AA(x=1, zz=2, o=3)
attr_acl.freeze(obj.zz)

### The followings must raise error
aa.x = 5
aa.zz = 6
aa.some_non_exist = 7
</code>```

答:
You should look harder at attrs and dataclasses.  They provide what you want:

```<code>@attr.s(slots=True)
class Coordinates(object):
    x = attr.ib()
    y = attr.ib()
</code>```

But also you should consider whether you need to protect your attributes.  It's easy to slip into a habit of overly defensive coding, where you work hard to prevent things that are not going to actually happen.

Body:
In Python world, IIUC, you generally have two kinds of options, every attribute is constant and frozen, like namedtuple, vs every attribute is modifiable.

You can write lots of getter/setter with @property. However, it's lots of boilerplates.

I like approaches like class Child(namedtuple(...)), however, it has the following downsides:

If in the inheritance you set __slots__ = (), then you can't add additional attribute into the child class.

If you don't set __slots__, then you can add additional attribute, however, there's no protection on assigning wrong attribute child.some_non_exist = some_value

Moreover, there's no way to optionally allow some attribute to be accessible and some attribute not.

I can have the following proposal, however, I don't know whether there's existing library for this.

Thanks!!

(I know attrs but I think it's focusing another set of problems.)

### The following is a proposal

@attr_acl
class A(object):
   x = attr_acl.frozen()    # x must be specified in __init__
   y = attr_acl.frozen(default = 5)
   z = attr_acl.mutable(default = 5)
   zz = attr_acl.mutable_freezable()
   g = attr_acl.mutable(is_final=True)

@attr_acl
class AA(X):
   o = attr_acl.mutable()

aa = AA(x=1, zz=2, o=3)
attr_acl.freeze(obj.zz)

### The followings must raise error
aa.x = 5
aa.zz = 6
aa.some_non_exist = 7

Body:
You should look harder at attrs and dataclasses.  They provide what you want:

@attr.s(slots=True)
class Coordinates(object):
    x = attr.ib()
    y = attr.ib()

But also you should consider whether you need to protect your attributes.  It's easy to slip into a habit of overly defensive coding, where you work hard to prevent things that are not going to actually happen.


问:
I am trying to get the Seconds since midnight: 86339
I am trying to get the Seconds since midnight:  86339

I tried writing a program and i get the results

Enter hour:11
Enter minute:58
Enter second:59
Enter frame:PM
Seconds since midnight: 43139
```

```hour = input("Enter hour:")
minute = input("Enter minute:")
second = input("Enter second:")
frame = raw_input("Enter frame:")

time = ( 3600 * hour + minute * 60 + second )
print "Seconds since midnight:",time
```

<p>This is the actual results i want to produce </p>

<pre class="lang-none prettyprint-override"><code>Enter hour: 11
Enter minute: 58
Enter second: 59
Enter AM or PM: PM
Seconds since midnight:  86339
</code>```

Enter hour: 12
Enter minute: 7
Enter second: 20
Enter AM or PM: AM
Seconds since midnight: 440

Enter hour: 12
Enter minute: 14
Enter second: 57
Enter AM or PM: PM
Seconds since midnight: 44097

答:
Change your time calculation to something like this:</p>

```<code>time = ( 3600 * hour + minute * 60 + second )
if "PM" == frame:
    time += 12 * 60 * 60
</code>```

Body:
I am trying to get the Seconds since midnight:  86339

I tried writing a program and i get the results

Enter hour:11
Enter minute:58
Enter second:59
Enter frame:PM
Seconds since midnight: 43139

hour = input("Enter hour:")
minute = input("Enter minute:")
second = input("Enter second:")
frame = raw_input("Enter frame:")

time = ( 3600 * hour + minute * 60 + second )
print "Seconds since midnight:",time

This is the actual results i want to produce

Enter hour: 11
Enter minute: 58
Enter second: 59
Enter AM or PM: PM
Seconds since midnight:  86339

Enter hour: 12
Enter minute: 7
Enter second: 20
Enter AM or PM: AM
Seconds since midnight: 440

Enter hour: 12
Enter minute: 14
Enter second: 57
Enter AM or PM: PM
Seconds since midnight: 44097

Body:
Change your time calculation to something like this:

time = ( 3600 * hour + minute * 60 + second )
if "PM" == frame:
    time += 12 * 60 * 60


问:
Limiting floats to two decimal points
I want a to be rounded to 13.95. I tried using round, but I get:

```<code>>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
</code>```

For the analogous issue with the standard library Decimal class, see How can I format a decimal to always show 2 decimal places?.

答:
Use combination of Decimal object and round() method.</p>

```<code>Python 3.7.3
>>> from decimal import Decimal
>>> d1 = Decimal (13.949999999999999) # define a Decimal
>>> d1
Decimal('13.949999999999999289457264239899814128875732421875')
>>> d2 = round(d1, 2) # round to 2 decimals
>>> d2
Decimal('13.95')
</code>```

OwnerDisplayName: kevin

LastEditorDisplayName: Gareth

Title: Limiting floats to two decimal points

Body:
I want a to be rounded to 13.95. I tried using round, but I get:

>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999

For the analogous issue with the standard library Decimal class, see How can I format a decimal to always show 2 decimal places?.

Body:
Use combination of Decimal object and round() method.

Python 3.7.3
>>> from decimal import Decimal
>>> d1 = Decimal (13.949999999999999) # define a Decimal
>>> d1
Decimal('13.949999999999999289457264239899814128875732421875')
>>> d2 = round(d1, 2) # round to 2 decimals
>>> d2
Decimal('13.95')


问:
Error: File google-services.json is missing. The Google Services Plugin cannot function without it.
i have already include google-services.json file in my app but it still give me error.
Error:Execution failed for task ':app:processDebugGoogleServices'.

File google-services.json is missing. The Google Services Plugin cannot function without it.
     Searched Location:
    C:\Users\vikas\AndroidStudioProjects\FireBaseFunctionality\app\src\debug\google-services.json
    C:\Users\vikas\AndroidStudioProjects\FireBaseFunctionality\app\google-services.json

答:
just change in the build.gradle the line

compile fileTree (dir: 'libs', include: ['* .jar'])

to

implementation fileTree(dir: 'libs', include: ['*.jar'])


问:
How to draw an 1 pixel line using Javafx Canvas?
I've been googling and searching, found some some related questions/posts but none of the address my problem.

I am drawing lines directly on canvas (JavaFX) using:

```<code>gc.setStroke(color);
gc.setLineWidth(lineWidth);
gc.strokeLine(startX, startY, endX, endY);
</code>```

I want 1 pixel width lines. So I set lineWidth=1.
I get this:

Note that the lines are blurred. It is not 1 pixel.
I've tried to set lineWidth to 0.1 or 0.01, etc. It does not change the result.

By the way... I do not understand why this parameter is a double. I read somewhere that it has to do with DPI. But I do not understand what is the unit and how it is converted to pixels.
Oracle's documentation does not help. (or I did not find the one that helps)

I'd like to get this instead:

This was implemented in another platform. Note that lines are sharp and have just one 1 pixel.

答:
Use coordinates in this notation x.5.

Look my example:

```<code>    gc.setFill(Color.BLACK);
    gc.setLineWidth(1.0);

    gc.strokeRect(50, 100, 25.0, 25.0);
    gc.strokeRect(100.5, 100.5, 25.0, 25.0);
</code>```

You will get two squares, the second sharp.

Reference: https://dlsc.com/2014/04/10/javafx-tip-2-sharp-drawing-with-canvas-api/

Body:
I've been googling and searching, found some some related questions/posts but none of the address my problem.

I am drawing lines directly on canvas (JavaFX) using:

gc.setStroke(color);
gc.setLineWidth(lineWidth);
gc.strokeLine(startX, startY, endX, endY);

I want 1 pixel width lines. So I set lineWidth=1.
I get this:

Note that the lines are blurred. It is not 1 pixel.
I've tried to set lineWidth to 0.1 or 0.01, etc. It does not change the result.

By the way... I do not understand why this parameter is a double. I read somewhere that it has to do with DPI. But I do not understand what is the unit and how it is converted to pixels.
Oracle's documentation does not help. (or I did not find the one that helps)

I'd like to get this instead:

This was implemented in another platform. Note that lines are sharp and have just one 1 pixel.

Body:
Use coordinates in this notation x.5.

Look my example:

    gc.setFill(Color.BLACK);
    gc.setLineWidth(1.0);

    gc.strokeRect(50, 100, 25.0, 25.0);
    gc.strokeRect(100.5, 100.5, 25.0, 25.0);

You will get two squares, the second sharp.

Reference: https://dlsc.com/2014/04/10/javafx-tip-2-sharp-drawing-with-canvas-api/


问:
Trying to read data from War Thunder local host with python
Basically I'm using python to send serial data to an arduino so that I can make moving dials using data from the game. This would work because you can use the url "localhost:8111" to give you a list of these stats when ingame. The problem is I'm using urllib and BeautifulSoup but they seem to be blindly reading the source code not giving the data I need.

The data I need comes up when I inspect the element of that page. Other pages seem to suggest that using something to run the HTML in python would fix this but I have found no way of doing this. Any help here would be great thanks.

答:
Here is a Python module that you can use to get all air vehicle telemetry data from War Thunder localhost server pages "indicators" and "status". The contents of each of these pages are static JSON descriptions of the vehicle's current telemetry values.

The Python package uses the requests module to query the localhost server for the data, converts the returned JSON data into dictionaries, and then consolidates all the data into a singular telemetry dictionary. This data can then be used for other Python processes such as datalogging or graphing.


问:
how to fix Encountered the symbol "WHERE" when expecting one of the following and {
i'm doing an OLD exame for my next exams and i encountered those problems :

```<code>**1-** ORA-06550: line 18, column 1:
PLS-00103: Encountered the symbol "{" when expecting one of the following:

**2-** ORA-06550: line 23, column 1:
PLS-00103: Encountered the symbol "WHERE" when expecting one of the following:
</code>```

i tried many things like to change the IF statement to look for errors type of ( ; '' ) missing etc but nothing really works

Code :

```<code>declare

cursor cur is select * from emp where sal > 0 order by sal ;

enreg emp%rowtype;

x number;

i number;

chaine dept.ename%type;

begin

open cur;

select count ename into x from emp where sal > 0;

i:=0;

loop

fetch cur into enreg;

i:=i+1;

IF i<x/4 THEN

{

dbms_output.put_line('le nom du ' || i || 'salairié est '|| enreg.ename);

dbms_output.put_line('lancien salaire du ' || i || 'salairié est '|| enreg.sal);

update emp

set emp.sal = emp.sal+((emp.sal*4)/100);

WHERE emp.sal = enreg.sal;

select dname from dept into chaine where dept.deptno=enreg.deptno;

enreg.sal := emp.sal;

dbms_output.putline('le depart  du ' || i || 'salairié est '|| chaine);

dbms_output.putline('le nouveau salaire du ' || i || 'salairié est '|| enreg.sal);

}

elseif i>=x/4 and i<=x/2 then

{

dbms_output.putline('le nom du ' || i || 'salairié est '|| enreg.ename);

dbms_output.putline('lancien salaire du ' || i || 'salairié est '|| enreg.sal);

update emp

set emp.sal = emp.sal+((emp.sal*6)/100);

where emp.sal=enreg.sal;

select dname from dept into chaine where dept.deptno=enreg.deptno;

enreg.sal := emp.sal;

dbms_output.put_line('le depart  du ' || i || 'salairié est '|| chaine);

dbms_output.put_line('le nouveau salaire du ' || i || 'salairié est '|| enreg.sal);

}

else

{

dbms_output.put_line('le nom du ' || i || 'salairié est '|| enreg.ename);

dbms_output.put_line('lancien salaire du ' || i || 'salairié est '|| enreg.sal);

update emp

set emp.sal = emp.sal+((emp.sal*8)/100);

where emp.sal=enreg.sal;

select dname from dept into chaine where dept.deptno=enreg.deptno;

enreg.sal := emp.sal;

dbms_output.putl_ine('le depart  du ' || i || 'salairié est '|| chaine);

dbms_output.put_line('le nouveau salaire du ' || i || 'salairié est '|| enreg.sal);

}

end if ;

exit when cur%notfound;

end loop;

end;
</code>```

END CODE

```<code>the expected results is to upgrade the salary
the first 1/4 of salaries have 4% upgrade
the other 1/4 have 6 %
the rest 8%
in the same time and with one cursor i must display the old value of the sal and the new value  and the name of the person + the department which he is in it
</code>```

tables are :

emp
 (

EMPNO   NUMBER(4,0) No  -   1

ENAME   VARCHAR2(10)

JOB VARCHAR2(9)
MGR NUMBER(4,0)

HIREDATE    DATE

SAL NUMBER(7,2)

COMM    NUMBER(7,2)

DEPTNO  NUMBER(2,0)

)

dept
(

DEPTNO  NUMBER(2,0)

DNAME   VARCHAR2(14)

LOC VARCHAR2(13)

)

答:
This clearly is an assignment so instead of a providing the solution I'll point out errors and where appropriate give you a pointer where to find the an answer, but you will need to build the solution. In the long I think that'll be of greater benefit.

```<code>select count ename into x from emp where sal > 0;
</code>```

This syntax for this statement is invalid. See Count function.

```<code>update emp
set emp.sal = emp.sal+((emp.sal*4)/100);
WHERE emp.sal = enreg.sal;
</code>```

These statements taken together also have invalid syntax. It seems you are thinking the semicolon - ; - indicates end of line but it actually indicates end of statement. I image you don't want the first - it is actually valid, but it will update every row in the table.  Without that semicolon only subset of rows would be updated, but that subset would be every matching salary, including those already updated. See Update within Cursor

A couple general comments.

Your procedure contains a lot of unnecessary repetition.  3 update statements for the EMP and corresponding selects for the DEPT table. You could instead define a variable for the percentage (calculated as 4,6 or 8) as appropriate then use that variable in a single update. And a step further, you can JOIN DEPT to EMP in the cursor and not then need an independent select for each row you process. Just a way to think about processing sets instead on individual rows.

All in addition to what @AlexPoole has pointed out.

Body:
i'm doing an OLD exame for my next exams and i encountered those problems :

**1-** ORA-06550: line 18, column 1:
PLS-00103: Encountered the symbol "{" when expecting one of the following:

**2-** ORA-06550: line 23, column 1:
PLS-00103: Encountered the symbol "WHERE" when expecting one of the following:

i tried many things like to change the IF statement to look for errors type of ( ; '' ) missing etc but nothing really works

Code :

declare

cursor cur is select * from emp where sal > 0 order by sal ;

enreg emp%rowtype;

x number;

i number;

chaine dept.ename%type;

begin

open cur;

select count ename into x from emp where sal > 0;

i:=0;

loop

fetch cur into enreg;

i:=i+1;

IF i<x/4 THEN

{

dbms_output.put_line('le nom du ' || i || 'salairié est '|| enreg.ename);

dbms_output.put_line('lancien salaire du ' || i || 'salairié est '|| enreg.sal);

update emp

set emp.sal = emp.sal+((emp.sal*4)/100);

WHERE emp.sal = enreg.sal;

select dname from dept into chaine where dept.deptno=enreg.deptno;

enreg.sal := emp.sal;

dbms_output.putline('le depart  du ' || i || 'salairié est '|| chaine);

dbms_output.putline('le nouveau salaire du ' || i || 'salairié est '|| enreg.sal);

}

elseif i>=x/4 and i<=x/2 then

{

dbms_output.putline('le nom du ' || i || 'salairié est '|| enreg.ename);

dbms_output.putline('lancien salaire du ' || i || 'salairié est '|| enreg.sal);

update emp

set emp.sal = emp.sal+((emp.sal*6)/100);

where emp.sal=enreg.sal;

select dname from dept into chaine where dept.deptno=enreg.deptno;

enreg.sal := emp.sal;

dbms_output.put_line('le depart  du ' || i || 'salairié est '|| chaine);

dbms_output.put_line('le nouveau salaire du ' || i || 'salairié est '|| enreg.sal);

}

else

{

dbms_output.put_line('le nom du ' || i || 'salairié est '|| enreg.ename);

dbms_output.put_line('lancien salaire du ' || i || 'salairié est '|| enreg.sal);

update emp

set emp.sal = emp.sal+((emp.sal*8)/100);

where emp.sal=enreg.sal;

select dname from dept into chaine where dept.deptno=enreg.deptno;

enreg.sal := emp.sal;

dbms_output.putl_ine('le depart  du ' || i || 'salairié est '|| chaine);

dbms_output.put_line('le nouveau salaire du ' || i || 'salairié est '|| enreg.sal);

}

end if ;

exit when cur%notfound;

end loop;

end;

END CODE

the expected results is to upgrade the salary
the first 1/4 of salaries have 4% upgrade
the other 1/4 have 6 %
the rest 8%
in the same time and with one cursor i must display the old value of the sal and the new value  and the name of the person + the department which he is in it

tables are :

emp
 (

EMPNO   NUMBER(4,0) No  -   1

ENAME   VARCHAR2(10)

JOB VARCHAR2(9)
MGR NUMBER(4,0)

HIREDATE    DATE

SAL NUMBER(7,2)

COMM    NUMBER(7,2)

DEPTNO  NUMBER(2,0)

)

dept
(

DEPTNO  NUMBER(2,0)

DNAME   VARCHAR2(14)

LOC VARCHAR2(13)

)

Body:
This clearly is an assignment so instead of a providing the solution I'll point out errors and where appropriate give you a pointer where to find the an answer, but you will need to build the solution. In the long I think that'll be of greater benefit.

select count ename into x from emp where sal > 0;

This syntax for this statement is invalid. See Count function.

update emp
set emp.sal = emp.sal+((emp.sal*4)/100);
WHERE emp.sal = enreg.sal;

These statements taken together also have invalid syntax. It seems you are thinking the semicolon - ; - indicates end of line but it actually indicates end of statement. I image you don't want the first - it is actually valid, but it will update every row in the table.  Without that semicolon only subset of rows would be updated, but that subset would be every matching salary, including those already updated. See Update within Cursor

A couple general comments.

Your procedure contains a lot of unnecessary repetition.  3 update statements for the EMP and corresponding selects for the DEPT table. You could instead define a variable for the percentage (calculated as 4,6 or 8) as appropriate then use that variable in a single update. And a step further, you can JOIN DEPT to EMP in the cursor and not then need an independent select for each row you process. Just a way to think about processing sets instead on individual rows.

All in addition to what @AlexPoole has pointed out.


问:
How to schedule a Cloud Datastore export with App Engine in Python3
I have an app which stores user data in GCP Datastore.
I have made a cron job that is scheduled to export the data in Datastore using the instructions given here.

However, I need to change python2 to python3.

According to docs,app uses a app_identity library to obtain tokens.

```<code>    from google.appengine.api import app_identity
    access_token, _ = app_identity.get_access_token('https://www.googleapis.com/auth/datastore')
</code>```

But this library is not supported in python3 according to here.

How can I get a access_token in python3?

答:
Checkout the google-api-python-client library. It's supported in python 3 and makes it easy to build requests for the Cloud Datastore API.

Another thing you'll need to change is the webapp2 library since it's also not supported in python 3. You can replace it with something like Flask.

Here's an example of the app rewritten for python 3:

app.yaml

```<code>runtime: python37

handlers:
- url: /.*
  script: auto
</code>```

(deploy to a non-default service if needed with service: service_name)

requirements.txt

```<code>Flask
google-api-python-client
</code>```

main.py

```<code>import datetime
import os
from googleapiclient.discovery import build

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

@app.route('/cloud-datastore-export')
def export():
    # Deny if not from the Cron Service
    assert request.headers['X-Appengine-Cron']
    # Deny if output_url_prefix not set correctly
    output_url_prefix = request.args.get('output_url_prefix')
    assert output_url_prefix and output_url_prefix.startswith('gs://')
    timestamp = datetime.datetime.now().strftime('%Y%m%d-%H%M%S')
    if '/' not in output_url_prefix[5:]:
      # Only a bucket name has been provided - no prefix or trailing slash
      output_url_prefix += '/' + timestamp
    else:
      output_url_prefix += timestamp
    kinds = request.args.getlist('kind')
    namespace_ids = request.args.getlist('namespace_id')
    entity_filter = {
        'kinds': kinds,
        'namespace_ids': namespace_ids
    }
    body = {
        'output_url_prefix': output_url_prefix,
        'entity_filter': entity_filter
    }
    project_id = os.environ.get('GOOGLE_CLOUD_PROJECT')
    client = build('datastore', 'v1')
    client.projects().export(projectId=project_id, body=body).execute()
    return 'Operation started'

if __name__ == '__main__':
    # This is used when running locally only. When deploying to Google App
    # Engine, a webserver process such as Gunicorn will serve the app. This
    # can be configured by adding an `entrypoint` to app.yaml.
    # Flask's development server will automatically serve static files in
    # the "static" directory. See:
    # http://flask.pocoo.org/docs/1.0/quickstart/#static-files. Once deployed,
    # App Engine itself will serve those files as configured in app.yaml.
    app.run(host='127.0.0.1', port=8080, debug=True)
</code>```

Body:
I have an app which stores user data in GCP Datastore.
I have made a cron job that is scheduled to export the data in Datastore using the instructions given here.

However, I need to change python2 to python3.

According to docs,app uses a app_identity library to obtain tokens.

    from google.appengine.api import app_identity
    access_token, _ = app_identity.get_access_token('https://www.googleapis.com/auth/datastore')

But this library is not supported in python3 according to here.

How can I get a access_token in python3?

Body:
Checkout the google-api-python-client library. It's supported in python 3 and makes it easy to build requests for the Cloud Datastore API.

Another thing you'll need to change is the webapp2 library since it's also not supported in python 3. You can replace it with something like Flask.

Here's an example of the app rewritten for python 3:

app.yaml

runtime: python37

handlers:
- url: /.*
  script: auto

(deploy to a non-default service if needed with service: service_name)

requirements.txt

Flask
google-api-python-client

main.py

import datetime
import os
from googleapiclient.discovery import build

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

@app.route('/cloud-datastore-export')
def export():
    # Deny if not from the Cron Service
    assert request.headers['X-Appengine-Cron']
    # Deny if output_url_prefix not set correctly
    output_url_prefix = request.args.get('output_url_prefix')
    assert output_url_prefix and output_url_prefix.startswith('gs://')
    timestamp = datetime.datetime.now().strftime('%Y%m%d-%H%M%S')
    if '/' not in output_url_prefix[5:]:
      # Only a bucket name has been provided - no prefix or trailing slash
      output_url_prefix += '/' + timestamp
    else:
      output_url_prefix += timestamp
    kinds = request.args.getlist('kind')
    namespace_ids = request.args.getlist('namespace_id')
    entity_filter = {
        'kinds': kinds,
        'namespace_ids': namespace_ids
    }
    body = {
        'output_url_prefix': output_url_prefix,
        'entity_filter': entity_filter
    }
    project_id = os.environ.get('GOOGLE_CLOUD_PROJECT')
    client = build('datastore', 'v1')
    client.projects().export(projectId=project_id, body=body).execute()
    return 'Operation started'

if __name__ == '__main__':
    # This is used when running locally only. When deploying to Google App
    # Engine, a webserver process such as Gunicorn will serve the app. This
    # can be configured by adding an `entrypoint` to app.yaml.
    # Flask's development server will automatically serve static files in
    # the "static" directory. See:
    # http://flask.pocoo.org/docs/1.0/quickstart/#static-files. Once deployed,
    # App Engine itself will serve those files as configured in app.yaml.
    app.run(host='127.0.0.1', port=8080, debug=True)


问:
Is Lightweight Code Generation (LCG) dead?
In the .NET 2.0-3.5 frameworks, LCG (aka the DynamicMethod class) was a decent way to emit lightweight methods at runtime when no class structure was needed to support them.

In .NET 4.0, expression trees now support statements and blocks, and as such appear to provide sufficient functionality to build just about any functionality you could require from such a method, and can be constructed in a much easier and safer way than directly emitting CIL op-codes. (This statement is borne from today's experimentation of converting some of our most complex LCG code to use expression tree building and compilation instead.)

So is there any reason why one would use LCG in any new code? Is there anything it can do that expression trees cannot? Or is it now a 'dead' piece of functionality?

答:
Well, this question's pretty old now, and I'm waiting for a tf get to complete... so I'll answer it myself.

Yes, LCG is dead in most cases.

We used to make quite a bit of use of LCG and it has now all been converted to use expression trees instead. They are much easier to build, the code is significantly easier to maintain and debug, and the error messages are generally more informative than 'Operation could destabilize the runtime' when you get things wrong during development.

But, perhaps most importantly, expression trees are composable in a way that Reflection.Emit is not. This means the architecture of the components used for runtime code generation can be more modular and even allow plugins to extend the code generation framework.

The one thing I've found that is supported by Reflection.Emit that isn't directly supported in expression trees is setting .initonly fields. This, however, can be achieved by using a little helper class and invoking it in the expression tree, for example the one I used is below:

```<code>internal static class FieldHelper
{
    public static TTarget AssignInitOnlyField<TTarget, TField>(
        TTarget target, string fieldName, TField value)
    {
        var field = target.GetType().GetField(
            fieldName,
            BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
        var boxed = (object)target; // required for value type support
        field.SetValue(boxed, value);
        return (TTarget)boxed;
    }
}
</code>```

It's worth mentioning the one down-side of using expression trees rather than LCG is that the construction and compilation of the expression trees is definitely slower than emitting the raw op-codes directly. Assuming you're caching the compiled methods this is unlikely to be a significant problem, but it's the one reason that could still compel you to use LCG.

ContentLicense: CC BY-SA 2.5

Body:
Well, this question's pretty old now, and I'm waiting for a tf get to complete... so I'll answer it myself.

Yes, LCG is dead in most cases.

We used to make quite a bit of use of LCG and it has now all been converted to use expression trees instead. They are much easier to build, the code is significantly easier to maintain and debug, and the error messages are generally more informative than 'Operation could destabilize the runtime' when you get things wrong during development.

But, perhaps most importantly, expression trees are composable in a way that Reflection.Emit is not. This means the architecture of the components used for runtime code generation can be more modular and even allow plugins to extend the code generation framework.

The one thing I've found that is supported by Reflection.Emit that isn't directly supported in expression trees is setting .initonly fields. This, however, can be achieved by using a little helper class and invoking it in the expression tree, for example the one I used is below:

internal static class FieldHelper
{
    public static TTarget AssignInitOnlyField<TTarget, TField>(
        TTarget target, string fieldName, TField value)
    {
        var field = target.GetType().GetField(
            fieldName,
            BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
        var boxed = (object)target; // required for value type support
        field.SetValue(boxed, value);
        return (TTarget)boxed;
    }
}

It's worth mentioning the one down-side of using expression trees rather than LCG is that the construction and compilation of the expression trees is definitely slower than emitting the raw op-codes directly. Assuming you're caching the compiled methods this is unlikely to be a significant problem, but it's the one reason that could still compel you to use LCG.


问:
Xamarin Forms Drag Image between Views
I have an application in Xamarin Forms, and I need that the user can choose one image from below and drag anywhere he wants to in the top view, the idea is: The below view with the images are the home rooms, and the top view is the Houseplant, the user can create his houseplant by dragging and rotating the images, and then finally save the top view as a jpg or png image.

I've searched here and 2 3 pages of google about drag and etc, but I haven't found anything that could help me with that, I tried pan gesture, tap gesture, but no success =[

Sorry if it is duplicated or something, this is my first post, and I really couldn't find anything.

How can I get this working in Xamarin.Forms or at least with custom renderers and etc?

Thank you guys.

Sample image of what I need

答:
Make sure your page or Image is not in a scrollView.
If ScrollView is enabled for both orientations, Pan-Gesture wont work.
.
.</p>

Title: Xamarin Forms Drag Image between Views


问:
Add audio (with an offset) to video with FFMPEG
I have a 10 minute video and a 50 minute audio mp3.
The video starts at 500 seconds into the audio.
Using FFMPEG, how can I add the the audio to the video but specify a 500 seconds audio offset (So that they sync up)?

EDIT:

Down the bottom of this page it suggests how to specify an offset.

```<code>$ ffmpeg -i video_source -itsoffet delay -i audio_source -map 0:x -map 1:y .......
</code>```

However, when I apply this, it still starts the audio from the start.

答:
We are 8 years later, and the -itsoffset does work.

Exactly as in your linked page:

```<code>ffmpeg -i input_1 -itsoffset 00:00:03 -i input_2
</code>```

Note that you place the -itsoffset switch before the input you want to delay, in this case input_2 will be delayed.

So in your case that the video starts later, you would add -itsoffset 00:08:20 before the video input.

Body:
I have a 10 minute video and a 50 minute audio mp3.
The video starts at 500 seconds into the audio.
Using FFMPEG, how can I add the the audio to the video but specify a 500 seconds audio offset (So that they sync up)?

EDIT:

Down the bottom of this page it suggests how to specify an offset.

$ ffmpeg -i video_source -itsoffet delay -i audio_source -map 0:x -map 1:y .......

However, when I apply this, it still starts the audio from the start.

Body:
We are 8 years later, and the -itsoffset does work.

Exactly as in your linked page:

ffmpeg -i input_1 -itsoffset 00:00:03 -i input_2

Note that you place the -itsoffset switch before the input you want to delay, in this case input_2 will be delayed.

So in your case that the video starts later, you would add -itsoffset 00:08:20 before the video input.


问:
Notification only sent once from service
I am writing a service to notify every few seconds, and a notification appears once but the expected result is that it notifies multiple times, where it appears multiple times in the list.

I know that the notification id must change between multiple notifications for it to appear multiple times, so I used an AtomicInteger to increment the notification id every time the notification is sent.

At the top of the class I have the following variables declared:

AtomicInteger count;
private Timer timer;
```

<p>Then in the method onCreate() I have the following code:</p>

<pre class="lang-java prettyprint-override"><code>    @Override
    public void onCreate() {
        count = new AtomicInteger(0);

        final NotificationManager notificationManager = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);

        timer = new Timer();

        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                Notification notification = new Notification.Builder(SiteCheckService.this)
                        .setContentTitle("Notification")
                        .setContentText("You should see this notification.")
                        .setSmallIcon(R.drawable.ic_launcher_foreground)
                        .build();
                notificationManager.notify(count.incrementAndGet(), notification);

            }
        };
        timer.schedule(task, 15000);
    }

</code>```

And the onDestroy method is as follows:

  @Override
    public void onDestroy() {
        timer.cancel();
        timer.purge();
    }

```

I expect the notification to be sent multiple times, but it is only sent one time. There are no errors in logcat.

答:
i suggest you to use and store your notification in a sharedPreferences element

```<code>final String Pref_Name = "Notification";
notificationPreferences = context.getSharedPreferences(Pref_Name, Context.MODE_PRIVATE);
editor = notificationPreferences.edit();
notificationCount = notificationPreferences.getInt("notifCountNumber", 0);
</code>```

and after your notify() method

```<code> editor.putInt("notifCountNumber",notificationCount+1);
 editor.commit();
</code>```

Body:
I am writing a service to notify every few seconds, and a notification appears once but the expected result is that it notifies multiple times, where it appears multiple times in the list.

I know that the notification id must change between multiple notifications for it to appear multiple times, so I used an AtomicInteger to increment the notification id every time the notification is sent.

At the top of the class I have the following variables declared:

AtomicInteger count;
private Timer timer;

Then in the method onCreate() I have the following code:

    @Override
    public void onCreate() {
        count = new AtomicInteger(0);

        final NotificationManager notificationManager = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);

        timer = new Timer();

        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                Notification notification = new Notification.Builder(SiteCheckService.this)
                        .setContentTitle("Notification")
                        .setContentText("You should see this notification.")
                        .setSmallIcon(R.drawable.ic_launcher_foreground)
                        .build();
                notificationManager.notify(count.incrementAndGet(), notification);

            }
        };
        timer.schedule(task, 15000);
    }

And the onDestroy method is as follows:

  @Override
    public void onDestroy() {
        timer.cancel();
        timer.purge();
    }

I expect the notification to be sent multiple times, but it is only sent one time. There are no errors in logcat.

Body:
i suggest you to use and store your notification in a sharedPreferences element

final String Pref_Name = "Notification";
notificationPreferences = context.getSharedPreferences(Pref_Name, Context.MODE_PRIVATE);
editor = notificationPreferences.edit();
notificationCount = notificationPreferences.getInt("notifCountNumber", 0);

and after your notify() method

 editor.putInt("notifCountNumber",notificationCount+1);
 editor.commit();


问:
Flask raises TemplateNotFound error even though template file exists
I am trying to render the file home.html.  The file exists in my project, but I keep getting jinja2.exceptions.TemplateNotFound: home.html when I try to render it.  Why can't Flask find my template?

```<code>from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('home.html')
</code>```

```<code>/myproject
    app.py
    home.html
</code>```

答:
If you must use a customized project directory structure (other than the accepted answer project structure),
we have the option to tell flask to look in the appropriate level of the directory hierarchy.

for example..

```<code>    app = Flask(__name__, template_folder='../templates')
</code>```
```<code>    app = Flask(__name__, template_folder='../templates', static_folder='../static')
</code>```

Starting with ../ moves one directory backwards and starts there.

Starting with ../../ moves two directories backwards and starts there (and so on...).

Within a sub-directory...

```<code>template_folder='templates/some_template'
</code>```

Body:
I am trying to render the file home.html.  The file exists in my project, but I keep getting jinja2.exceptions.TemplateNotFound: home.html when I try to render it.  Why can't Flask find my template?

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('home.html')

/myproject
    app.py
    home.html

Body:
If you must use a customized project directory structure (other than the accepted answer project structure),
we have the option to tell flask to look in the appropriate level of the directory hierarchy.

for example..

    app = Flask(__name__, template_folder='../templates')

    app = Flask(__name__, template_folder='../templates', static_folder='../static')

Starting with ../ moves one directory backwards and starts there.

Starting with ../../ moves two directories backwards and starts there (and so on...).

Within a sub-directory...

template_folder='templates/some_template'


问:
Sql Server Shrinking temp db mdf and ndf
So my question is that even after the job runs and I'm enforcing the mdf (main tempdb file) to be shrunk to about 10mb or so why is it NOT doing it?
I have tried to run this job after my most heavy lifting ETL jobs (that pulls from various sources and preps data for reporting needs). This specific server IS NOT used for reporting procs. I'm just curious as to why the shrink does not happen? Should I be taking a full backup of Temp db? and then delete the backup?
Sql job that I did my research here from previous threads and posts and built.
Sql server job

```<code>dbcc shrinkdatabase (tempdb, 97)

-- Clean all buffers and caches
DBCC DROPCLEANBUFFERS;
DBCC FREEPROCCACHE;
DBCC FREESYSTEMCACHE('ALL');
DBCC FREESESSIONCACHE;

DBCC SHRINKFILE (temp2,TRUNCATEONLY);
DBCC SHRINKFILE (temp3,TRUNCATEONLY);
DBCC SHRINKFILE (temp4,TRUNCATEONLY);
DBCC SHRINKFILE (temp5,TRUNCATEONLY);
DBCC SHRINKFILE (temp6,TRUNCATEONLY);
DBCC SHRINKFILE (temp7,TRUNCATEONLY);
DBCC SHRINKFILE (temp8,TRUNCATEONLY);
DBCC SHRINKFILE (templog,TRUNCATEONLY);
DBCC SHRINKFILE (tempdev,TRUNCATEONLY);

DBCC SHRINKFILE (temp2,10);
DBCC SHRINKFILE (temp3,10);
DBCC SHRINKFILE (temp4,10);
DBCC SHRINKFILE (temp5,10);
DBCC SHRINKFILE (temp6,10);
DBCC SHRINKFILE (temp7,10);
DBCC SHRINKFILE (temp8,10);
DBCC SHRINKFILE (templog,10);
DBCC SHRINKFILE (tempdev,10);
dbcc shrinkdatabase (tempdb, 10);

ALTER DATABASE tempdb MODIFY FILE (NAME = 'templog', SIZE = 10);
ALTER DATABASE tempdb MODIFY FILE (NAME = 'tempdev', SIZE = 10);
ALTER DATABASE tempdb MODIFY FILE (NAME = 'temp2', SIZE = 10);
ALTER DATABASE tempdb MODIFY FILE (NAME = 'temp3', SIZE = 10);
ALTER DATABASE tempdb MODIFY FILE (NAME = 'temp4', SIZE = 10);
ALTER DATABASE tempdb MODIFY FILE (NAME = 'temp5', SIZE = 10);
ALTER DATABASE tempdb MODIFY FILE (NAME = 'temp6', SIZE = 10);
ALTER DATABASE tempdb MODIFY FILE (NAME = 'temp7', SIZE = 10);
ALTER DATABASE tempdb MODIFY FILE (NAME = 'temp8', SIZE = 10);
</code>```

答: Verify that after executing the JOB, other transactions are not being executed. Apparently other transactions are being executed after you reduce the TEMPDB.</p>

Body:
So my question is that even after the job runs and I'm enforcing the mdf (main tempdb file) to be shrunk to about 10mb or so why is it NOT doing it?
I have tried to run this job after my most heavy lifting ETL jobs (that pulls from various sources and preps data for reporting needs). This specific server IS NOT used for reporting procs. I'm just curious as to why the shrink does not happen? Should I be taking a full backup of Temp db? and then delete the backup?
Sql job that I did my research here from previous threads and posts and built.
Sql server job

dbcc shrinkdatabase (tempdb, 97)

-- Clean all buffers and caches
DBCC DROPCLEANBUFFERS;
DBCC FREEPROCCACHE;
DBCC FREESYSTEMCACHE('ALL');
DBCC FREESESSIONCACHE;

DBCC SHRINKFILE (temp2,TRUNCATEONLY);
DBCC SHRINKFILE (temp3,TRUNCATEONLY);
DBCC SHRINKFILE (temp4,TRUNCATEONLY);
DBCC SHRINKFILE (temp5,TRUNCATEONLY);
DBCC SHRINKFILE (temp6,TRUNCATEONLY);
DBCC SHRINKFILE (temp7,TRUNCATEONLY);
DBCC SHRINKFILE (temp8,TRUNCATEONLY);
DBCC SHRINKFILE (templog,TRUNCATEONLY);
DBCC SHRINKFILE (tempdev,TRUNCATEONLY);

DBCC SHRINKFILE (temp2,10);
DBCC SHRINKFILE (temp3,10);
DBCC SHRINKFILE (temp4,10);
DBCC SHRINKFILE (temp5,10);
DBCC SHRINKFILE (temp6,10);
DBCC SHRINKFILE (temp7,10);
DBCC SHRINKFILE (temp8,10);
DBCC SHRINKFILE (templog,10);
DBCC SHRINKFILE (tempdev,10);
dbcc shrinkdatabase (tempdb, 10);

ALTER DATABASE tempdb MODIFY FILE (NAME = 'templog', SIZE = 10);
ALTER DATABASE tempdb MODIFY FILE (NAME = 'tempdev', SIZE = 10);
ALTER DATABASE tempdb MODIFY FILE (NAME = 'temp2', SIZE = 10);
ALTER DATABASE tempdb MODIFY FILE (NAME = 'temp3', SIZE = 10);
ALTER DATABASE tempdb MODIFY FILE (NAME = 'temp4', SIZE = 10);
ALTER DATABASE tempdb MODIFY FILE (NAME = 'temp5', SIZE = 10);
ALTER DATABASE tempdb MODIFY FILE (NAME = 'temp6', SIZE = 10);
ALTER DATABASE tempdb MODIFY FILE (NAME = 'temp7', SIZE = 10);
ALTER DATABASE tempdb MODIFY FILE (NAME = 'temp8', SIZE = 10);


问:
Returning Start and End Dates of Previous Quarter in MySQL
How would I go about writing a statement in MySQL to return the previous start and end date of the previous quarter? Say if I wanted the start and end date of the quarter before this one (i.e. beginning of last October and end of last December).</p>

答:
This will work such that if the date is in the first quarter, it'll roll back to the previous year in quarter 4.</p>

```<code>SELECT @dateLastQuarter := DATE_SUB('yourdate', INTERVAL 3 MONTH);
SELECT MAKEDATE(YEAR(@dateLastQuarter), 1) + INTERVAL QUARTER(@dateLastQuarter) QUARTER - INTERVAL 1 QUARTER,
MAKEDATE(YEAR(@dateLastQuarter), 1) + INTERVAL QUARTER(@dateLastQuarter) QUARTER - INTERVAL 1 DAY;
</code>```

Body:
This will work such that if the date is in the first quarter, it'll roll back to the previous year in quarter 4.

SELECT @dateLastQuarter := DATE_SUB('yourdate', INTERVAL 3 MONTH);
SELECT MAKEDATE(YEAR(@dateLastQuarter), 1) + INTERVAL QUARTER(@dateLastQuarter) QUARTER - INTERVAL 1 QUARTER,
MAKEDATE(YEAR(@dateLastQuarter), 1) + INTERVAL QUARTER(@dateLastQuarter) QUARTER - INTERVAL 1 DAY;


问:
How can I simulate a phone call from "Unavailable" in the android studio device emulator?
I'm making an app using Broadcast Receiver and I want my phone to be able to handle calls from "Unavailable". I don't want to wait until I get a call from "Unavailable" before being able to do a test. How can I simulate a call from "Unavailable" in an android studio emulator?</p>

答:
connect to your PC using telnet on the port of your emulator, e.g.

```<code>telnet localhost 5554
</code>```

and use the gsm call command with a number of # instead of digits

```<code>gsm call #
</code>```

and you'll receive your unknown call on the emulator's phone.

Body:
connect to your PC using telnet on the port of your emulator, e.g.

telnet localhost 5554

and use the gsm call command with a number of # instead of digits

gsm call #

and you'll receive your unknown call on the emulator's phone.


问:
pass PHP value back to AJAX function on success
I'm building an AJAX timeline of wall posts and I have the following function to check for new posts and then post the new ones to the wall, similar to how Twitter works:

wall_posts.php

```<code>$news = tz::shared()->news->getNew(25);

<div id="wall_posts">
    <?php foreach ($news as $news_post) { ?>
        <div class="wall_post"><?php echo $news_post['message']; ?></div>
    <?php } ?>
</div>
</code>```

jQuery:

```<code>function checkForNewPosts() {

    // This represents the last record in the table AKA the "most recent" news
    var lastCustomerNewsID = <?php echo $news[0]['id']; ?>;

    $.ajax({
        url: "example.com/ajax.php",
        method: "post",
        data:{
            lastCustomerNewsID: lastCustomerNewsID,
        },
        dataType:"text",
        success:function(data)
        {
            $('#wall_posts').prepend(data);
        }
    });

}

setInterval(checkForNewPosts, 10000);
</code>```

The news PHP array above with index 0 indicates it is the last/most recent ID in the array/table

PHP (ajax.php):

```<code>if ($_POST) {

    $lastCustomerNewsID = $_POST['lastCustomerNewsID'];

    $new_posts = tz::shared()->news->getNewForWall($lastCustomerNewsID);

    $output = '';

    if ($new_posts) {

        foreach ($new_posts as $new_post) {

            $output .= "<div class='wall_post'>";
                $output .= $new_post['message'];
            $output .= "</div>";

        }

    } else {

    }

    echo $output;

}
</code>```

Note - The function getNewForWall pulls records with an id greater than the argument passed in

This works fine when getting a new post, however the problem is that I need to update the "last id" to the "newest id" from the new records returned in ajax.php each time the function runs, because currently once its grabs the newest posts the first time, its keeps recognizing those as new on an ongoing basis.

How can I pass the newest "last id" from the array in ajax.php back to the AJAX function each time it runs? Can I pass a separate variable back to the AJAX function?

Thanks!

答:
First of all, I think PHP here should return JSON instead of HTML information
JQuery should process JSON to generate HTML information

The PHP code looks like this (this is an example)

```<code><?php
$page   = $_POST['page'];
$method = $_GET['method'];

if ($method == "list") {
    $limit  = 20;
    $offset = ($page - 1) * $limit;

    $post = new Post();

    // Calculate offsets according to page limits and page numbers and query articles
    //Let's assume that the field of content is "content"
    $offset    = ($page - 1) * $limit;
    $post_list = $post->offset($offset)->limit($limit)->select();
    $total = $post->offset($offset)->limit($limit)->count(); //Statistics of all entries

    //Get the largest ID by ID sort
    $last_id = $post->order('id desc')->find();
    $last_id = $last_id['id'];
    echo json_encode([
        'last_id'   => $last_id,
        'post_list' => $post_list,
        "maxpage"=>ceil($total / $limit), //Calculate the maximum number of pages
    ]);
} elseif ($method == 'last_check') {
    $post = new Post();
    //Get the largest ID by ID sort
    $last_id = $post->order('id desc')->find();
    $last_id = $last_id['id'];
    echo json_encode([
        'last_id' => $last_id,
    ]);
}
</code>```

Now we can check whether there are new articles through timers and page flips.
And you can use maxpage to determine if there is the next page.

```<code>function checkForNewPosts() {

    $.ajax({
        url: "example.com/ajax.php?method=last_check",
        method: "get",
        dataType:"json",
        success:function(data)
        {
            if(data.last_id>lastCustomerNewsID){
                //Write a new post operation here.

                lastCustomerNewsID = data.last_id;
            }
        }
    });

}

function getNextPage(){
    var html;
    page = page + 1;
    $.ajax({
        url: "example.com/ajax.php?method=list",
        method: "post",
        data:{
            "page": page
        },
        dataType:"json",
        success:function(data)
        {
            //Collate JSON into the required HTML format
            html = "";
            $.each(data.post_list, function(i, item){
                html = html + "<div class='wall_post'>" + item.contect + "</div>";
            });
            if(data.last_id>lastCustomerNewsID){
                //Write a new post operation here.
                lastCustomerNewsID = data.last_id;
            }
            if(data.maxpage<=page){
                //If there is no next page

            }

            $('#wall_posts').prepend(data);
        }
    });
}

setInterval(checkForNewPosts, 10000);
</code>```

Body:
I'm building an AJAX timeline of wall posts and I have the following function to check for new posts and then post the new ones to the wall, similar to how Twitter works:

wall_posts.php

$news = tz::shared()->news->getNew(25);

    <?php foreach ($news as $news_post) { ?>

<?php echo $news_post['message']; ?>

    <?php } ?>

jQuery:

function checkForNewPosts() {

    // This represents the last record in the table AKA the "most recent" news
    var lastCustomerNewsID = <?php echo $news[0]['id']; ?>;

    $.ajax({
        url: "example.com/ajax.php",
        method: "post",
        data:{
            lastCustomerNewsID: lastCustomerNewsID,
        },
        dataType:"text",
        success:function(data)
        {
            $('#wall_posts').prepend(data);
        }
    });

}

setInterval(checkForNewPosts, 10000);

The news PHP array above with index 0 indicates it is the last/most recent ID in the array/table

PHP (ajax.php):

if ($_POST) {

    $lastCustomerNewsID = $_POST['lastCustomerNewsID'];

    $new_posts = tz::shared()->news->getNewForWall($lastCustomerNewsID);

    $output = '';

    if ($new_posts) {

        foreach ($new_posts as $new_post) {

            $output .= "
";
                $output .= $new_post['message'];
            $output .= "
";

        }

    } else {

    }

    echo $output;

}

Note - The function getNewForWall pulls records with an id greater than the argument passed in

This works fine when getting a new post, however the problem is that I need to update the "last id" to the "newest id" from the new records returned in ajax.php each time the function runs, because currently once its grabs the newest posts the first time, its keeps recognizing those as new on an ongoing basis.

How can I pass the newest "last id" from the array in ajax.php back to the AJAX function each time it runs? Can I pass a separate variable back to the AJAX function?

Thanks!

Body:
First of all, I think PHP here should return JSON instead of HTML information
JQuery should process JSON to generate HTML information

The PHP code looks like this (this is an example)

<?php
$page   = $_POST['page'];
$method = $_GET['method'];

if ($method == "list") {
    $limit  = 20;
    $offset = ($page - 1) * $limit;

    $post = new Post();

    // Calculate offsets according to page limits and page numbers and query articles
    //Let's assume that the field of content is "content"
    $offset    = ($page - 1) * $limit;
    $post_list = $post->offset($offset)->limit($limit)->select();
    $total = $post->offset($offset)->limit($limit)->count(); //Statistics of all entries

    //Get the largest ID by ID sort
    $last_id = $post->order('id desc')->find();
    $last_id = $last_id['id'];
    echo json_encode([
        'last_id'   => $last_id,
        'post_list' => $post_list,
        "maxpage"=>ceil($total / $limit), //Calculate the maximum number of pages
    ]);
} elseif ($method == 'last_check') {
    $post = new Post();
    //Get the largest ID by ID sort
    $last_id = $post->order('id desc')->find();
    $last_id = $last_id['id'];
    echo json_encode([
        'last_id' => $last_id,
    ]);
}

Now we can check whether there are new articles through timers and page flips.
And you can use maxpage to determine if there is the next page.

function checkForNewPosts() {

    $.ajax({
        url: "example.com/ajax.php?method=last_check",
        method: "get",
        dataType:"json",
        success:function(data)
        {
            if(data.last_id>lastCustomerNewsID){
                //Write a new post operation here.

                lastCustomerNewsID = data.last_id;
            }
        }
    });

}

function getNextPage(){
    var html;
    page = page + 1;
    $.ajax({
        url: "example.com/ajax.php?method=list",
        method: "post",
        data:{
            "page": page
        },
        dataType:"json",
        success:function(data)
        {
            //Collate JSON into the required HTML format
            html = "";
            $.each(data.post_list, function(i, item){
                html = html + "<div class='wall_post'>" + item.contect + "</div>";
            });
            if(data.last_id>lastCustomerNewsID){
                //Write a new post operation here.
                lastCustomerNewsID = data.last_id;
            }
            if(data.maxpage<=page){
                //If there is no next page

            }

            $('#wall_posts').prepend(data);
        }
    });
}

setInterval(checkForNewPosts, 10000);


问:
How to sort a list of restaurant names by restaurant rating (possibly from Google Places or Yelp Fusion API)
I have a csv file with thousands of restaurant names and addresses that I need to sort by rating (data that is not in the csv). Is there a way to fill in the csv with this data? Possibly with Google Places API or Yelp Fusion API?</p>

答:
Both the Google Places API and Yelp Fusion API let you obtain a restaurant’s rating if you query with the business name and address. I’m going to explain how to do this but, first a caution about compliance. What you describe is clearly against the terms of service for both APIs. The only permitted use of their data is to display it on a publicly available website or app. Fetching and retaining it in a csv file is clearly improper. The APIs are intended for real-time query and immediate display of results for your users.

Google requires that the Places data be displayed in conjunction with a Google map or an approved "powered by Google" image. Additionally, no "pre-fetching, caching, or storage of content" is permitted. For details see https://developers.google.com/places/web-service/policies

Yelp requires attribution, basically requiring you to display the star rating and the Yelp logo with a link back to the business page on Yelp for the restaurant you have queried. See https://www.yelp.com/developers/display_requirements Furthermore, you can’t “cache, record, pre-fetch, or otherwise store any portion of the Yelp Content for a period longer than twenty-four (24) hours from receipt of the Yelp Content, or attempt or provide a means to execute any scraping or "bulk download" operations.” For full text and terms see https://www.yelp.com/developers/api_terms

With the legalese out of the way, here’s how to request a restaurant’s rating from Google Places:

```<code>https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=Applebees,234 W 42nd St,New York,NY&inputtype=textquery&fields=formatted_address,name,rating&key=YOUR_API_KEY
</code>```

And, the JSON response:

```<code>{
    "candidates": [
        {
            "formatted_address": "234 W 42nd St, New York, NY 10036, USA",
            "name": "Applebee's Grill + Bar",
            "rating": 3.6
        }
    ],
    "status": "OK"
}
</code>```

Here is the same request for Yelp Fusion. There is no way to request just the rating. Results always contain everything in their database for the restaurant:

```<code>https://api.yelp.com/v3/businesses/search?term=applebees&location=234 W 42nd St,New York,NY&limit=1
</code>```

JSON response:

```<code>{
    "businesses": [
        {
            "id": "gytFjzBw-z5LZD-6JSMChg",
            "alias": "applebees-grill-bar-new-york-3",
            "name": "Applebee's Grill + Bar",
            "image_url": "https://s3-media1.fl.yelpcdn.com/bphoto/CLizyj9S7pMvwGNm2dgdiQ/o.jpg",
            "is_closed": false,
            "url": "https://www.yelp.com/biz/applebees-grill-bar-new-york-3?adjust_creative=pnOv3Zj2REsNDMU4Z3-SLg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=pnOv3Zj2REsNDMU4Z3-SLg",
            "review_count": 444,
            "categories": [
                {
                    "alias": "tradamerican",
                    "title": "American (Traditional)"
                },
                {
                    "alias": "burgers",
                    "title": "Burgers"
                },
                {
                    "alias": "sportsbars",
                    "title": "Sports Bars"
                }
            ],
            "rating": 2,
            "coordinates": {
                "latitude": 40.756442,
                "longitude": -73.988838
            },
            "transactions": [
                "delivery",
                "pickup"
            ],
            "price": "$$",
            "location": {
                "address1": "234 W 42nd St",
                "address2": "",
                "address3": "",
                "city": "New York",
                "zip_code": "10036",
                "country": "US",
                "state": "NY",
                "display_address": [
                    "234 W 42nd St",
                    "New York, NY 10036"
                ]
            },
            "phone": "+12123917414",
            "display_phone": "(212) 391-7414",
            "distance": 5.938732504864397
        }
    ],
    "total": 2900,
    "region": {
        "center": {
            "longitude": -73.98880004882812,
            "latitude": 40.75648701137637
        }
    }
}
</code>```

Body:
Both the Google Places API and Yelp Fusion API let you obtain a restaurant’s rating if you query with the business name and address. I’m going to explain how to do this but, first a caution about compliance. What you describe is clearly against the terms of service for both APIs. The only permitted use of their data is to display it on a publicly available website or app. Fetching and retaining it in a csv file is clearly improper. The APIs are intended for real-time query and immediate display of results for your users.

Google requires that the Places data be displayed in conjunction with a Google map or an approved "powered by Google" image. Additionally, no "pre-fetching, caching, or storage of content" is permitted. For details see https://developers.google.com/places/web-service/policies

Yelp requires attribution, basically requiring you to display the star rating and the Yelp logo with a link back to the business page on Yelp for the restaurant you have queried. See https://www.yelp.com/developers/display_requirements Furthermore, you can’t “cache, record, pre-fetch, or otherwise store any portion of the Yelp Content for a period longer than twenty-four (24) hours from receipt of the Yelp Content, or attempt or provide a means to execute any scraping or "bulk download" operations.” For full text and terms see https://www.yelp.com/developers/api_terms

With the legalese out of the way, here’s how to request a restaurant’s rating from Google Places:

https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=Applebees,234 W 42nd St,New York,NY&inputtype=textquery&fields=formatted_address,name,rating&key=YOUR_API_KEY

And, the JSON response:

{
    "candidates": [
        {
            "formatted_address": "234 W 42nd St, New York, NY 10036, USA",
            "name": "Applebee's Grill + Bar",
            "rating": 3.6
        }
    ],
    "status": "OK"
}

Here is the same request for Yelp Fusion. There is no way to request just the rating. Results always contain everything in their database for the restaurant:

https://api.yelp.com/v3/businesses/search?term=applebees&location=234 W 42nd St,New York,NY&limit=1

JSON response:

{
    "businesses": [
        {
            "id": "gytFjzBw-z5LZD-6JSMChg",
            "alias": "applebees-grill-bar-new-york-3",
            "name": "Applebee's Grill + Bar",
            "image_url": "https://s3-media1.fl.yelpcdn.com/bphoto/CLizyj9S7pMvwGNm2dgdiQ/o.jpg",
            "is_closed": false,
            "url": "https://www.yelp.com/biz/applebees-grill-bar-new-york-3?adjust_creative=pnOv3Zj2REsNDMU4Z3-SLg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=pnOv3Zj2REsNDMU4Z3-SLg",
            "review_count": 444,
            "categories": [
                {
                    "alias": "tradamerican",
                    "title": "American (Traditional)"
                },
                {
                    "alias": "burgers",
                    "title": "Burgers"
                },
                {
                    "alias": "sportsbars",
                    "title": "Sports Bars"
                }
            ],
            "rating": 2,
            "coordinates": {
                "latitude": 40.756442,
                "longitude": -73.988838
            },
            "transactions": [
                "delivery",
                "pickup"
            ],
            "price": "$$",
            "location": {
                "address1": "234 W 42nd St",
                "address2": "",
                "address3": "",
                "city": "New York",
                "zip_code": "10036",
                "country": "US",
                "state": "NY",
                "display_address": [
                    "234 W 42nd St",
                    "New York, NY 10036"
                ]
            },
            "phone": "+12123917414",
            "display_phone": "(212) 391-7414",
            "distance": 5.938732504864397
        }
    ],
    "total": 2900,
    "region": {
        "center": {
            "longitude": -73.98880004882812,
            "latitude": 40.75648701137637
        }
    }
}


问:
Wrong 1st argument Type Uri/FileProvider Fragment
I'm trying to get cameraFragment.this to work in a Fragment but it keeps telling me "Wrong 1st argument type etc"

```<code>public void dispatchPicTaken(){
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if(intent.resolveActivity(getActivity().getPackageManager()) !=
null){
            File imgFile = null;
            imgFile = createPhotoFile();

            if(imgFile != null) {
                pathToFile = imgFile.getAbsolutePath();
                Uri photoURI =
FileProvider.getUriForFile(cameraFragment.this, "test", imgFile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(intent, 1);
            }
        }
    }
</code>```

答:
you should use getActivity() to get the context in a fragment instead of cameraFragment.this

```<code>FileProvider.getUriForFile(getActivity(), "test", imgFile);
</code>```

Body:
I'm trying to get cameraFragment.this to work in a Fragment but it keeps telling me "Wrong 1st argument type etc"

public void dispatchPicTaken(){
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if(intent.resolveActivity(getActivity().getPackageManager()) !=
null){
            File imgFile = null;
            imgFile = createPhotoFile();

            if(imgFile != null) {
                pathToFile = imgFile.getAbsolutePath();
                Uri photoURI =
FileProvider.getUriForFile(cameraFragment.this, "test", imgFile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(intent, 1);
            }
        }
    }

Body:
you should use getActivity() to get the context in a fragment instead of cameraFragment.this

FileProvider.getUriForFile(getActivity(), "test", imgFile);