text:
Q: Вычисление суммы ряда мне нужно сделать код так, чтобы получился пример под цифрой 2
но код я смог сделать только так, что у меня получается пример под цифрой 1
Как мне это переделать?
1. 1+1/2^2!+ 1/3^2!+ 1/4^2!+ 1/5^2!+... до Вводимого числа E
 2. 0,001^2+0,002^2/2!+ 0,003^2/3!+...до Вводимого числа E
#include <iostream>
#include <math.h>

int main()

{
   using namespace std;

   float e, s, i = 1, f = 1, prev;

   cout << "value for e =";
   cin >> e;

   s = 0;
   do
   {
       s = s + pow((1 / f), 2);
       i++;
       prev = 1 / f;
       f *= i;
       cout << "s="<< s<< endl;
   } while (1 / f >= e);
   return 0;
}

A: Вот как лучше сформулировать задание:
Нужно вычислить сумму ряда

для x=0.001, останавливая вычисления, когда очередной член становится меньше вводимого значения eps.
Тогда все просто - лучше только не "в лоб", а заметить, что отношение соседних членов равно

Тогда очень просто получается нужный код:
int main(int argc, const char * argv[])
{
    double x = 0.001;
    double eps;

    cin >> eps;

    double term = 1, sum = 1;
    for(int n = 2;term > eps; ++n)
        sum += (term *= double(n)/(n-1)/(n-1));
    sum *= x*x;

    cout << sum << endl;
}

Второй вариант - вычисление суммы для N членов - столь же простое:
int main(int argc, const char * argv[])
{
    double x = 0.001;
    int N;

    cin >> N;

    double term = 1, sum = 1;
    for(int n = 2; n <= N; ++n)
        sum += (term *= double(n)/(n-1)/(n-1));
    sum *= x*x;

    cout << sum << endl;
}

P.S. Правда, есть одна хитрость - чисто с точки зрения машинной точности такие суммы лучше считать от малых членов к большим, но для данного задания это уже перебор :)
А вообще, в пределе эта сумма равна

A: Можно здесь (?). Тут - же вы написали прогрессию гармонического ряда для степени 2, что разве неясно чему она равна. Ну или = Пи в квадрате / на 6. А в Результат также можно добавить будет 0. Всё. Компьютерных алгоритмов не знаю и не знаю: как писать шифры.


text:
Q: java.lang.UnsatisfiedLinkError: couldn't find DSO to load: libhermes-executor-release.so. in React-Native: 0.70.6 info Fetching system and libraries information...
System:
OS: macOS 12.2.1
CPU: (10) arm64 Apple M1 Max
Memory: 122.73 MB / 32.00 GB
Shell: 5.8 - /bin/zsh
Binaries:
Node: 18.11.0 - /opt/homebrew/bin/node
Yarn: 1.22.18 - /opt/homebrew/bin/yarn
npm: 8.19.2 - /opt/homebrew/bin/npm
Watchman: 2022.10.17.00 - /opt/homebrew/bin/watchman
Managers:
CocoaPods: 1.11.3 - /opt/homebrew/bin/pod
SDKs:
iOS SDK:
Platforms: DriverKit 21.4, iOS 15.4, macOS 12.3, tvOS 15.4, watchOS 8.5
Android SDK:
API Levels: 23, 29, 30, 31, 32, 33
Build Tools: 29.0.2, 29.0.3, 30.0.2, 30.0.3, 32.0.0, 32.1.0, 33.0.0, 33.0.1
System Images: android-24 | Google APIs ARM 64 v8a, android-25 | Google APIs ARM 64 v8a, android-28 | Google APIs ARM 64 v8a, android-28 | Google ARM64-V8a Play ARM 64 v8a, android-29 | ARM 64 v8a, android-29 | Google Play ARM 64 v8a, android-30 | ARM 64 v8a, android-30 | Intel x86 Atom_64, android-30 | Google APIs ARM 64 v8a, android-30 | Google APIs Intel x86 Atom, android-30 | Google APIs Intel x86 Atom_64, android-30 | Google Play ARM 64 v8a, android-30 | Google Play Intel x86 Atom, android-30 | Google Play Intel x86 Atom_64, android-31 | ARM 64 v8a, android-31 | Intel x86 Atom_64, android-31 | Google APIs ARM 64 v8a, android-31 | Google APIs Intel x86 Atom_64, android-31 | Google Play ARM 64 v8a, android-31 | Google Play Intel x86 Atom_64, android-32 | Google APIs ARM 64 v8a, android-32 | Google APIs Intel x86 Atom_64, android-32 | Google Play ARM 64 v8a, android-32 | Google Play Intel x86 Atom_64, android-33 | Google APIs ARM 64 v8a, android-Tiramisu | Google Play ARM 64 v8a
Android NDK: 22.1.7171670
IDEs:
Android Studio: 2021.3 AI-213.7172.25.2113.9123335
Xcode: 13.3/13E113 - /usr/bin/xcodebuild
Languages:
Java: 11.0.8 - /Library/Java/JavaVirtualMachines/openlogic-openjdk-11.jdk/Contents/Home/bin/javac
npmPackages:
@react-native-community/cli: Not Found
react: 18.2.0 => 18.2.0
react-native: 0.70.6 => 0.70.6
react-native-macos: Not Found
npmGlobalPackages:
react-native: Not Found
While opening an app itself I am getting below crash
java.lang.UnsatisfiedLinkError: couldn't find DSO to load: libhermes-executor-release.so
SoSource 0: com.facebook.soloader.DirectorySoSource[root = /data/app/~~Ugf7fQtxfAVyef-2afpx_A==/com.swellmoney.qa.android-bbsSDgEUlLKmTLucaSeD8g==/lib/arm64 flags = 0]
SoSource 1: com.facebook.soloader.DirectApkSoSource[root = (/data/app/~~Ugf7fQtxfAVyef-2afpx_A==/com.swellmoney.qa.android-bbsSDgEUlLKmTLucaSeD8g==/base.apk!/lib/arm64-v8a, )]
SoSource 2: com.facebook.soloader.DirectorySoSource[root = /system/lib64 flags = 2]
SoSource 3: com.facebook.soloader.DirectorySoSource[root = /vendor/lib64 flags = 2]
Native lib dir: /data/app/~~Ugf7fQtxfAVyef-2afpx_A==/com.swellmoney.qa.android-bbsSDgEUlLKmTLucaSeD8g==/lib/arm64
result: 0
at com.facebook.soloader.SoLoader.doLoadLibraryBySoName(SoLoader.java:1127)
at com.facebook.soloader.SoLoader.loadLibraryBySoNameImpl(SoLoader.java:943)
at com.facebook.soloader.SoLoader.loadLibraryBySoName(SoLoader.java:855)
at com.facebook.soloader.SoLoader.loadLibrary(SoLoader.java:802)
at com.facebook.soloader.SoLoader.loadLibrary(SoLoader.java:772)
at com.facebook.hermes.reactexecutor.HermesExecutor.loadLibrary(HermesExecutor.java:30)
at com.facebook.hermes.reactexecutor.HermesExecutor.(HermesExecutor.java:19)
at com.facebook.hermes.reactexecutor.HermesExecutor.loadLibrary(HermesExecutor.java:23)
at com.facebook.react.ReactInstanceManagerBuilder.getDefaultJSExecutorFactory(ReactInstanceManagerBuilder.java:393)
at com.facebook.react.ReactInstanceManagerBuilder.build(ReactInstanceManagerBuilder.java:343)
at com.facebook.react.ReactNativeHost.createReactInstanceManager(ReactNativeHost.java:96)
at com.facebook.react.ReactNativeHost.getReactInstanceManager(ReactNativeHost.java:42)
at com.swellmoney.android.MainApplication.onCreate(MainApplication.java:67)
at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1192)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6712)
at android.app.ActivityThread.access$1300(ActivityThread.java:237)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1913)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Laravel дополнительная обработка запроса Сделал php artisan create:request TableCreateRequest
Прописал правила:
    public function rules()
    {
        return [
            'login' => 'nullable',
            'pass' => 'nullable',
            'google_maps' => 'nullable',
             #https://www.google.com/maps?q=52.2484,21.0026
             #В google_cords должно передать 522484:210026
            'google_cords' => 'nullable',
        ];
    }

Делаю Table::create($request->validated()); в бд всё создаётся, всё хорошо. Мне теперь нужно в ходе запроса если есть request->google_maps, взять координаты и помести в google_cords. Можно ли это сделать как-то в модели или в TableCreateRequest?

A: В TableCreateRequest добавляем:
    private function getGoogleCords($google_maps)
    {
        $result = substr($google_maps , 30 );
        $result = explode(",", $result);
        $cord1 = str_replace('.', '', $result[0]);
        $cord2 = str_replace('.', '', $result[1]);
        return $cord1 . ':' . $cord2;
    }

    protected function prepareForValidation()
    {
        $google_maps = $this->request->get('google_maps');
        if ( $google_maps )
        {
        $this->request->set('google_cords', $this->getGoogleCords($google_maps));
        }
    }


text:
Q: Plots in Hammer projection I have a function $f[\theta,\phi]$ defined on the surface of a sphere that I would like to plot in an equal-area projection ellipse.  Surely there's a straightforward way to do this, but so far all I've able to produce are rectangular plots.

A: Here's a code snippet that I wrote a long time ago, specifically for the Hammer projection.
HammerPlot::usage=
  "HammerPlot[f] shows a Hammer projection (see http://en.wikipedia.org/wiki/Hammer_projection) of a function f[θ,φ].  "~~
  "The option ViewPoint->{Θ,Φ,χ} places the viewer over the point (Θ,Φ) and "~~
  "rotates the sphere by an angle χ around the line connecting the viewer and the center.  "~~
  "With ViewPoint->{0,0,0} the observer looks at the north pole, with the Gulf of Guinea to the right and the Bay of Bengal up.  "~~
  "With ViewPoint->{π/2,0,0} the observer looks at the Gulf of Guinea, with the Bay of Bengal up, the north pole left, and the south pole right.  "~~
  "With ViewPoint->{π/2,π/2,0} the observer looks at the Bay of Bengal, with the Gulf of Guinea down, the Pacific ocean up, the north pole left and the south pole right.  "~~
  "With the default setting ViewPoint->{π/2,0,-π/2} the observer looks at the Gulf of Guinea, with the equator going left-to-right, the north pole up, and the south pole down.";

Options[HammerPlot] = Join[Options[DensityPlot], {ViewPoint -> Automatic}];
SetOptions[HammerPlot, AspectRatio -> Automatic, PlotRange -> All,
                       Frame -> False, ColorFunction -> "SunsetColors"];
HammerPlot[f_, opts : OptionsPattern[]] := Module[{vp, θ, φ, χ},
  (* read view point *)
  vp = OptionValue[ViewPoint];
  {θ, φ, χ} = If[VectorQ[vp, NumericQ] && Length[vp] == 3,
                 vp,
                 {π/2, 0, -π/2}];
  DensityPlot[
    f[ArcCos[1/(4 Sqrt[4 + (-8 + x^2) y^2 + 4 y^4]) ((x^4 + 8 (-1 + y^2)^2 + x^2 (-8 + 6 y^2)) Cos[θ] + Sin[θ] (x Sqrt[8 - x^2 - 4 y^2] (-4 + x^2 + 4 y^2) Cos[χ] - 2 y Sqrt[-(-8 + x^2 + 4 y^2) (4 + (-8 + x^2) y^2 + 4 y^4)] Sin[χ]))],
      ArcTan[(x^4 + 8 (-1 + y^2)^2 + x^2 (-8 + 6 y^2)) Cos[φ] Sin[θ] - Sin[φ] (2 y Sqrt[(8 - x^2 - 4 y^2) (4 + (-8 + x^2) y^2 + 4 y^4)] Cos[χ] + x Sqrt[8 - x^2 - 4 y^2] (-4 + x^2 + 4 y^2) Sin[χ]) + Cos[θ] Cos[φ] (-x Sqrt[8 - x^2 - 4 y^2] (-4 + x^2 + 4 y^2) Cos[χ] + 2 y Sqrt[(8 - x^2 - 4 y^2) (4 + (-8 + x^2) y^2 + 4 y^4)] Sin[χ]), Cos[φ] (2 y Sqrt[(8 - x^2 - 4 y^2) (4 + (-8 + x^2) y^2 + 4 y^4)] Cos[χ] + x Sqrt[8 - x^2 - 4 y^2] (-4 + x^2 + 4 y^2) Sin[χ]) + Sin[φ] (8 Sin[θ] + (x^2 + 2 y^2) (-8 + x^2 + 4 y^2) Sin[θ] + Cos[θ] (-x Sqrt[8 - x^2 - 4 y^2] (-4 + x^2 + 4 y^2) Cos[χ] + 2 y Sqrt[(8 - x^2 - 4 y^2) (4 + (-8 + x^2) y^2 + 4 y^4)] Sin[χ]))]],
     {x, -2, 2}, {y, -1, 1},
     RegionFunction -> ((#1/2)^2 + #2^2 < 1 &),
     Evaluate[FilterRules[{opts, Options[HammerPlot]}, Options[DensityPlot]]]]]

Try it out: Plot the $x=\sin(\theta)\cos(\phi)$ coordinate with
HammerPlot[Sin[#1] Cos[#2] &]

Plot the $y=\sin(\theta)\sin(\phi)$ coordinate with
HammerPlot[Sin[#1] Sin[#2] &]

Plot the $z=\cos(\theta)$ coordinate with
HammerPlot[Cos[#1] &]

These plots can be modified with all the options available for DensityPlot, for example HammerPlot[Cos[#1] &, ColorFunction -> Hue, PlotLegends -> Automatic]. Particularly the ViewPoint option is useful to center the viewer at arbitrary points over the sphere.

A: How about the following?
Plot3D[Re[SphericalHarmonicY[3, 1,\[Theta],\[Phi]]] /.
 {\[Phi] -> ArcSin[x*y], \[Theta]->2*ArcTan[x*Sqrt[1 - (x/4)^2-(y/2)^2]/
2/(2*(1 - (x/4)^2 - (y/2)^2) - 1)]}, {x, -4, 4}, {y, -Sqrt[1 - (x/4)^2], Sqrt[1 - (x/4)^2]},
BoxRatios -> Automatic]

The formulas from Wiki are used. Compare with
Plot3D[Re[SphericalHarmonicY[3, 1, \[Theta], \[Phi]]], {\[Theta], 0,  Pi}, {\[Phi], 0, 2*Pi}]


text:
Q: Continuing a Loop and Moving On (Python) I have a 'while' loop in my Python app (v2.7) which basically communicates with a Bluetooth GPS device and the loop continues for as long as there is data being received. In essence, the while loop looks like this:-
> data = ""
>
> if data == None:
>     print "Connection Failed" else:
>     print "Connection Established"
>
> while True:
>     data = socket.recv(1024)

Now what I want to do is leave this while loop running continually throughout the life of the program until the bluetooth device is switched off which in turn will end the loop as no data will be being received. Nonetheless, as this while loop continues, I then want to move onto another method which will parse the data.
How can I leave the loop running and move on to the next command? Is threading required? I'm new to the concept of threading and so please be patient with me :)
Thanks

A: Yeah, because you're essentially going to be doing two things at the same time, you'll have to create a new thread (using threading) or perhaps more simply a new process (using multiprocessing or just os.fork)
The easiest thing to do is to put this part in a function, and use multiprocessing or threading to start the function in a different process.  Typically you'll have less weirdness with multiple processes than multiple threads, just FYI.

A: received = ""
while True:
     data = socket.recv(1024)
     if not data:
         break # ends the while loop
     received+=data

do_stuff(received)


text:
Q: Data(longitude&latitude) extracted from .csv file and making a visual map with the coordinates I have a .csv file where it has all the airports and other info
import csv
from collections import defaultdict

columns = defaultdict(list)

with open('airports.csv', newline='', encoding='utf-8') as f:
    reader = csv.DictReader(f)
    for row in reader:
        for (k,v) in row.items():
            columns[k].append(v)

print(columns['longitude_deg'])

print(columns['latitude_deg'])

this outputs something like
['-74.9336013793945', '-151.695999146', '-86.7703018188477', '-91.2548980712891', '-112.165000915527', '-116.888000488', '-104.34400177002', '-82.2190017700195', ......]
['-74.9336013793945', '-151.695999146', '-86.7703018188477', '-91.2548980712891', '-112.165000915527', '-116.888000488', '-104.34400177002', '-82.2190017700195', ......]

for both longitude and latitude.
how can i use these to pinpoint the locations on a map?(with python)

A: If you want to do it on google-maps (as your tag indicates) you will need to use a Python wrapper for the Google Maps javascript API. You will need to use something like http://code.google.com/p/pygmaps/.
Install it with:
pip install pygmaps

Then for example:
import pygmaps

mymap = pygmaps.maps(39.0194, 125.7381,8)
mymap.addpoint(39.0194, 125.7381)
mymap.addpoint(37.5665, 126.978)
mymap.draw('./mymap.html')

Will produce:


text: Q: Couchbase store only one revision Is it possible to store only one revision of each document in Couchbase so that it doesn't inflate  after each update using set? This question is interesting in context of Couchbase Lite too.


text:
Q: org.apache.jasper.JasperException When i open first time my application its show error like
org.apache.jasper.JasperException
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:460)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:373)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:329)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.tuckey.web.filters.urlrewrite.NormalRewrittenUrl.doRewrite(NormalRewrittenUrl.java:183)
    org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:125)
    org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:107)
    org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:78)
    org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:383)

But i refreshed again then it will open fine without error.
What is the problem and how to fix this?
Please can any one help me...

A: it looks like your application requires some initialization of code which takes time. now while you open the page it is initializing things in background and you see error due to uninitialized or partial initialized values.
you can add some auto initializers or wait for some time to get it loaded completely.

A: Here's an extract of relevance of the JspServletWrapper#handleJspException() source.
456         // If the line number is less than one we couldn't find out
457         // where in the JSP things went wrong
458         int jspLineNumber = detail.getJspBeginLineNumber();
459         if (jspLineNumber < 1) {
460             throw new JasperException(ex);
461         }

Apparently the JSP was empty on first access. What frameworks are you using? I haven't seen a framework before which autogenerates JSP files on startup or something like that. It might need some configuration finetuning.

A: I met this problem because of web.xml misconfiguration.
I tried to add *.jar to be served by JspServlet.
You certainly did an error in Servlet mapping in your web.xml.


text:
Q: How to pass a variable between web pages when using Reactjs Router Switch to navigate I am working on a web application that can load one of several scenarios based on a selection that a user makes.
A webpage has already been implemented to load a scenario, which is initiated by making an API call to the back end (python via flask).
The web-based UI is in javascript making use of react js.
At the moment I use the Router Switch method to allow navigation between a few web pages.
What I would like to achieve is:

*

*On Home page, user selects scenario and presses Load

*Load in fact calls a renderRedirect() function, and triggers navigation to the Scenario page.

*Upon arrival on the Scenario page, the API call to the back-end is made  requesting the creation of the specific scenario that the user had selected in step 1.

What I don't know is how to get the information (just a string scenario_id) from the Home page to the Scenario page.
I found this question/answer, but to implement it I would have to rework my current Switch setup to instead make use of router.push, unless I am mistaken?
Here is my current Routing code:
render((
    <BrowserRouter>
        <Switch>
            <Route exact path='/new-scenario' component={NewScenario}/>
            <Route exact path='/about' component={About}/>
            <Route exact path='/' component={Home}/>
        </Switch>
    </BrowserRouter>
), document.getElementById('root'));

A: If I understood you only want the scenario_id, I think you can do it via url params
if you select scenario_id 1 on home page your url can be something like
/scenario/1
so you could define your route like this
       <Route exact path="/scenario/:id" render={props => <ScenarioComponent {...props} /> } />

with this code you're sending the :id part of the url to your component via props
you can get the value on Scenario with
this.props.match.params.id


text:
Q: Home Name Server I would like to set up a name server for my home network so that I can use my easily remembered names to point at my devices. I haven't played with DNS in over 7 years and honestly don't remember how to do this. Can anyone point me to a good "how to" or something of the like to get me started?

A: I would suggest using dnsmasq, as it will give you a two fold solution: dhcp server and dns proxy for your local network.
You might want to look at https://help.ubuntu.com/community/Dnsmasq
Advantages of dnsmasq is that it will resolve dhcp names in its dns proxy, and simply use /etc/hosts for static ip you might have. It is much simpler than using a full bind9 server.

A: Well, if the network is really simple and static, you could just modify /etc/hosts on all devices to have lines like:
192.168.1.42  universe
172.17.18.19  foobar

If you have too many devices or they change too often, dnsmasq (available in the repository) provides you with either a DNS server or a DHCP server, or both. There is a rudimentary setup guide on community help wiki, and documentation on dnsmasq homepage.


text:
Q: GCC not using proper version of std::string Why is GCC using std::string instead of  std::__cxx11::basic_string
this is not a duplicate of this because i am already using different versions. Please read the question and explanation before marking as a duplicate in 2 seconds. thank you for your patience and understanding
I also do not think that this question is a duplicate as it still does not explain why is GCC's behaviour is like this, but more addresses the differences between gcc and g++.
I have manually installed GCC8.2.0 and compiled it from source and everything seemed to have worked out fine. Added the directory to /etc/ld.so.conf and ran again ldconfig. However when i test it, it is still using the old libstdc++ library.
What am i missing?
#include <iostream>
#include <string>
int main()
{
  std::string hey = "hello";
  std::cout<<hey<<" world"<<std::endl;
  return 0;
}
gcc -D_GLIBCXX_USE_CXX11_ABI=1 test.cpp -std=c++17 -lstdc++ --verbose -o  test -Wl,--verbose >link.txt

Compilation output:
Using built-in specs.
COLLECT_GCC=/usr/local/gcc8.2/bin/gcc
COLLECT_LTO_WRAPPER=/usr/local/gcc8.2/libexec/gcc/x86_64-pc-linux-gnu/8.2.0/lto-wrapper
Target: x86_64-pc-linux-gnu
Configured with: /root/gcc-8.2.0/configure --prefix=/usr/local/gcc8.2 --disable-multilib --enable-languages=c,c++ --enable-threads
Thread model: posix
gcc version 8.2.0 (GCC)
COLLECT_GCC_OPTIONS='-D' '_GLIBCXX_USE_CXX11_ABI=1' '-std=c++17' '-v' '-o' 'test' '-mtune=generic' '-march=x86-64'
 /usr/local/gcc8.2/libexec/gcc/x86_64-pc-linux-gnu/8.2.0/cc1plus -quiet -v -D_GNU_SOURCE -D _GLIBCXX_USE_CXX11_ABI=1 test.cpp -quiet -dumpbase test.cpp -mtune=generic -march=x86-64 -auxbase test -std=c++17 -version -o /tmp/cctBaif9.s
GNU C++17 (GCC) version 8.2.0 (x86_64-pc-linux-gnu)
        compiled by GNU C version 8.2.0, GMP version 6.0.0, MPFR version 3.1.1, MPC version 1.0.1, isl version none
GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
ignoring nonexistent directory "/usr/local/gcc8.2/lib/gcc/x86_64-pc-linux-gnu/8.2.0/../../../../x86_64-pc-linux-gnu/include"
#include "..." search starts here:
#include <...> search starts here:
 /usr/local/gcc8.2/lib/gcc/x86_64-pc-linux-gnu/8.2.0/../../../../include/c++/8.2.0
 /usr/local/gcc8.2/lib/gcc/x86_64-pc-linux-gnu/8.2.0/../../../../include/c++/8.2.0/x86_64-pc-linux-gnu
 /usr/local/gcc8.2/lib/gcc/x86_64-pc-linux-gnu/8.2.0/../../../../include/c++/8.2.0/backward
 /usr/local/gcc8.2/lib/gcc/x86_64-pc-linux-gnu/8.2.0/include
 /usr/local/include
 /usr/local/gcc8.2/include
 /usr/local/gcc8.2/lib/gcc/x86_64-pc-linux-gnu/8.2.0/include-fixed
 /usr/include
End of search list.
GNU C++17 (GCC) version 8.2.0 (x86_64-pc-linux-gnu)
        compiled by GNU C version 8.2.0, GMP version 6.0.0, MPFR version 3.1.1, MPC version 1.0.1, isl version none
GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
Compiler executable checksum: ffbbe768b373e36d4dbebee8b6dad361
COLLECT_GCC_OPTIONS='-D' '_GLIBCXX_USE_CXX11_ABI=1' '-std=c++17' '-v' '-o' 'test' '-mtune=generic' '-march=x86-64'
 as -v --64 -o /tmp/ccY7GV78.o /tmp/cctBaif9.s
GNU assembler version 2.30 (x86_64-redhat-linux) using BFD version version 2.30-47.el7
COMPILER_PATH=/usr/local/gcc8.2/libexec/gcc/x86_64-pc-linux-gnu/8.2.0/:/usr/local/gcc8.2/libexec/gcc/x86_64-pc-linux-gnu/8.2.0/:/usr/local/gcc8.2/libexec/gcc/x86_64-pc-linux-gnu/:/usr/local/gcc8.2/lib/gcc/x86_64-pc-linux-gnu/8.2.0/:/usr/local/gcc8.2/lib/gcc/x86_64-pc-linux-gnu/
LIBRARY_PATH=/usr/local/gcc8.2/lib/gcc/x86_64-pc-linux-gnu/8.2.0/:/usr/local/gcc8.2/lib/gcc/x86_64-pc-linux-gnu/8.2.0/../../../../lib64/:/lib/../lib64/:/usr/lib/../lib64/:/usr/local/gcc8.2/lib/gcc/x86_64-pc-linux-gnu/8.2.0/../../../:/lib/:/usr/lib/
COLLECT_GCC_OPTIONS='-D' '_GLIBCXX_USE_CXX11_ABI=1' '-std=c++17' '-v' '-o' 'test' '-mtune=generic' '-march=x86-64'
 /usr/local/gcc8.2/libexec/gcc/x86_64-pc-linux-gnu/8.2.0/collect2 -plugin /usr/local/gcc8.2/libexec/gcc/x86_64-pc-linux-gnu/8.2.0/liblto_plugin.so -plugin-opt=/usr/local/gcc8.2/libexec/gcc/x86_64-pc-linux-gnu/8.2.0/lto-wrapper -plugin-opt=-fresolution=/tmp/ccuLLh38.res -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lc -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lgcc_s --eh-frame-hdr -m elf_x86_64 -dynamic-linker /lib64/ld-linux-x86-64.so.2 -o test /lib/../lib64/crt1.o /lib/../lib64/crti.o /usr/local/gcc8.2/lib/gcc/x86_64-pc-linux-gnu/8.2.0/crtbegin.o -L/usr/local/gcc8.2/lib/gcc/x86_64-pc-linux-gnu/8.2.0 -L/usr/local/gcc8.2/lib/gcc/x86_64-pc-linux-gnu/8.2.0/../../../../lib64 -L/lib/../lib64 -L/usr/lib/../lib64 -L/usr/local/gcc8.2/lib/gcc/x86_64-pc-linux-gnu/8.2.0/../../.. /tmp/ccY7GV78.o -lstdc++ --verbose -lgcc --as-needed -lgcc_s --no-as-needed -lc -lgcc --as-needed -lgcc_s --no-as-needed /usr/local/gcc8.2/lib/gcc/x86_64-pc-linux-gnu/8.2.0/crtend.o /lib/../lib64/crtn.o
COLLECT_GCC_OPTIONS='-D' '_GLIBCXX_USE_CXX11_ABI=1' '-std=c++17' '-v' '-o' 'test' '-mtune=generic' '-march=x86-64'

Relevant part of the linking process:
attempt to open /usr/local/gcc8.2/lib/gcc/x86_64-pc-linux-gnu/8.2.0/libstdc++.so failed
attempt to open /usr/local/gcc8.2/lib/gcc/x86_64-pc-linux-gnu/8.2.0/libstdc++.a failed
attempt to open /usr/local/gcc8.2/lib/gcc/x86_64-pc-linux-gnu/8.2.0/../../../../lib64/libstdc++.so succeeded
-lstdc++ (/usr/local/gcc8.2/lib/gcc/x86_64-pc-linux-gnu/8.2.0/../../../../lib64/libstdc++.so)

ls -lah /usr/local/gcc8.2/lib/gcc/x86_64-pc-linux-gnu/8.2.0/../../../../lib64/libstdc++.so

lrwxrwxrwx 1 root root 19 Jan 25 14:07 /usr/local/gcc8.2/lib/gcc/x86_64-pc-linux-gnu/8.2.0/../../../../lib64/libstdc++.so -> libstdc++.so.6.0.25

Problem:
nm -C a.out |grep string
                 U std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&)@@GLIBCXX_3.4
                 U std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()@@GLIBCXX_3.4
                 U std::basic_ostream<char, std::char_traits<char> >& std::operator<< <char, std::char_traits<char>, std::allocator<char> >(std::basic_ostream<char, std::char_traits<char> >&, std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)@@GLIBCXX_3.4

Why is this linking with such an old GLIBCXX_3.4, and how do I convince gcc (when called as gcc) to use the std::string I want it to?


text:
Q: How could I solve Invalid driver requested Session_session_id Error? Using Community Auth Codeigniter authentication package.
After login, I'm getting the following view error:

Invalid driver requested: Session_session_id

I've looked at documentation and searched for a solution with no luck.
Config file: http://pastebin.com/Nn7JeUDB
Debug is set to 2. The output is:
DEBUG - 2016-01-17 06:15:32 --> CI_Session routines successfully run
DEBUG - 2016-01-17 06:15:32 --> Database Driver Class Initialized
DEBUG - 2016-01-17 06:15:32 --> Session class already loaded. Second attempt ignored.
DEBUG - 2016-01-17 06:15:32 --> Encryption: Auto-configured driver 'openssl'.
DEBUG - 2016-01-17 06:15:32 --> Encryption: OpenSSL initialized with method AES-128-CBC.
DEBUG - 2016-01-17 06:15:32 --> Encryption Class Initialized
DEBUG - 2016-01-17 06:15:32 --> Model Class Initialized
DEBUG - 2016-01-17 06:15:32 --> Model Class Initialized
DEBUG - 2016-01-17 06:15:32 --> Controller Class Initialized
DEBUG - 2016-01-17 06:15:32 --> XSS Filtering completed
DEBUG - 2016-01-17 06:15:32 --> XSS Filtering completed
ERROR - 2016-01-17 06:15:32 --> Invalid driver requested: Session_session_id

Session Config.php
$config['sess_driver']          = 'cookie';
$config['sess_valid_drivers']   = array();
$config['sess_cookie_name']     = 'ci_session';
$config['sess_expiration']      = 7200;
$config['sess_expire_on_close'] = FALSE;
$config['sess_encrypt_cookie']  = FALSE;
$config['sess_use_database']    = FALSE;
$config['sess_table_name']      = 'ci_sessions';
$config['sess_match_ip']        = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update']  = 300;


text:
Q: Generate correct data in select tag Structure of the table category:
id | parent_id | name
----------------------
1  | NULL      | test1
2  | NULL      | test2
3  | 1         | test3
4  | 1         | test4
5  | 3         | test5
6  | 2         | test6
7  | 6         | test7
8  | 3         | test8

It is tree.
So, this is what I want in PHP:
I have id (it can be function argument), for example 5 and I want generate select tags, (in this example 3 level) so I want generate something like this:
https://jsfiddle.net/Lh8y2mzh/
test6 and test7 are not in select and this is what I want. It should work recursively I think. Any help? How to make the function?


text:
Q: Getting output as:- number:57929.0, number:59214.0, number:57931.0 instead of 57929, 59214,57931 The following is the code I am trying to execute. But when I execute it, I am not getting the output the way I want.
The output cell has the value number:57929.0 instead of 57929.
I know that by using, a = int(values[i].value) I am getting proper "57929" as the output.
But I want to do the set operations on it, so when I am converting the values[] to the set(), the number:57929.0 values gets into the set variable.
The list "values" contains the value in this "number:57929.0" format, so how do I remove this to get a desired output.
import xlrd
import xlwt

data = xlrd.open_workbook('TAX TCC.xlsx')
table = data.sheet_by_name(u 'WARD 1')

nrows = table.nrows
ncols = table.ncols

data1 = xlrd.open_workbook('WardWiseProperty.xlsx')
table1 = data1.sheet_by_name(u 'Sheet1')
nrows1 = table1.nrows
ncols1 = table1.ncols

values = []
for i in range(nrows - 3):
  values.append(table.cell(i + 3, 0))

values1 = []
for i in range(5902):
  values1.append(table1.cell(i + 10, 5))

sett = set(values)
sett1 = set(values1)

print(sett - sett1)


text:
Q: Retrieving intermediate values for raw_input If I have a thread running in the background, is there any way it can retrieve from Python's raw_input what has been typed so far? Example: User is sitting at prompt and typing away. I would like to receive what has been typed so far at the 5 second mark, 10 second mark, etc.
Relatedly, is there any type of KeyboardEvent indicating that typing is going on?
Additionally, is there any way to modify raw_input's buffer? Clear the buffer from a different thread?
For threading I'm using the 'signal' module.


text:
Q: Execute Code On Standard Page Layout My goal is that whenever the Account page layout loads, custom code is executed. And, in order to execute the code properly I need to access the account object that is displayed on the Account page layout.
The functionality i am trying to add is that the Account object gets updated from a external source when the Account page layout loads.
I know I can add a custom lightning component and execute code on load, but is it possible to access the object loaded in the layout from the lightning component?
Currently I see any obvious functionality in the "Customize Page Layouts" section.
So I am expecting to be able to do something like
layout.load => {
Scope.object.field = 'new value'
}


text:
Q: How to implement roles in web application I was create a website it runs perfectly. But I have one problem am having two folders, called  user and admin. Both folders contain a home.aspx file. Suppose you are a user, not an admin, and you have logged in using a username and password.
Given an URL like this: http:localhost:8080/user/home.aspx, suppose you go to addressbar and type admin instead of user means you can access the admin page with your session.
How can I block the access to the admin page for regular users?

A: When logging in, you should set a flag identifying the type of user. The on each page where login is required, you check whether the currently logged in user is a type of user you want to allow access to the page.
So on admin/home.aspx, psuedo-code:
if (!LoggedInUser.IsAdmin)
    Redirect("Not Allowed");

And on user/home.aspx:
if (LoggedInUser == null)
    Redirect("Not Allowed");

There are many ways to do this, depending on the way you handle your users. An example can be found here.

A: The easiest prescribed way to get started is using the ASP.net membership and roles system which allows you to define folder level permissions based upon the logged in user - and many more features.
These videos will get you started: http://www.asp.net/web-forms/videos/authentication

A: When user(not admin) logs in, set a user role in session:
For Example:
set isAdmin=false in session
Now at beginning of admin page:
if( isAdmin is false ) {
   // Redirect to any other page or error page
}

// Other admin content


text:
Q: Database Design - foreign key same as primary key? I would like if this simple database modeling is fine. Specially the Billing table.
Can you guys give your opinions?

A: It is perfectly acceptable to have a foreign key column be part of the primary key of a table.  This happens frequently in intersection tables which implement many-to-many relationships, for example.
Some people find that is it preferable to use surrogate keys instead of compound keys.  When you use a foreign key column as a primary key you will almost always be using compound keys and these could potentially get large and complex.
If you search around here on StackOverflow and elsewhere you can find extensive and passionate discussions of the relative merits of natural vs. compound vs. surrogate keys.  If you read these you'll find that there are lots of people who would support the way you defined the primary keys in your model.

A: I think you're asking if it's ok for the primary key in EmployeeProject to consist of two foreign keys. If I've understood your question correctly, that's fine.
In Billing, there's nothing wrong with having a foreign key consisting of two columns that refer to EmployeeProject. (In SQL, foreign key (empNo, projectNo) references EmployeeProject (empNo, projectNo).) You almost certainly don't want two separate foreign keys referencing Employee and Project here.
The three-column primary key in Billing (SQL, primary key (billingNo, empNo, projectNo)) allows data like this.
billingNo  empNo  projectNo  hoursBilled
--
1003       13     7          3
1003       13     6          2
1003       17     7          8
1004       13     7          3
1004       13     6          2

If that's your intent, you going in the right direction.


text:
Q: Deploying as ASP.NET website DLL a year ago I created and deployed a simple web app from visual studio 2012. This included a dll in the bin folder containing the code behind.
Fast forward one year and I need to make a small change to the .cs file.
I open the solution in VS2012, make my change and select build project. No bin folder and no dll are created. I try build website, rebuild website and anything obvious I can see but even though the build process works fine I do not end up with the bin folder or the dll. I have double checked the live site and the web site contains a bin folder and a dll rather than individual code-behind files.
Have I missed something obvious or fundamental here?

A: Have solved this now. The compilation of the dll happens at the publish web site stage and not the build web site stage. Once I sorted out an issue with FTP I was able to publish to the live site and the dll was overwritten with my new one


text:
Q: How to open an attachment using a link in an xpage? How to open an attachment in an xpage using a link url? What are all the fields iln the url? Pls explain. Also about the document folder created in the 'xsppers' folder.

A: The short answer how to open a attached Image is:
http://pathToyourDatabase/DatabaseName.nsf/0/DocumentUniversalID/$File/MyImage.jpg

you can create this link with:
var imageurl = facesContext.getExternalContext().getRequest().getContextPath() + "/0/" +
                /*in my case: viewEntry.getDocument().getUniversalID()*/
                + "/$File/"+ AttachmentName;

placing this link in the src attribute of an <img> or in the url attribute of the <xp:image> tag will dislay this image on your xPage. This example works fine for me but for other Attachments you maby have to add ?OpenElement after the AttachmentName.
Update:
I did a short experiment on this with a pdf file and it worked without the ?OpenElement just use the code to generate the url it should work. Additional you can look @ Link.


text:
Q: HTML Bootstrap Carousel Responsive Picture When using the carousel from Bootstrap shown below: The image will resize until it reaches the size of the natural picture size of the picture.

      Previous

      Next

To make this more responsive, I've tried making all img's as class .image-item and setting width: 100%. The pictures still only resizes as long as it has not met it's natural size. Additionally, I've tried using  instead of just a  tag to see if I can replace the image file with a more appropriate file when screen grows. However, that didn't work either:
...

        <picture>
            <Sources media="(min-width: 400px)" srcset="A-Large_1x.jpg 1x, A-Large_2x.jpg 2x">

        </picture>
    ...

In short summary, I'm trying to make this carousel responsive such that
1) Images will scale to be bigger than natural size if necessarily (screen enlarged considerably)
2) Images will be replaced with higher resolution picture (1x or 2x) if necessary
3) Different sizes of the same images will be shown depending on screen width of device (A-Small.jps, A-Medium.jpg, A-Large.jpg)
The carousel works but the images do not resize nor will they show the appropriate version of a image based on device screen width. Do you guys have any ideas how I might about resolving this?

A: Bootstrap provides you with a great class called img-responsive. It will make any picture responsive. Just include the class to every  element. If you want to know more about this, make sure to check the documentation: http://getbootstrap.com/css/#images
   ....

   ....

Hope that helps!

A: For anyone else who stumbles across this, the correct answer for getting the  element to work within the bootstrap carousel is the correct source below.
tldr; the <Sources> tag was being used incorrectly, it should be <source>
The first answer was correct for making an image responsive.
But, if you're like me and want to serve an optimized image in the bootstrap carousel supported by the visitors browser and browser size (ie. mobile vs desktop) then you'll need the following:
<picture>
    <source class="d-block w-100" media="(min-width: 768px;)" srcset="not-real.webp" type="image/webp">
    <source class="d-block w-100" srcset="not-real-2.webp" type="image/webp">
    <source class="d-block w-100" media="(min-width: 768px;)" srcset="not-real.jp2" type="image/jp2">
    <source class="d-block w-100" srcset="not-real-2.jp2" type="image/jp2">

</picture>

This will let the browser serve the optimized image based on the file type supported (webp for most, jp2000 for Safari, and the jpeg for IE8+ as the fail-safe in the img tag), and based on the screen size.


text:
Q: Memory usage on MQTT subscription How much of memory used whenever we use from # (wildcard) to subscription into many topics? for example if we have over 10M topics, it's possible to use # to subscribe into all of them, or it caused to memory leaks?

A: This problem is strictly related to the MQTT broker and client implementation.
Of course, the MQTT standard specification doesn't provide any information on the features related to such implementation.
Paolo.

A: Extending on ppatierno's answer.
For most well designed brokers the number or scope (for wild card) subscriptions shouldn't really change the amount of memory used under normal circumstances . At most the storage should equate to the topic string that the client subscribes to, this will be matched against a incoming message to see if it should be delivered.
Where this may not hold true is with persistent subscriptions (where the clean session value is not set to true). In this case if a client disconnects then messages may be queued until it reconnects. The amount of memory consumed here will be a function of the number of messages and their size (plus what discard policy the broker may have) and not directly a function of the number of subscribed topics.
To answer the second part of your question, subscribing to 10,000,000 topics using the wildcard is not likely to cause a memory leak, but it may very well flood the client depending on how often messages are published on those topics.


text:
Q: Lua AST within C# What is the easiest way to get an abstract-syntax-tree within C# from a Lua script? I'm trying to do a simple static code analysis within C# for a Lua script.
Many existing code analysis tools like LuaInspect are based on MetaLua, but I don't see an easy way to integrate MetaLua within C#. And projects like Lua for Irony seem to be in an alpha stage or the development has stopped years ago.
What would be your suggestion to get an AST for LUA within C# for static code analysis?

A: You might want to try monosharp: http://www.moonsharp.org/
It uses ANTLR to build a C# AST. You will probably have to do some code spelunking though, since its main objective isn't "creating an AST" but actually "interpreting Lua directly in C#".

A: If you can run Lua code, nothing should stop you from integrating LuaInspect and MetaLua. The earlier versions of MetaLua required some manual work to avoid compilation steps, but the recent versions (0.7+) don't require much work. The generation of AST is as simple as:
require('metalua.compiler').new():src_to_ast(src, filename)

Note that LuaInspect hasn't been updated to support lineinfo format changes in the recent metalua versions, so if you plan on using it with ML 0.7+, you may review these changes I made to make it work in the Lua IDE I'm working on.


text:
Q: Stop browser requests Is it possible to stop all the requests/scripts that are happening on a page, when the refresh button is hit?

I have a $.ajax request that takes a few minutes. I have tried to do window.stop() in the unload event; I have tried xhr = $.ajax(...); and xhr.abort(); and any other methods found over the internet and nothing works.
Is this even possible? Why the browser still waits for that request to finish and send back a response and not refresh the page?

LATER EDIT (SOLVED): it seems that the waiting problem is actually from the server. If in the ajax call, the script uses the SESSION then the web page will freeze until the request is finished, even if we abort the xhr.
Why is that? Explanation:
Session data is usually stored after your script terminated without the need to call session_write_close(), but as session data is locked to prevent concurrent writes only one script may operate on a session at any time. When using framesets together with sessions you will experience the frames loading one by one due to this locking. You can reduce the time needed to load all the frames by ending the session as soon as all changes to session variables are done.

A: Maybe try canceling right before refresh as in here?
window.onbeforeunload = function(event) {
    xhr.abort();
};


text:
Q: How can I programmatically select an Android Map v2 marker to test the onclick behaviour? I am trying to write an automated test for my map based Android application that uses the v2 GoogleMaps.
I need to be able to programmatically recreate the effect of a user taping a map marker so I can verify other UI activities occur.
I have looked into using Robotium however, the extensions available for GoogleMaps only support v1 and I am using v2. Espresso doesn't seem to have any support at all for GoogleMaps so I am left with either adding my own extensions or using plain ActivityInstrumentationTestCase2 implementations.
Any ideas?

A: Do this work for you?
Projection projection = map.getProjection();
LatLng markerLocation = marker.getPosition();
Point screenPosition = projection.toScreenLocation(markerLocation);
long downTime = SystemClock.uptimeMillis();
long eventTime = SystemClock.uptimeMillis() + 100;
        MotionEvent motionEvent = MotionEvent.obtain(
                downTime,
                eventTime,
                MotionEvent.ACTION_UP,
                screenPosition.x,
                screenPosition.y,
                0
        );
        mapView.dispatchTouchEvent(motionEvent);

A: Use UIAutomator:
UiDevice device = UiDevice.getInstance(getInstrumentation());
UiObject marker = device.findObject(new UiSelector().descriptionContains("marker title"));
marker.click();

my complete answer:
Using Espresso to Unit Test Google Maps


text:
Q: How to ensure two asynchronous tasks that 'start' together are completed before running another? I am setting up an app that utilizes promiseKit as a way to order asynchronous tasks. I currently have a set up which ensures two async functions (referred to as promises) are done in order (lets call them 1 and 2) and that another set of functions (3 and 4) are done in order. Roughly:
import PromiseKit
override func viewDidAppear(_ animated: Bool) {

        firstly{
            self.promiseOne() //promise #1 happening first (in relation to # 1 and #2)
            }.then{_ -> Promise<[String]> in
                self.promiseTwo()//promise #2 starting after 1 has completed
            }
            .catch{ error in
                print(error)
        }
        firstly{
            self.promiseThree()//Promise #3 happening first (in relation to #3 and #4)
            }.then{_ -> Promise<[String]> in
                self.promiseFour()//Promise #4 starting after #3 has completed
            }.
            .catch{ error in
                print(error)
        }
}

Each firstly ensures the order of the functions within them by making sure the first one is completed before the second one can initiate. Using two separate firstly's ensures that 1 is done before 2, 3 is done before 4, and (importantly) 1 and 3 start roughly around the same time (at the onset of the viewDidAppear()). This is done on purpose because 1 and 3 are not related to each other and can start at the same time without any issues (same goes for 2 and 4). The issue is that there is a fifth promise, lets call it promiseFive that must only be run after 2 and 4 have been completed. I could just link one firstly that ensure the order is 1,2,3,4,5, but since the order of 1/2 and 3/4 is not relevant, linking them in this fashion would waste time.
I am not sure how to set this up so that promiseFive is only run upon completion of both 2 and 4. I have thought to have boolean-checked functions calls at the end of both 2 and 4, making sure the other firstly has finished to then call promiseFive but, since they begin asynchronously (1/2 and 3/4), it is possible that promiseFive would be called by both at the exact same time with this approach, which would obviously create issues. What is the best way to go about this?

A: You can use when or join to start something after multiple other promises have completed. The difference is in how they handled failed promises. It sounds like you want join. Here is a concrete, though simple example.
This first block of code is an example of how to create 2 promise chains and then wait for both of them to complete before starting the next task. The actual work being done is abstracted away into some functions. Focus on this block of code as it contains all the conceptual information you need.
Snippet
let chain1 = firstly(execute: { () -> (Promise<String>, Promise<String>) in
    let secondPieceOfInformation = "otherInfo" // This static data is for demonstration only

    // Pass 2 promises, now the next `then` block will be called when both are fulfilled
    // Promise initialized with values are already fulfilled, so the effect is identical
    // to just returning the single promise, you can do a tuple of up to 5 promises/values
    return (fetchUserData(), Promise(value: secondPieceOfInformation))

}).then { (result: String, secondResult: String) -> Promise<String> in
    self.fetchUpdatedUserImage()
}

let chain2 = firstly {
    fetchNewsFeed() //This promise returns an array

}.then { (result: [String : Any]) -> Promise<String> in

    for (key, value) in result {
        print("\(key) \(value)")
    }
    // now `result` is a collection
    return self.fetchFeedItemHeroImages()
}

join(chain1, chain2).always {
    // You can use `always` if you don't care about the earlier values

    let methodFinish = Date()
    let executionTime = methodFinish.timeIntervalSince(self.methodStart)
    print(String(format: "All promises finished %.2f seconds later", executionTime))
}

PromiseKit uses closures to provide it's API. Closures have an scope just like an if statement. If you define a value within an if statement's scope, then you won't be able to access it outside of that scope.
You have several options to passing multiple pieces of data to the next then block.

*

*Use a variable that shares a scope with all of the promises (you'll likely want to avoid this as it works against you in managing the flow of asynchronous data propagation)

*Use a custom data type to hold both (or more) values. This can be a tuple, struct, class, or enum.

*Use a collection (such as a dictionary), example in chain2

*Return a tuple of promises, example included in chain1
You'll need to use your best judgement when choosing your method.
Complete Code
import UIKit
import PromiseKit

class ViewController: UIViewController {

    let methodStart = Date()

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        <<Insert The Other Code Snippet Here To Complete The Code>>

        // I'll also mention that `join` is being deprecated in PromiseKit
        // It provides `when(resolved:)`, which acts just like `join` and
        // `when(fulfilled:)` which fails as soon as any of the promises fail
        when(resolved: chain1, chain2).then { (results) -> Promise<String> in
            for case .fulfilled(let value) in results {
                // These promises succeeded, and the values will be what is return from
                // the last promises in chain1 and chain2
                print("Promise value is: \(value)")
            }

            for case .rejected(let error) in results {
                // These promises failed
                print("Promise value is: \(error)")
            }

            return Promise(value: "finished")
            }.catch { error in
                // With the caveat that `when` never rejects
        }
    }

    func fetchUserData() -> Promise<String> {
        let promise = Promise<String> { (fulfill, reject) in

            // These dispatch queue delays are standins for your long-running asynchronous tasks
            // They might be network calls, or batch file processing, etc
            // So, they're just here to provide a concise, illustrative, working example
            DispatchQueue.global().asyncAfter(deadline: .now() + 2.0) {
                let methodFinish = Date()
                let executionTime = methodFinish.timeIntervalSince(self.methodStart)

                print(String(format: "promise1 %.2f seconds later", executionTime))
                fulfill("promise1")
            }
        }

        return promise
    }

    func fetchUpdatedUserImage() -> Promise<String> {
        let promise = Promise<String> { (fulfill, reject) in
            DispatchQueue.global().asyncAfter(deadline: .now() + 2.0) {
                let methodFinish = Date()
                let executionTime = methodFinish.timeIntervalSince(self.methodStart)

                print(String(format: "promise2 %.2f seconds later", executionTime))
                fulfill("promise2")
            }
        }

        return promise
    }

    func fetchNewsFeed() -> Promise<[String : Any]> {
        let promise = Promise<[String : Any]> { (fulfill, reject) in
            DispatchQueue.global().asyncAfter(deadline: .now() + 1.0) {
                let methodFinish = Date()
                let executionTime = methodFinish.timeIntervalSince(self.methodStart)

                print(String(format: "promise3 %.2f seconds later", executionTime))
                fulfill(["key1" : Date(),
                         "array" : ["my", "array"]])
            }
        }

        return promise
    }

    func fetchFeedItemHeroImages() -> Promise<String> {
        let promise = Promise<String> { (fulfill, reject) in
            DispatchQueue.global().asyncAfter(deadline: .now() + 2.0) {
                let methodFinish = Date()
                let executionTime = methodFinish.timeIntervalSince(self.methodStart)

                print(String(format: "promise4 %.2f seconds later", executionTime))
                fulfill("promise4")
            }
        }

        return promise
    }
}

Output

promise3 1.05 seconds later
  array ["my", "array"]
  key1 2017-07-18 13:52:06 +0000
  promise1 2.04 seconds later
  promise4 3.22 seconds later
  promise2 4.04 seconds later
  All promises finished 4.04 seconds later
  Promise value is: promise2
  Promise value is: promise4

A: The details depend a little upon what types of these various promises are, but you can basically return the promise of 1 followed by 2 as one promise, and return the promise of 3 followed by 4 as another, and then use when to run those two sequences of promises concurrently with respect to each other, but still enjoy the consecutive behavior within those sequences. For example:
let firstTwo = promiseOne().then { something1 in
    self.promiseTwo(something1)
}

let secondTwo = promiseThree().then { something2 in
    self.promiseFour(something2)
}

when(fulfilled: [firstTwo, secondTwo]).then { results in
    os_log("all done: %@", results)
}.catch { error in
    os_log("some error: %@", error.localizedDescription)
}

This might be a situation in which your attempt to keep the question fairly generic might make it harder to see how to apply this answer in your case. So, if you are stumbling, you might want to be more specific about what these four promises are doing and what they're passing to each other (because this passing of results from one to another is one of the elegant features of promises).


text:
Q: Android / Java Development - Horizontal Scroll View I am wondering how to make multiple horizontal scroll views in one xml file.
Is this a simple adjustment from a normal Scroll View or is this a lot more complex?
Thanks

A: yes you should be able to put multiple scroll views in on xml. You can try something like:
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayoutRight" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
<HorizontalScrollView android:id="@+id/scrollView1" android:background="#000" android:layout_width="match_parent" android:layout_height="300dp">
</HorizontalScrollView>
 <HorizontalScrollView android:id="@+id/scrollView1" android:background="#f00" android:layout_width="match_parent" android:layout_height="300dp">
  </HorizontalScrollView>
</LinearLayout>


text:
Q: No match with qi::repeat and optional parser I've been experimenting with Qi to parse a simple, new-line delimited
file of vertices.  In the following format (expressed in my made-up easy to read notation):
double double double optional(either (int int int optional(int)) or (double double double optional(double)))
My test-cases start failing with repeat and I can't find the error. The comments in the code are hopefully more enlightening:
#include <boost/spirit/include/qi.hpp>
#include <string>
#include <iostream>

using namespace boost::spirit;

qi::rule<std::string::iterator, ascii::space_type> vertexRule =
  (double_ >> double_ >> double_);

qi::rule<std::string::iterator, ascii::space_type> colorRule =
  (double_ >> double_ >> double_ >> -(double_)) | (uint_ >> uint_ >> uint_ >> -(uint_));

template<typename Iterator, typename Rule>
bool parseIt(Iterator begin, Iterator end, Rule rule) {
  bool r = qi::phrase_parse(
    begin, end,
    rule,
    ascii::space
    );

  if(begin != end) {
    std::cout << "No full match!" << std::endl;
    while(begin != end)
      std::cout << *begin++;
    return false;
  }
  return r;
}

int main()
{
  qi::rule<std::string::iterator, ascii::space_type> rule1 =
    repeat(3)[vertexRule >> -(colorRule)];

  std::string t1{
    "20.0 20.0 20.0\n"
      "1.0 1.0 1.0 255 0 255 23\n"
      "1.0 1.0 1.0 1.0 0.3 0.2 0.3\n"
        };
  std::cout << std::boolalpha;
  // matches
  std::cout << parseIt(t1.begin(), t1.end(), rule1) << std::endl;

  // 3 double 3 ints
  std::string test{"1.0 1.0 1.0 1 3 2\n"};
  // matches individually
  std::cout << parseIt(test.begin(), test.end(), vertexRule >> -(colorRule)) << std::endl;

  // offending line added at the end
  // but position does not matter
  // also offending 3 double 3 double
  std::string t2{
    "20.0 20.0 20.0\n"
      "1.0 1.0 1.0 255 0 255 23\n"
      "1.0 1.0 1.0 1.0 0.3 0.2 0.3\n"
      "1.0 1.0 1.0 1 3 2\n"
      };

  qi::rule<std::string::iterator, ascii::space_type> rule2 =
    repeat(4)[vertexRule >> -(colorRule)];

  // does not match
  std::cout << parseIt(t2.begin(), t2.end(), rule2) << std::endl;

  // interestingly this matches
  // std::string t2{
  //     "1.0 1.0 1.0 1 3 2\n"
  //     "1.0 1.0 1.0 1 3 2\n"
  //     "1.0 1.0 1.0 1 3 2\n"
  //     "1.0 1.0 1.0 1 3 2\n"
  //     };
}

I'm new to parser construction and especially Boost.Spirit. So comments pointing out the obvious are also appreciated.

A: Your prose description and sample inputs seem to indicate line-ends have significance to your grammar.
Yet, I cannot find any evidence of the fact that you tried to express that in your rules.
There is one other issue with the ambiguity between double_ and uint_ (see below).
Here is a reworked sample that adds a custom skipper (that will no eat the eol). Also, I made it accept any number of trailing eol, but nothing else:
skipper = qi::char_(" \t");

bool r = qi::phrase_parse(
             begin, end,
             (vertexRule >> -colorRule) % qi::eol >> *qi::eol >> qi::eoi,
             skipper
         );

Full code returning success for all parses:
#include <boost/spirit/include/qi.hpp>
#include <string>
#include <iostream>

using namespace boost::spirit;

template<typename Iterator>
bool parseIt(Iterator begin, Iterator end)
{
    qi::rule<Iterator, qi::blank_type> vertexRule, colorRule;

    vertexRule = double_ >> double_ >> double_;
    colorRule  = (double_ >> double_ >> double_ >> -(double_)) | (uint_ >> uint_ >> uint_ >> -(uint_));

    bool r = qi::phrase_parse(
                 begin, end,
                 (vertexRule >> -colorRule) % qi::eol >> *qi::eol >> qi::eoi,
                 qi::blank
             );

    if(begin != end)
    {
        std::cout << "No full match! '" << std::string(begin, end) << std::endl;
        return false;
    }
    return r;
}

int main()
{
    std::string t1
    {
        "20.0 20.0 20.0\n"
        "1.0 1.0 1.0 255 0 255 23\n"
        "1.0 1.0 1.0 1.0 0.3 0.2 0.3\n"
    };
    std::cout << std::boolalpha;
    // matches
    std::cout << parseIt(t1.begin(), t1.end()) << std::endl;

    // 3 double 3 ints
    std::string test {"1.0 1.0 1.0 1 3 2\n"};
    // matches individually
    std::cout << parseIt(test.begin(), test.end()) << std::endl;

    // offending line added at the end
    // but position does not matter
    // also offending 3 double 3 double
    std::string t2
    {
        "20.0 20.0 20.0\n"
        "1.0 1.0 1.0 255 0 255 23\n"
        "1.0 1.0 1.0 1.0 0.3 0.2 0.3\n"
        "1.0 1.0 1.0 1 3 2\n"
    };

    // does not match
    std::cout << parseIt(t2.begin(), t2.end()) << std::endl;

    // interestingly this matches
    // std::string t2{
    //     "1.0 1.0 1.0 1 3 2\n"
    //     "1.0 1.0 1.0 1 3 2\n"
    //     "1.0 1.0 1.0 1 3 2\n"
    //     "1.0 1.0 1.0 1 3 2\n"
    //     };
}

uint_ versus double_
As mentioned, there is also an ambiguity lurking here:
colorRule  = (double_ >> double_ >> double_ >> -(double_)) | (uint_ >> uint_ >> uint_ >> -(uint_));

As it stands, the (uint_ >> uint_ >> uint_ >> -(uint_) part of the rule will never be matched, as it would also match the first part (with double_). I'd simply rewrite this as
colorRule  = double_ >> double_ >> double_ >> -double_;

Unless of course the meaning of the values changes if they are specified as floats (e.g. uints go from 0..255, but doubles go from 0.0..1.0). In that case I can see why you would want to detect integer-ness. You can achieve that by reordering.
colorRule  = (uint_ >> uint_ >> uint_ >> -(uint_))
           | (double_ >> double_ >> double_ >> -(double_));

To make things easier on the user of the parser, I'd simply expose the same attribute type at all times, and consider a semantic action to convert the integers to doubles using whatever conversion appropriate:
#include <boost/spirit/include/phoenix_operator.hpp>
// ....

qi::rule<Iterator, Skipper, double()> colorInt = uint_ [ _val = _1 / 255.0 ];
colorRule = (colorInt >> colorInt >> colorInt >> -(colorInt))
           | (double_ >> double_ >> double_ >> -(double_));


text:
Q: How do I debug a custom Colorbox installation for Magento I wanted to have a Colorbox (http://jacklmoore.com/colorbox/) lightbox that would display product images in a mini gallery for static pages.
I installed colorbox onto Magento:
JS

*

*/skin/frontend/{custom}/default/js/colorbox.inline.js

*(for the inline script that is in the head on the examples)

*/skin/frontend/{custom}/default/js/jquery.colorbox.js
CSS
 - /skin/frontend/{custom}/default/css/colorbox.css
Images
 - /skin/frontend/{custom}/default/images/...

I updated the XML of the page in the backend under 'Custom Layout Update XML' as follows:

    skin_csscss/colorbox.css
    skin_jsjs/jquery/jquery.1.6.min.js
    skin_jsjs/jquery/jquery.colorbox.js
    skin_jsjs/jquery/colorbox.inline.js

When I click on the colorbox class links to test, the image opens in the same tab, but as an external file.  I set up a local file that references the same images, and references the JS and CSS files that I'm using for Magento, and the lightbox works.
I'm a bit perplexed with what's going on so any tips, ideas, and advice is most welcome.
Cheers!

A: This is what you need.
Move you javascript files to /js/colorbox/jquery.colorbox.js
                             /js/colorbox/colorbox.inline.js
<reference name="head">
    <action method="addJs"><script>colorbox/jquery.colorbox.js</script></action>
    <action method="addJs"><script>colorbox/colorbox.inline.js</script></action>
</reference >

This will get you javascript files to load. see the page.xml file to see how to load css files from the skin folder.


text:
Q: Determine the point of intersection between a line and contour represented by list of points Given : List of points representing a closed contour
Task  : Choose a random point on the contour and shoot a ray inside the contour and determine the point where the ray intersects the contour. This needs to be implemented with some programming language.
The approach I have in mind is to interpolate the points and solve the equations of the line and the curve. Is there any library in C++ which can achieve this or any simpler math besides interpolation, or any hints.

A: I would treat the contour as a set of line segments and perform an intersection test between each line segment and your ray. Geometric tools has a very comprehensive library of intersections tests and I've used it successfully for many applications.


text:
Q: Is the quantum harmonic oscillator energy $E = n\hbar\omega$ or $E = (n + 1/2)\hbar\omega$? (Feynman Lectures) Please, read the whole question. I've discussed a few contradictions and so far have not found an explanation for them.
I was reading The Feynman Lectures on Physics (vol. 1), the part where he talks about black-body radiation. When he explains the Planck hypothesis, he states that the oscillators have energy $E_n = nhf = n \hbar \omega $ where $n = 0, 1, 2...$

The image above shows Feynman's energy levels for the quantum harmonic oscillator.
My problem with this is that I am pretty sure the energy levels are actually
$$E_n = \left(n + \frac{1}{2} \right) \hbar \omega.$$
Using Feynman's energy expression, we may use Boltzmann statistics to find the average energy per oscillator:
$$\langle E \rangle = \frac{\hbar\omega}{e^{\frac{\hbar\omega}{kT}} - 1} $$
If we take the limit $T \to 0$, the average energy becomes $0$, and therefore the system has zero total energy.
But we know this isn't true!, since zero point energy is a very important concept in Quantum Mechanics (it even has a relationship with Heisenberg's Uncertainty Principle), and we know that the energy in the limit $T \to 0$ should be nonzero.
Using the $\left(n + 1/2\right)\hbar\omega$ energy expression, we use Boltzmann statistics to find the average energy to be:
$$ \langle E \rangle = \hbar\omega \left (\frac{1}{2} + \frac{1}{e^{\frac{\hbar\omega}{kT}} - 1}\right) $$
If we take the same limit $T \to 0$, the average energy becomes $\frac{\hbar\omega}{2}$, which is a nonzero energy (the zero point energy of the quantum harmonic oscillator, as expected).
Of course, this appears to show that the two contradictory expressions are truly fundamentally different.
But the problem goes on:
Feynman goes on to derive this formula for black-body radiation, based on his results for the average energy:
$$I(\omega) = \frac{\hbar\omega^3}{\pi^2c^2(e^{\frac{\hbar\omega}{kT}} - 1)}$$
Which appears to be the correct formula, as evidenced by Wikipedia's article on Planck's Law.
I tried finding anything about the average energy formula as derived by using the $(n + 1/2)\hbar\omega$ energy expression, and I did indeed find it in Wikipedia's article on zero point energy. The article claims:

In 1912, Max Planck published the first journal article to describe the discontinuous emission of radiation, based on the discrete quanta of energy. In Planck's "second quantum theory" resonators absorbed energy continuously, but emitted energy in discrete energy quanta only when they reached the boundaries of finite cells in phase space, where their energies became integer multiples of hν. This theory led Planck to his new radiation law, but in this version energy resonators possessed a zero-point energy, the smallest average energy a resonator could take on. Planck's radiation equation contained a residual energy factor, one $h\nu/2$, as an additional term dependent on the frequency $\nu$, which was greater than zero (where $h$ is Planck's constant). It is therefore widely agreed that "Planck's equation marked the birth of the concept of zero-point energy." In a series of papers from 1911 to 1913, Planck found that the average energy of an oscillator to be:

And the above image from Wikipedia shows exactly the formula for average energy with nonzero zero point energy.
But the seeming contradiction is that the correct formula for black-body radiation appears to have been derived from a wrong (?) expression for energy (and therefore, wrong expression for average energy). Adding the $1/2$ factor changes the black-body radiation law, but this "correct" formula is nowhere to be found. It is as if Feynman's $n\hbar\omega$ expression finds the correct (?) formula for black-body radiation, but using the correct $(n + 1/2)\hbar\omega$ leads to a formula that appears to predict nonzero emission at $T = 0$.
And, as I've discussed before, the Feynman expression predicts no zero point energy, so it cannot (?) be correct.
How do I reconcile all of this? I am trying to search for an explanation but I'm making no progress whatsoever.

A: Planck's original postulate was that oscillators have energies
$$E=n\hbar\omega\quad(n=0,1,2,\ldots)$$
This is also the result we obtain if we analyse the harmonic oscillator with old, semiclassical Quantum Theory. Only later did Planck add the $\frac{\hbar\omega}{2}$ term, but was a mostly just a matter of luck that it matched up with the actual Quantum Harmonic Oscillator's ground state. The actual energy formula
$$E=\hbar\omega\left(n+\frac{1}{2}\right)$$
was only first discovered decades later, with the advent of proper Quantum Mechanics brought about by Heisenberg.
While it is true that zero-point energy plays an important role in Quantum Mechanics, in this specific case of thermal radiation we only really care about the energy changes, not the total energy, which is why the first formula can be used to derive Blackbody radiation with no problems.


text:
Q: Warning: 'as' will become a reserved keyword in Python 2.6 while running npm install (e.g. https://github.com/donpark/html2jade), I run into this error:
/usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/input.py:852: Warning: 'as' will become a reserved keyword in Python 2.6
Traceback (most recent call last):
  File "/usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp", line 15, in <module>
    import gyp
  File "/usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/__init__.py", line 8, in <module>
    import gyp.input
  File "/usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/input.py", line 852
    except ImportError as e:
                        ^
SyntaxError: invalid syntax

python --version generates 'Python 2.7.1'

A: This would not be a syntax error in Python 2.7.1. A quick workaround would be to run this programme as python /full/path/to/scriptname.py, which will actually use Python 2.7.1.


text:
Q: How to make checkbox background transparent? i use the following code to make check box background transparent or in my case off white but i can't find what wrong with this plz help me how to do this?
HBRUSH CfvcolorDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
 HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);

 pDC->SetBkColor(MYCOLOR);

 if((HBRUSH)brush == NULL)
    brush.CreateSolidBrush(MYCOLOR);
 return (HBRUSH) brush;
}

A: where is 'brush' declared? As you posted it it won't even compile.


text:
Q: Create a shell namespace extension How does acronis create this virtual folders. For example I created a backup of the folder Example located at C:\Example This is how the backup looks:

If I double click on that file then I could navigate to:

if I right click on that folder I will not get the regular menu that I get with directories. If I double click that directory then I will navigate to the content of that folder as:

Note that the content that I am looking at is inside a file not on windows explorer.
I know that if I send VirtualDir.tib to somewone they will not be able to see the same because they do not have acronis true image installed.
How could I be able to do something similar with c# ?

Edit
Sorry I just updated the title. How will I be able to create a chell namespace extension with c#?

A: To answer your question about whether it can be done in C#, the answer is no. As is explicitly stated here, writing shell extensions in managed code is entirely unsupported.
This is because shell extension DLLs can be loaded into multiple processes, some of which would already have another version of the CLR loaded.


text:
Q: How to attach SSL certificates in your network request flutter I have 2 certificates
abc.bks
abc.p12
how do i attach these in my network request ,
as of now i am making request like this:

  final url = "https://jsonplaceholder.typicode.com/posts";
  final response = await http.get(url);

  var jsonData = json.decode(response.body);
  List<APIData> users = [];
  for (var u in jsonData) {
    APIData data = APIData(
        userId: u["userId"], id: u["id"], title: u["title"], body: u["body"]);
    users.add(data);
  }


text:
Q: dill fails to pickle sympy.Float under Python 3.7 for dill.settings["recurse"]=True Under python 3.7, dill fails to pickle sympy.Float objects when the "recurse" setting is set to True:
dill.settings["recurse"] = True
import sympy
tst = sympy.Float(3.3)
dill.detect.errors(tst)

This fails with RecursionError('maximum recursion depth exceeded in comparison').
Does anybody know a workaround?
The error disappears for Python >=3.8, and also does not occur in the absence of the "recurse" setting. Unfortunately I need to support Python 3.7 and am forced to use the "recurse" mode.

A: Change pickle protocol from 3 to 4:
import dill
dill.settings["recurse"] = True
dill.settings["protocol"] = 4  # Add this
import sympy
tst = sympy.Float(3.3)
dill.detect.errors(tst)

In Python 3.8 and above, pickle sets DEFAULT_PROTOCOL = 4.
Explanation

*

*In pickle save_reduce, if protocol < 4, a func is saved instead of the Float class:

if self.proto >= 4:
    save(cls)
    save(args)
    save(kwargs)
    write(NEWOBJ_EX)
else:
    func = partial(cls.__new__, cls, *args, **kwargs)
    save(func)
    save(())
    write(REDUCE)

*With "recurse" = True, dill recursively traces and pickles objects referred to in the global dictionary of functions (starting with cls.__new__, i.e. Float.__new__).

*sympy has circular references in Float.__new__ → _convert_numpy_types → sympify → _convert_numpy_types (repeated) → ...
Proof of concept
You can reproduce the error with:
def a():
    b

def b():
    a

import dill
dill.settings["recurse"] = True
dill.detect.errors(a)

A: I'm the dill author.  I'm not seeing the reported behavior.  Maybe you are using an older version of Python, dill, or sympy.
Python 3.7.13 (default, May 10 2022, 11:13:40)
[Clang 10.0.1 (clang-1001.0.46.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> import sympy
>>> dill.__version__
'0.3.6.dev0'
>>> sympy.__version__
'1.10.1'
>>> tst = sympy.Float(3.3)
>>> dill.copy(tst)
3.30000000000000
>>> dill.settings['recurse'] = True
>>> dill.copy(tst)
3.30000000000000
>>> dill.detect.errors(tst)
>>>

Here, copy(tst) is the same as loads(dumps(tst)). If your versions are older than mine, and after you update you still see the same behavior (or it otherwise persists for you), then please do let me know in the comments (and fill out an issue on the dill GitHub page).
Note: We have a release that is imminent, so dill-0.3.6 will be out in a matter of days.


text:
Q: Having trouble understanding order of evaluation in Python method call Just wondering if anyone can help me understand this code a little better. Here is the program:
class Card(object):
    """ A playing card. """
    RANKS = ["A", "2", "3", "4", "5", "6", "7",
             "8", "9", "10", "J", "Q", "K"]
    SUITS = ["c", "d", "h", "s"]

    def __init__(self, rank, suit):
        self.rank = rank
        self.suit = suit

    def __str__(self):
        rep = self.rank + self.suit
        return rep

class Hand(object):
""" A hand of playing cards. """
    def __init__(self):
        self.cards = []

    def __str__(self):
        if self.cards:
           rep = ""
           for card in self.cards:
               rep += str(card) + "\t"
        else:
            rep = "<empty>"
        return rep

    def clear(self):
        self.cards = []

    def add(self, card):
        self.cards.append(card)

    def give(self, card, other_hand):
        self.cards.remove(card)
            other_hand.add(card)

class Deck(Hand):
    """ A deck of playing cards. """

    def populate(self):
        for suit in Card.SUITS:
            for rank in Card.RANKS:
                self.add(Card(rank, suit))   # <- HERE

    def shuffle(self):
        import random
        random.shuffle(self.cards)

    def deal(self, hands, per_hand = 1):
        for rounds in range(per_hand):
            for hand in hands:
                if self.cards:
                    top_card = self.cards[0]
                    self.give(top_card, hand)
                else:
                    print("Can't continue deal. Out of cards!")

# main
deck1 = Deck()
print("Created a new deck.")
print("Deck:")
print(deck1)

deck1.populate()
print("\nPopulated the deck.")
print("Deck:")
print(deck1)

The thing I'm wondering about is self.add(Card(rank, suit)) it's confusing me. Does Card(rank, suit) get sent to the add method straight away or does it get sent to the Card class first and then go to the add method? The add method has a cardparameter, what gets put into that parameter?
If I'm not making much sense it's because I've been staring at this for 2 hours.
Thanks

A: It's pretty simple.
Any time you call a class in Python, you create a new instance of the class.  So if you call the Card class, you create a new instance of class Card... in other words, you create a new card.
Let's create the ace of spades:
ace_of_spades = Card('A', 's')

But I'm cheating.  I looked and saw what strings to pass to Card when I should be using the pre-defined constants.  Let's do it more properly:
ace_of_spades = Card(Card.RANKS[0], Card.SUITS[3])

Hmm, I'm not sure that Card.RANKS[0] is that easy to understand.  Personally I would probably do something like
class Card(object):
    RANK_ACE = 'A'
    RANK_2 = '2'
    # and so on

and then:
ace_of_spades = Card(Card.RANK_ACE, Card.SUIT_SPADES)

Now that we have used the variable name ace_of_spades to hold a reference to the card, we can use the card:
hand = Hand()
hand.add(ace_of_spades)

But if we just want to get the card into the hand, we don't need that variable name ace_of_spades.  We could remove the name:
del(ace_of_spades)

But there is no need to use the name in the first place.  We can simply do:
hand.add(Card(Card.RANK_ACE, Card.SUIT_SPADES))

This creates the card, then immediately passes the newly created card to Hand.add() to add it to a hand.
You don't, strictly speaking, need to store the ranks and suits inside the Card class.  In Python, it might be more common to put these things outside of the classes, in "module" scope.  I would most likely do:
RANK_ACE = 'A'
RANK_2 = '2'
# and so on
SUIT_CLUBS = 'c'
# and so on

class Card(object):
    # and so on

But if you are taking a class and your teacher wants you to put constants inside your programs' classes, then do that.
EDIT: You are trying to figure out what self.add() does in the program.
Here's the source code for it:
# inside class Hand
def add(self, card):
    self.cards.append(card)

self refers to the object.  To see how this works, let's imagine you have an instance of class Hand, saved in the variable h.  If you call h.add(ace_of_spades) then the self in this function will be set to the same instance of Hand that h refers to.
In fact, the call h.add(ace_of_spades) is exactly the same as doing this call:
Hand.add(h, ace_of_spades)

When you use the form h.add(), Python automatically does the same thing as the above call.  Python looks at h and figures out that it is an instance of class Hand.  Then Python looks in class Hand for a function called add().  Then Python builds a call similar to the one shown above.
self.cards refers to a list object stored inside the Hand instance.  Python lists have a method function, .append(), that appends an item to the list.
You can read more about classes and method functions here: http://docs.python.org/2/tutorial/classes.html

A: Good question. You are definitely making sense :)
Here's what's happening in self.add(Card(rank, suit)): note that self.add(Card(rank, suit)) is being called from within a nested for loop. The rank and suit parameters are defined by those loops. You are right, Card(rank, suit) is evaluated first, then the returned card object is fed as a parameter to self.add method on the Deck. So, the combination of loops and method calls populates the deck with 52 card objects -- one of each suit and face. Does that make sense?

A:
Q1: Does (Card(rank, suit)) get sent to the add method straight away or
  does it get sent to the Card class first and then go to the add
  method?

Here's what's happening in self.add(Card(rank, suit)):

*

*Card(rank, suit) calls Card's __new__ and __init__ methods. __new__ creates a new Card object and the __init__ method initializes it to have the given rank an suit.

*That new card is passed to Deck.add() method where it is appended to self.cards list (Note that Deck inherits the cards list and add method from Hand)

Here I've stripped the code down to only the necessary methods for reference:
class Card(object):
    def __init__(self, rank, suit):
        self.rank = rank
        self.suit = suit

class Hand(object):
    def __init__(self):
        self.cards = []
    def add(self, card):
        self.cards.append(card)

class Deck(Hand):
    def populate(self):
        for suit in Card.SUITS:
            for rank in Card.RANKS:
                self.add(Card(rank, suit))

Q2: The add method has a 'card' parameter, what gets put into that
  parameter?

The newly created Card as described above

A: If you add two print statements like these:
In Card class:
def __init__(self, rank, suit):
    print "card.init: {} {}".format(rank, suit)
    self.rank = rank
    self.suit = suit

In Hand:
def add(self, card):
    print "add: {}".format(card)
    self.cards.append(card)

You will see this output:
Created a new deck.
Deck:
<empty>
card.init: A c
add: Ac
card.init: 2 c
add: 2c
card.init: 3 c
add: 3c


text:
Q: onBackPressed() not called first time from AppCompatActivity I have a series of fragments that are called in order A > B > C from user interaction. The Navigates by clicking "Launch B" from A, and "Launch C" from B.
If the user is on C, and clicks back, I need to clear an Activity level variable, so I have an interface/callback that is set. When my activity overrides onBackPressed(), the callback is called.
I am then on Fragment B, and I press back again. onBackPressed() is not called this time. Pressing it a second time does call it.
public interface BackOverrideCallback {
    void onBack();
}

private BackOverrideCallback mBackOverride;

private BackOverrideCallback mFragCBack = new BackOverrideCallback () {
    @Override
    public void onBack() {
        mVar = null;
        getSupportFragmentManager().popBackStack();
        mBackOverride = null;
    }
};

@Override
public void onBackPressed() {
    if (mBackOverride != null) {
        mBackOverride.onBack();
    } else {
        super.onBackPressed();
    }
}

My API 19 emulator Logcat shows this when the back press does nothing:
com.android.systemui D/EGL_emulation: eglMakeCurrent: 0xb891dad0: ver 2 0
system_process E/SoundPool: error loading /system/media/audio/ui/Effect_Tick.ogg
system_process W/AudioService: Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
system_process E/SoundPool: error loading /system/media/audio/ui/Effect_Tick.ogg
system_process W/AudioService: Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
system_process E/SoundPool: error loading /system/media/audio/ui/Effect_Tick.ogg
system_process W/AudioService: Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
system_process E/SoundPool: error loading /system/media/audio/ui/Effect_Tick.ogg
system_process W/AudioService: Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
system_process E/SoundPool: error loading /system/media/audio/ui/Effect_Tick.ogg
system_process W/AudioService: Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
system_process E/SoundPool: error loading /system/media/audio/ui/KeypressStandard.ogg
system_process W/AudioService: Soundpool could not load file: /system/media/audio/ui/KeypressStandard.ogg
system_process E/SoundPool: error loading /system/media/audio/ui/KeypressSpacebar.ogg
system_process W/AudioService: Soundpool could not load file: /system/media/audio/ui/KeypressSpacebar.ogg
system_process E/SoundPool: error loading /system/media/audio/ui/KeypressDelete.ogg
system_process W/AudioService: Soundpool could not load file: /system/media/audio/ui/KeypressDelete.ogg
system_process E/SoundPool: error loading /system/media/audio/ui/KeypressReturn.ogg
system_process W/AudioService: Soundpool could not load file: /system/media/audio/ui/KeypressReturn.ogg
system_process E/SoundPool: error loading /system/media/audio/ui/KeypressInvalid.ogg
system_process W/AudioService: Soundpool could not load file: /system/media/audio/ui/KeypressInvalid.ogg
system_process W/AudioService: onLoadSoundEffects(), Error -1 while loading samples

API 27 Logcat shows this
? W/audio_hw_generic: Not supplying enough data to HAL, expected position 30719740 , only wrote 30719520
com.android.systemui D/EGL_emulation: eglMakeCurrent: 0xa59843c0: ver 2 0 (tinfo 0xa59835d0)
system_process D/AutofillManagerService: onBackKeyPressed()


text:
Q: Clicking on audio/video file in Gnome Files opens Gnome Videos, but file is not played After an upgrade (Debian bookworm) I found that starting a video/audio using Gnome Files (nautilus) will start Gnome Videos (totem), but totem gives me a blank screen with no files selected to play.
The result is not the same as running totem from terminal, because then the playlist is opened first. When specifiying totem videofile.mkv the file plays without problem. When selecting vlc to play the files from Gnome Files, the file also plays.
Unfortunately I am not familiar with the Gnome file handling mechanism, so I am not even sure where the problem is. Anyone could help?


text:
Q: WCF Workflow Service - How to add Workflow Control Endpoint? I've created a new WCF Workflow Service project in VS2012.
Ultimately, what I need is the ability to terminate instance B of my workflow from instance A of my workflow.
As best I can tell, the only way to achieve that is via the Workflow Control Endpoint, but I can't figure out how to add/access that to my project.
From what I've seen (e.g. here), to add the control endpoint, you just add an <endpoint> element to <service> node in web.config with the appropriate attribute values. The problem is.. I don't have a <service> element in my web.config. The "WCF Workflow Service Application" project template does not add one. My web.config is below.
So my question is simply: Starting from the "WCF Workflow Service Application" project template, how do I add a Workflow Control Endpoint?
These are the default launch settings for the project:

web.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" strict="false" explicit="true" targetFramework="4.5" >
    </compilation>
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>

A: Finally found a solution for this. See this post.


text:
Q: WinError 2: The system cannot find the file specified I am brand new to setting up an editor for Python. I am trying to setup Sublime Text to start learning Python for my job.
I have setup the editor and attempt to run the 'Hello World' text using the Python build within Sublime.
The following error message occurs:
[WinError 2] The system cannot find the file specified
[cmd: ['py', '-u', 'C:\\Users\\myname\\OneDrive\\Documents\\Python_Projects\\intro.py']]
[dir: C:\Users\myname\OneDrive\Documents\Python_Projects]
[path: C:\Windows\System32;C:\Windows;C:\Windows\System32\wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\MATLAB\R2021a\bin;C:\Users\myname\AppData\Local\Microsoft\WindowsApps;]
[Finished]

I tried running the code using automatic build settings and python build settings directly. Still no luck.
I see that a MATLAB file directory is being called in the "path:" and I thought maybe that might be the interference?
Thank you!

A: I assume that if you are working with Sublime Text, then you have downloaded and installed the executable version of Python from Python.org. Here I show a reference just in case.

So, It seems, by your error messages, that in your "windows PATH" there isn't a reference to Python.exe. Maybe you have forgotten to mark the "Add Python.exe to PATH" box. This right here.

There is a way to add it manually, here is the link of the post that explains it: Adding Python to PATH on Windows
But in my case, I prefer to uninstall both "Sublime Text" and "Python" and reinstall it, I start with Python (don't forget to check the "path" box) and then install Sublime Text
You should verify that everything works fine by checking it in the TOOLS box in the Sublime Text menu bar. The version of Python you have installed will appear there.


text:
Q: iPad App Navigation with SlideView - change size of UIView? i want to create a slide out menu which has a normal width of about 50 pixels, and if the user press the expand button i will also show the labels for the button.
Like in this example:

What is the correct way to create such a menu? I though about using 2 views and set the size of contentview to width-50pixels.
But i am unable to change the frame of my UIView in the ViewDidLoad function. (this is an example)
override func viewDidLoad() {

    super.viewDidLoad()

    self.view.frame = CGRect(x:50, y:0, width:974, height:768)

    sidebarIsOpen = false
}

And if the user click on the expand Button
@IBAction func expandButtonClicked(sender : AnyObject) {

    var x = self.sidebarIsOpen! ? 50 : 300
    UIView.animateWithDuration(0.2, animations: {
        self.view.frame = CGRect(x:x, y:0, width:300, height:768)
        }, completion: { _ in
            self.sidebarIsOpen = !(self.sidebarIsOpen!)
        })
}

If i click the button again, everything is fine. But on ViewDidLoad i am unable to move the contentview to right.
Thanks in advance

A: Ill found already the solution by myself.
Created 2 views and animate the "contentview" on button click.
@IBOutlet weak var menuView: UIView!

@IBAction func toggleMenuButton(sender: UIBarButtonItem) {

    var x = self.sidebarIsOpen! ? 50 : 200

    UIView.animateWithDuration(0.2, animations: {
        self.contentView.frame = CGRect(x:x, y:0, width:974, height:768)
        }, completion: { _ in
            self.sidebarIsOpen = !(self.sidebarIsOpen!)
        })

}


text:
Q: Relative minimality for conic bundles Due to difficulties in finding references I am not sure of what relative minimality is about for conic bundles. Suppose we're working on con. bun. over surfaces.
The definition is ok: the fiber over any irreducible component of the discriminant curve should not be reducible. But how can I handle that concretely?
My impression is that there should always be somehow a way to reduce a non-relatively minimal conic bundle to a rel. minimal one (via birational maps, say blow-ups). Does this exist? Is there a canonical way? I would be glad if someone could make these guesses of mine more precise or give me some references.

A: You might consult
http://hal.archives-ouvertes.fr/docs/00/46/16/98/PDF/modelsgeomratcompositio.pdf
Your own definition seems a little confusing.  A conic bundle is a map whose fibers are conics.  Of course conics are embedded objects so this requires some kind of definition of a conic structure on the fibers.  Plane conics come in three versions, irreducible and smooth, two distinct lines, and a double line.  Usually a conic bundle has only the first two types and the locus in the target over which fibers are two lines is called the discriminant.
Thus for a conic bundle over a surface, the discriminant would be the curve in that surface over which the fibers are reducible, rather than irreducible.  However if that curve is empty then both statements are true.  Indeed in the cited reference, minimal [complex] conic bundles are said to be those with empty discriminant curve.  That paper studies real conic bundles for which the term minimal is said to apply to those with imaginary discriminant curve.
If instead of requiring an embedding inducing the structure of conic on the fibers, one makes a definition that the fibers are only abstractly isomorphic to conics (as in this reference), then i suppose you could blow up the source threefold along a curve meeting each fiber at most once, and change a curve of irreducible fibers into reducible ones.  That would seem to be a "non minimal" object you would want to exclude?
A general reference on [conic and] quadric bundles is Beauville's paper "Varietes de Prym et Jacobians intermediaire", in Ann. Sci. de l'Ecole Normale Sup., (4) 10 (1977), no.3, p.309 ff.
The concept of relatively minimal variety cited elsewhere here, seems related to minimal model theory, and hence presumably to the sort of bad example I proposed.  As to the definition of minimal in the paper first cited in this answer, it seems not to be a sort that can always be achieved by modifications.  I.e. it seems the threefold could be minimal and yet the discriminant curve still has real points. I am far from expert on this.

A: This paper gives the following definition of a relatively minimal variety:a relatively minimal variety $X'$ over a base $Y$ is a projective variety with at most $\mathbb{Q}$-factorial terminal singularities which has an extremal ray contraction $\phi: X'\to Y$ of fiber type, i.e., $\dim Y<\dim X$.


text:
Q: Loading multiple CSV files into MySQL I am working on a metrics project for my team.  I have to load several different reports into a central repository and then create tables and reports off of this data.
The data sources are:

*

*CSV files

*PDFs

*Ad-hoc/manual data.

I was playing with Talend and MySQL.  I am a little confused as to how to load the CSV files. Should I have a collection of directories and one or more scheduled tasks that load the files?
Another thought was to write a custom file processor that will load the file based on naming convention.  What are your thoughts?

A: "PDF" is something complicated. as it is pdf... "ad-hoc/manual data" needs much more details.
But if we focus on csv and your question is related to those guys only if I'm right, I'd do this by writing an app which calls an SP in my mySQL DB, handing over the full path to the csv (and any additional data, such as table's "user friendly name" if needed - or any other meta-data you'd like to store) which executes an import using mySQL Load Data.
The reason is, there can be many rules in the "business logic" after a csv was imported, and it's easier to maintain an app according to changing business requirements, than changing DB behavior all the time, and, if something goes terribly wrong my DB would be safe and only the "import manager app" fails - as I don't have to store neither that nor the csvs on the same system where my DB is.
DBs, relational DBs are basically about storing data, and retrieving data rapidly based on 'set theory', not about taking care of how the data gets into the system.

So think about these questions before you start implementing anything:

*

*What happens to the csv after it was processed? Can be deleted? Should be moved to e.g. a "processed" folder? Should remain/stay where it was intact?

*If should stay where it was and as it was, what should I do to know I already processed the file? (set the "ready to archive" flag, for instance? Touch the "last modified" date and set it to 1950.01.01? Add an extra property to the file?

*What should I do if csv import fails (e.g. invalid data in file, or NULL value where it shouldn't have NULLs)? Display error? Mark csv as unusable? Send e-mail? Move to "processing_failed" folder?

*What to do if file count grows huge in the input folder?

*How easily can I change the import/process/etc if business logic changes, or csv format changes?

and so on. Think through all the options you have and decide.
I hope I answered your question ;)


text:
Q: A Noetherian Ring with Discrete Spectrum is Artinian I'm trying to solve an exercise.

I should prove that if $R$ is a notherian ring and $\operatorname{Spec}(R)$ is discrete then $R$ is artinian.

I think it is enough to show that $\dim R=0$ since I can use that $R$ is artinian if and only if $R$ is noetherian and $\dim R=0$. Can you help me?
Thank you!

A: Hint
Suppose $\mathfrak{P}$ is prime, show that $\mathfrak{P}$ is maximal (Hint: $\mathfrak{P}$ is closed due to the topology on $\operatorname{Spec}(R)$).
What does that say about $\operatorname{Dim}(R)$?

A: You're on a good track, but try to think more about the discreteness. You want to say that there are no chains of prime ideals of length $1$; suppose that you had such a chain, say $\mathfrak p \subsetneqq \mathfrak q$. If $\operatorname{Spec}$ is discrete, then $\{\mathfrak p\}$ is a closed set. Is this possible? Recall what the closed subsets of $\operatorname{Spec}$ are defined to be in the Zariski topology.

A: See Theorem 293 in $\S 13.3$ of these notes: among other things, it shows that the space $\operatorname{Spec} R$ is Hausdorff iff it is separated ("$T_1$") iff $R$ has dimension zero.  Discrete spaces are Hausdorff, so there you go.
Note also that once you show that $R$ is Artinian, you will be able to conclude that $\operatorname{Spec} R$ is not only discrete but finite.