Q: BeautifulSoup and Selenium won't retrieve full html from website This is the site I'm trying to retrieve information from: https://www.baseball-reference.com/boxes/CLE/CLE202108120.shtml I want to get the box score data so like the Oakland A's total batting average in the game, at bats in the game, etc. However, when I retreive and print the html from the site, these box scores are missing completely from the html. Any suggestions? Thanks.
Here's my code:
from bs4 import BeautifulSoup
import requests

url = "https://www.baseball-reference.com/boxes/CLE/CLE202108120.shtml"

page = requests.get(url)

soup = BeautifulSoup(page.content, 'html.parser')

print(soup.prettify)

Please help! Thanks! I tried selenium and had the same problem.

A: The page is loaded by javascript. Try using the requests_html package instead. See below sample.
from bs4 import BeautifulSoup
from requests_html import HTMLSession

url = "https://www.baseball-reference.com/boxes/CLE/CLE202108120.shtml"

s = HTMLSession()

page = s.get(url, timeout=20)
page.html.render()

soup = BeautifulSoup(page.html.html, 'html.parser')

print(soup.prettify)

A: The other tables are there in the requested html, but within the comments. So you need to parse out the comments to get those additional tables:
import requests
from bs4 import BeautifulSoup, Comment
import pandas as pd

url = "https://www.baseball-reference.com/boxes/CLE/CLE202108120.shtml"
result = requests.get(url).text
data = BeautifulSoup(result, 'html.parser')

comments = data.find_all(string=lambda text: isinstance(text, Comment))

tables = pd.read_html(url)
for each in comments:
    if 'table' in str(each):
        try:
            tables.append(pd.read_html(str(each))[0])
        except:
            continue

Output:
Oakland
print(tables[2].to_string())
                   Batting    AB     R     H   RBI    BB   SO    PA     BA    OBP    SLG    OPS    Pit    Str    WPA   aLI   WPA+     WPA-    cWPA  acLI  RE24    PO     A   Details
0            Mark Canha LF   6.0   1.0   1.0   3.0   0.0  0.0   6.0  0.247  0.379  0.415  0.793   23.0   19.0  0.011  0.58  0.040  -0.029%   0.01%  1.02   1.0   1.0   0.0        2B
1        Starling Marte CF   3.0   0.0   2.0   3.0   0.0  1.0   4.0  0.325  0.414  0.476  0.889   12.0    7.0  0.116  0.90  0.132  -0.016%   0.12%  1.57   2.8   1.0   0.0    2B,HBP
2   Stephen Piscotty PH-RF   1.0   0.0   1.0   2.0   0.0  0.0   2.0  0.211  0.272  0.349  0.622    7.0    3.0  0.000  0.00  0.000   0.000%      0%  0.00   2.0   1.0   0.0       HBP
3            Matt Olson 1B   6.0   0.0   1.0   2.0   0.0  0.0   6.0  0.283  0.376  0.566  0.941   21.0   13.0 -0.057  0.45  0.008  -0.065%  -0.06%  0.78  -0.6   9.0   1.0       GDP
4        Mitch Moreland DH   5.0   3.0   2.0   2.0   0.0  0.0   6.0  0.230  0.290  0.415  0.705   23.0   16.0  0.049  0.28  0.064  -0.015%   0.05%  0.50   1.5   NaN   NaN  2·HR,HBP
5         Josh Harrison 2B   0.0   1.0   0.0   0.0   1.0  0.0   1.0  0.294  0.366  0.435  0.801    7.0    3.0  0.057  1.50  0.057   0.000%   0.06%  2.63   0.6   0.0   0.0       NaN
6             Tony Kemp 2B   4.0   3.0   3.0   0.0   1.0  0.0   5.0  0.252  0.370  0.381  0.751   16.0   10.0 -0.001  0.14  0.009  -0.010%      0%  0.24   1.6   2.0   2.0       NaN
7            Sean Murphy C   4.0   3.0   2.0   2.0   2.0  1.0   6.0  0.224  0.318  0.419  0.737   25.0   15.0  0.143  0.38  0.151  -0.007%   0.15%  0.67   2.7   7.0   0.0        2B
8          Matt Chapman 3B   1.0   3.0   0.0   0.0   5.0  1.0   6.0  0.214  0.310  0.365  0.676   31.0   10.0  0.051  0.28  0.051   0.000%   0.05%  0.49   2.2   1.0   3.0       NaN
9         Seth Brown RF-CF   5.0   1.0   1.0   1.0   0.0  1.0   6.0  0.204  0.278  0.451  0.730   18.0   12.0 -0.067  0.40  0.000  -0.067%  -0.07%  0.70  -1.7   4.0   0.0        SF
10         Elvis Andrus SS   5.0   2.0   1.0   2.0   1.0  0.0   6.0  0.233  0.283  0.310  0.593   20.0   15.0  0.015  0.42  0.050  -0.034%   0.02%  0.73  -0.1   0.0   4.0       NaN
11                     NaN   NaN   NaN   NaN   NaN   NaN  NaN   NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN   NaN    NaN      NaN     NaN   NaN   NaN   NaN   NaN       NaN
12         Chris Bassitt P   NaN   NaN   NaN   NaN   NaN  NaN   NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN   NaN    NaN      NaN     NaN   NaN   NaN   1.0   0.0       NaN
13              A.J. Puk P   NaN   NaN   NaN   NaN   NaN  NaN   NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN   NaN    NaN      NaN     NaN   NaN   NaN   0.0   0.0       NaN
14         Deolis Guerra P   NaN   NaN   NaN   NaN   NaN  NaN   NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN   NaN    NaN      NaN     NaN   NaN   NaN   0.0   0.0       NaN
15          Jake Diekman P   NaN   NaN   NaN   NaN   NaN  NaN   NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN   NaN    NaN      NaN     NaN   NaN   NaN   0.0   0.0       NaN
16             Team Totals  40.0  17.0  14.0  17.0  10.0  4.0  54.0  0.350  0.500  0.575  1.075  203.0  123.0  0.317  0.41  0.562  -0.243%   0.33%  0.72  12.2  27.0  10.0       NaN


Q: Ionic 2 Crosswalk for Android: this.platform.height()/width() inconsistent result on this.platform.ready() event I use Crosswalk plugin for Android with Ionic 2 and I've noticed, when running on a real device, that this gives an inconsistent result:
this.platform.ready().then(() => {
        console.log("this.platform.height(): " + this.platform.height() + " / this.platform.width(): " + this.platform.width());
});

Sometimes I get height and width both > 0: in this case it works.
Sometimes I get height and width == 0: in this case it does not work.
My assumption is that there might be another event in Crosswalk to notify that it is ready to display the right height and width.
I had a look around this Crosswalk web api page but I did not find what I was looking for.

A: https://ionicframework.com/docs/v2/api/platform/Platform/
width()
Gets the width of the platform’s viewport using window.innerWidth. Using this method is preferred since the dimension is a cached value, which reduces the chance of multiple and expensive DOM reads.
height()
Gets the height of the platform’s viewport using window.innerHeight. Using this method is preferred since the dimension is a cached value, which reduces the chance of multiple and expensive DOM reads.

*

*Please try using window.innerHeight and window.innerWidth to get height and width of the device at first.

*Try

// Add readySource to check if platform ready was used. The resolved value is the readySource, which states which platform ready was used.
// For example, when Cordova is ready, the resolved ready source is cordova. The default ready source value will be dom.

import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';

@Component({...})
export MyApp {
  constructor(platform: Platform) {
    platform.ready().then((readySource) => {
      console.log('Platform ready from', readySource);
      console.log('Width: ' + platform.width());
      console.log('Height: ' + platform.height());
    });
  }

*Remove Crosswalk in Ionic 2 to check if system webview can get correct results, then it should be Crosswalk issue rather than Ionic issue.

Relevant topic: https://forum.ionicframework.com/t/how-to-get-device-width-and-height/28372


Q: call local .asmx webservice from phonegap android app to get data? i m creating one phonegap test application, for that i want data from database through webservice (.asmx). i m just newer for this technology. i have spent 2 days for this call posible bt couldnt.

    function test()
    {
    jQuery.support.cors = true;
         $.mobile.allowCrossDomainPages = true;
          $.ajax({
          data: "{}",
             type: "GET",
            dataType: "json",
             contentType: "application/json; charset=utf-8",
             url: "http://localhost:xxxxx/yyyy/testservice.asmx?op=testfunction",
             success: function (msg) {
                $('#divToBeWorkedOn').html(msg.text);
             },
             error: function (e) {
                 $('#divToBeWorkedOn').html("unavailable");
             }
         });
    }

Its local service.

A: I would replace http://localhost:xxxxx/ with the actual internal IP address of the server (probably something like http://192.168.x.x:xxxxx/) - just make sure your server and mobile device are connected to the same network through wi-fi not gsm network.
Also make sure you updated the domain white list. more info how to do that can be found here http://docs.phonegap.com/en/2.2.0/guide_whitelist_index.md.html#Domain%20Whitelist%20Guide
hope this will help, good luck!


Q: How to set react createtableselect to prevent creating element not in options? I was trying to have a create select option that limit users from adding their own option to the predefine option list, Sample code for setting options in create table select.
Unfortunately this this doesn't solve the problem. please help with a simple fix
      <CreatableSelect
        name="dataN"
        id="dataN"
        className="selctInputs"
        placeholder="Select"
        isMulti
        onChange={(e) => getData(e)}
        options={Options} />

A:     ## React createtableselect prevent creating element not in option ##
'''
import CreatableSelect from 'react-select/creatable';

 const createOption = (label, dataId) => ({
        label,
        value: dataId,
    });

    const levelOptions = ([{ "name": "Course1", "id": 1 }, { "name": "Course2", "id": 2 }, { "name": "Course3", "id": 3 }, { "name": "Course4", "id": 4 }])?.map((post, id) => {
        return createOption(post.name, post.id);
    });

        <CreatableSelect
          name="dataN"
          id="dataN"
          className="selctInputs"
          placeholder=" Select..."
          isMulti
          onChange={(e) => getData(e)}
          options={Options} />
'''

## Set isLoading to true provides a simple fix ##
'''
    <CreatableSelect
      isLoading={true}
      name="dataN"
      id="dataN"
      className="selctInputs"
      placeholder=" Select"
      isMulti
      onChange={(e) => getData(e)}
      options={Options} />

'''


Q: Sqaure brackets & asterisk sign as WildCards chars in Redis keys or scan with match We query redis using SCAN command along with MATCH, in following manner:
scan 0 MATCH "S*"

this will find anything starting with S
then there is a square brackets syntax is also supported([]) which OR
scan 0 MATCH "[ef]*"

this will find anything that's starting with e OR f
Now,
I am looking to combination of both.

*

*match anything that start with e OR f

*AND match anything that has S after e OR f
I came up with following:
scan 0 MATCH "[ef]S*"

But this just keep running without any results. is is the above correct? let me know

A: Should work as is - verified locally:
127.0.0.1:6379> FLUSHALL
OK
127.0.0.1:6379> MSET a "" e "" f "" eSz "" fSx "" efg "" fgi "" SSX ""
OK
127.0.0.1:6379> scan 0 MATCH "[ef]S*"
1) "0"
2) 1) "eSz"
   2) "fSx"
127.0.0.1:6379>


Q: Error in converting images in Imagemagick I use Imagemagick convert to convert pdf file to png as follows:
Magick convert -density 300 PointOnLine.pdf -quality 90 PointOnLine.png

It gives me the following warning:
convert: profile 'icc': 'RGB ': RGB color space not permitted on grayscale PNG `PointOnLine.png' @ warning/png.c/MagickPNGWarningHandler/1744.

And png image created is all black. However, convert to jpg image is fine.
Update: After adding -define profile:skip=ICC, image is still dark. But if convert to jpg and then to png, it is ok, but background is dark. The same warning is still there. What is the problem? Thanks.

A: The following works for me without error in ImageMagick 7.0.7.22 Q16 Mac OSX Sierra with Ghostscript 9.21 and libpng @1.6.34_0. Your PDF has an alpha channel, so you might want to flatten it.
magick -density 300 PointOnLine.pdf -flatten -quality 90 result.png

This also works without error, but leaves the alpha channel in the png, though you won't see it here until you extract the image:
magick -density 300 PointOnLine.pdf -quality 90 result2.png

Note that in IM 7 you should just use magick and not magick convert.
Check that you are using a current version of Ghostscript and libpng, if you do not get the same results.
Your delegates.xml file for PS:alpha should show sDEVICE=pngalpha rather than pnmraw as follows.
<delegate decode="ps:alpha" stealth="True" command=""gs" -sstdout=%%stderr -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 "-sDEVICE=pngalpha" -dTextAlphaBits=%u -dGraphicsAlphaBits=%u "-r%s" %s "-sOutputFile=%s" "-f%s" "-f%s""/>
USER REQUESTED RESULTING IMAGES THAT I POSTED TO BE REMOVED!

A: Command which worked for me was:
magick -density 300 PointOnLine.pdf -depth 8 -strip -background white -alpha off PointOnLine.tiff

It did not gave any warning, also removed black blackground as well.
I was able to convert it to the text afterwards using tesseract:
tesseract PointOnLine.tiff PointOnLine

A: I understand you are using ImageMagick under Windows, even if not stated (and the respective versions of IM, Win were not posted)
I am under Ubuntu 16.04 LTS, and I will provide an answer possibly useful. (Under Win, prepend everything with Magick).
For me,
convert -density 300 -quality 90 PointOnLine.pdf PointOnLine.png

works fine, with no warnings, producing a suitable output.
I tried other things which work as well, some of them may suit you.

*

*First convert your pdf to RGB and then to png.
convert -density 300 -colorspace RGB PointOnLine.pdf PointOnLine_rgb.pdf
convert -density 300 PointOnLine_rgb.pdf PointOnLine_rgb.png

A: If you post your PDF, I can check it out. Otherwise, perhaps it is CMYK, which PNG does not support. So try
magick -quiet -density 300 -colorspace srgb PointOnLine.pdf -quality 90 PointOnLine.png

Note in IM 7, use magick not magick convert. Also not that -quality is different for PNG than JPG. See https://www.imagemagick.org/script/command-line-options.php#quality

A: I had the same issue and resolved adding -colorspace RGB before the output filename.
convert -density 300 PointOnLine.pdf -quality 90 -colorspace RGB PointOnLine.png


Q: Lifetime of std::initializer_list when used recursively I am trying to use std::initializer_list in order to define and output recursive data-structures. In the example below I am dealing with a list where each element can either be an integer or another instance of this same type of list. I do this with an intermediate variant type which can either be an initializer list or an integer.
What is unclear to me is whether the lifetime of the std::initializer_list will be long enough to support this use-case or if I will be experiencing the possibility of inconsistent memory access. The code runs fine, but I worry that this is not guaranteed. My hope is that the std::initializer_list and any intermediate, temporary std::initializer_list objects used to create the top-most list are only cleaned up after the top-level expression is complete.
struct wrapped {
    bool has_list;
    int n = 0;
    std::initializer_list<wrapped> lst;

    wrapped(int n_) : has_list(false), n(n_) {}
    wrapped(std::initializer_list<wrapped> lst_) : has_list(true), lst(lst_) {}

    void output() const {
      if (!has_list) {
        std::cout << n << ' ';
      } else {
        std::cout << "[ ";
        for (auto&& x : lst)  x.output();
        std::cout << "] ";
      }
    }
  };

  void call_it(wrapped w) {
    w.output();
    std::cout << std::endl;
  }

  void call_it() {
    call_it({1});                 // [ 1 ]
    call_it({1,2, {3,4}, 5});     // [ 1 2 [ 3 4 ] 5 ]
    call_it({1,{{{{2}}}}});       // [ 1 [ [ [ [ 2 ] ] ] ] ]
  }

Is this safe, or undefined behavior?

A: As far as I can tell the program has undefined behavior.
The member declaration std::initializer_list<wrapped> lst; requires the type to be complete and hence will implicitly instantiate std::initializer_list<wrapped>.
At this point wrapped is an incomplete type. According to [res.on.functions]/2.5, if no specific exception is stated, instantiating a standard library template with an incomplete type as template argument is undefined.
I don't see any such exception in [support.initlist].
See also active LWG issue 2493.

A: What you're doing should be safe. Section 6.7.7 of the ISO Standard, paragraph 6, describes the third and last context in which temporaries are destroyed at a different point than the end of the full expression. Footnote (35) explicitly says that this applies to the initialization of an intializer_list with its underlying temporary array:

The temporary object to which the reference is bound or the temporary object that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference if the glvalue to which the reference is bound was obtained through one of the following: ...

...(where a glvalue is, per 7.2.1, an expression whose evaluation determines the identity of an object, bit-field, or function) and then enumerates the conditions. In (6.9), it specifically mentions that:

A temporary object bound to a reference parameter in a function call (7.6.1.2) persists until the completion of the full-expression containing the call.

As I read it, this protects everything needed to build up the final argument to the top call to call_it, which is what you intend.


Q: (Warning) IP address 'XXX.XXX.XX.XXX' could not be resolved: Name or service not known I Use Mariadb-10.3 at 127.0.0.1:3310. The sites are working correctly, everything is fine. But I noticed these connections in the logs:
200812 21:16:31 [Warning] IP address '195.54.167.225' could not be resolved: Name or service not known
200813  1:44:22 [Warning] IP address '177.156.63.4' has been resolved to the host name '177.156.63.4.dynamic.adsl.gvt.net.br', which resembles IPv4-address itself.
200813  3:03:27 [Warning] IP address '51.103.146.73' could not be resolved: Name or service not known
200813  3:24:40 [Warning] IP address '20.52.50.38' could not be resolved: Name or service not known
200813 15:01:29 [Note] Hostname 'worker-13.sfj.censys-scanner.com' does not resolve to '192.35.168.220'.
200813 15:01:29 [Note] Hostname 'worker-13.sfj.censys-scanner.com' has the following IP addresses:
200813 15:01:29 [Note]  - 192.35.168.208

200813 18:14:01 [Warning] IP address '170.130.187.30' could not be resolved: Name or service not known
200813 21:14:05 [Warning] IP address '64.227.86.82' could not be resolved: Name or service not known
200813 21:39:55 [Note] Hostname '186-210-095-134.xd-dynamic.algarnetsuper.com.br' does not resolve to '186.210.95.134'.
200813 21:39:55 [Note] Hostname '186-210-095-134.xd-dynamic.algarnetsuper.com.br' has the following IP addresses:
200813 21:39:55 [Note]  - 195.85.231.19

200813 23:11:43 [Warning] IP address '92.63.194.76' could not be resolved: Name or service not known
200814  1:17:00 [Warning] IP address '79.152.33.82' has been resolved to the host name '82.red-79-152-33.dynamicip.rima-tde.net', which resembles IPv4-address itself.
200814 13:18:19 [Warning] IP address '118.193.28.58' could not be resolved: Name or service not known
200814 18:47:42 [Note] Hostname '3c2e01.rederatural.com' does not resolve to '104.140.188.10'.
200814 18:47:42 [Note] Hostname '3c2e01.rederatural.com' has the following IP addresses:
200814 18:47:42 [Note]  - 212.32.237.101

200814 20:25:51 [Note] Hostname '683b217.rederatural.com' does not resolve to '104.140.188.6'.
200814 20:25:51 [Note] Hostname '683b217.rederatural.com' has the following IP addresses:
200814 20:25:51 [Note]  - 212.32.237.90

200814 22:43:46 [Note] Hostname 'zg-0708b-125.stretchoid.com' does not resolve to '192.241.238.224'.
200814 22:43:46 [Note] Hostname 'zg-0708b-125.stretchoid.com' has the following IP addresses:
200814 22:43:46 [Note]  - 178.210.89.119

200814 23:08:48 [Note] Hostname 'zg-0708a-49.stretchoid.com' does not resolve to '192.241.212.195'.
200814 23:08:48 [Note] Hostname 'zg-0708a-49.stretchoid.com' has the following IP addresses:
200814 23:08:48 [Note]  - 178.210.89.119

200814 23:40:20 [Warning] IP address '80.82.78.85' could not be resolved: Name or service not known
200815  2:01:33 [Warning] IP address '183.136.225.44' could not be resolved: Name or service not known

After that, the mysql server is disabled and i have to restart it. Can you tell me what this is? Attempted hacking or something else?
I read it somewhere and in /etc/my.cnf added skip_name_resolve = 1. Helps?

A: For each incoming connection, MariaDB is attempting to do a DNS lookup.  As you wrote in the question, adding skip-name-resolve = on to /etc/my.cnf will prevent the lookup.
The fact that you are even getting these connection attempts means your DB is exposed to the Internet.  It would be highly recommended not to allow public access to that port, e.g. limit to loopback interface and/or use the firewall to only allow whitelisted IPs.


Q: Keycloak user resource - return user representation with roles and groups instead querying rest api for roles and groups I have to search users by text, groups and roles and it takes 6 seconds to query for users, groups and roles for each user, it is about 15 HTTP requests to Keycloak REST API.
Such slow searching is not acceptable from GUI point of view.. How u search users in your projects with Keycloak ? Do you synchronize users from Keycloak? Then data would not be fresh.. or maybe it is possible to write someadapter in Keycloak to synchronize data to my application, so the changes would be reflected immediatelly in my database and I would search users in my database. .? Or maybe uconnect to Keycloak data database ? But then u limit yourself to Keycloak version..
When serching users you get UserResources and u can do userResource.toRepresentation() to get specific data an you see groups and roles collections that are always empty.
Is it possible to retrieve UserResources that have groups and roles filled? Currently userResource.toRepresentation() returns user but with null groups and roles. So what groups and roles collections are for in UserRepresentation if they are always null?

A: It's not exactly the topic but I needed to find the roles associated with a specific user and this question pops first with my keywords web search. Here's what worked for me with keycloak client 13.0.1
RealmResource realmResource = keycloak.realm(REALM);
UsersResource usersResource = realmResource.users();
UserResource userResource =  usersResource.get(USER_ID);
RoleMappingResource roleMappingResource = userResource.roles();
// either realmLevel or clientLevel
RoleScopeResource roleScopeResource = roleMappingResource.realmLevel();
List<RoleRepresentation> rolesRepresentation = roleScopeResource.listAll();

I didn't find it elsewhere, I hope it can be useful.


Q: Lower bound on a function of probability distribution Let
$$
\gamma = \frac{1}{\sum_{y}f(y)W(y)},
$$
where
$$
f(y) = 1 + e^{-|y|}
$$
and $W(y)$ is a probability distribution (unknown) with $y \in \mathcal{Y}$ arbitrary but discrete, and $x \in \{0,1\}$. I want to calculate a lower bound on $\gamma$. I came up with one lower bound as follows:
\begin{aligned}
\gamma &= \frac{1}{\sum_{y}f(y)W(y)}\\
&\ge  \frac{1}{\sum_{y}f(y)}, \because W(y) \le 1,  \forall y \in \mathcal{Y}\\
\end{aligned}
I wanted a tighter bond than this. Any ideas or references are appreciated. Thank you !

A: $1 \lt f(y) \le 2$
so  $1=\sum_{y}W(y) \lt \sum_{y}f(y)W(y) \le \sum_{y}2W(y) =2$
so $\frac12 \le \gamma \lt 1$.

A: As $$f(y) = 1 + e^{-|y|}\leq 2$$
then
$$E[f(y)]=\sum_{y} f(y)W(y)\leq \sum_{y} 2 ~W(y)=2 $$
Hence
$$\gamma = \frac{1}{\sum_{y}f(y)W(y)}\geq \frac{1}{2}$$


Q: AOSP build both x86 and x64 for aosp_x86_64-eng When building Android 9.0.0_r30, I lunch "aosp_x86_64-eng", but it builts both x86 and x64 targets, i.e. there are two clang invokes for each C/C++ source in the build log:
...clang...-target i686-linux-android...
...clang...-target x86_64-linux-android...

which generates two sets of binaries which wastes time and disk space.
Can I/how to only build x64 target?

A: You will probably not have success with building an x64 Android without any x86 binaries. Every module can decide to be built in the target architecture, a fixed one or both and a lot of modules do that.
If you start to grep for LOCAL_MULTILIB in Android.mk and compile_multilib in Android.bp, you will find lots of modules and have to figure out the reason for every one of them to build for x86, x64 or both.
grep -rn "compile_multilib" --include="Android.bp"
grep -rn "LOCAL_MULTILIB" --include="Android.mk"

You can find out what the configurations mean here: https://source.android.com/setup/develop/64-bit-builds


Q: How to redirect Woocommerce to a specific page? I use "Woocommerce User Email Verification" which after the user registers, it redirects user to the main page. It doesn't have built in option to redirect users to a page where I can tell them that they should check their email and confirm it to access my-account section!
Plugin link:
https://wordpress.org/plugins/woo-confirmation-email/
download link:
https://downloads.wordpress.org/plugin/woo-confirmation-email.3.1.15.zip
Please tell me how I can redirect a user after they press the Register to any page of my own website that I want?
Ps. I know that without this plugin, when user registers, they automatically go to my-account section. So this plugin is causing the Redirect I think.
Would you be so kind and help?
Thanks!

A: Try to add this in function.php
function wpse_registration_redirect() {
    return home_url().'/my-page' ;
}

add_filter( 'registration_redirect', 'wpse_registration_redirect' );

or
function custom_registration_redirect() {
    return home_url().'/my-page' ;
}
add_action('woocommerce_registration_redirect', 'custom_registration_redirect', 2);

or
After login
function admin_default_page() {
  return home_url().'/my-page' ;
}

add_filter('login_redirect', 'admin_default_page');

or After WooCommerce login
function iconic_login_redirect( $redirect_to) {
    $redirect_to = 'http://yoursiteshop';
   return $redirect_to ;
}

add_filter( 'woocommerce_login_redirect', 'iconic_login_redirect',1100, 2 );


Q: When you play poker in Red Dead Redemption, is the "look around" option actually useful? In Red Dead Redemption, during the poker game, you can look around at other people's faces. I assume there's a use of this option, but I wasn't able to get any hint when it may be. Does it actually have a purpose, or is it just for game immersion ?

A: Well technically it has a purpose and also adds to game immersion ;)
In all seriousness the NPC players give off tells as well as change their tones/mannerisms slightly depending on past hands and their current hands. The look around option gives you a chance to watch for those tells and play accordingly. It can also give you a better idea of when to cheat, since most of the time the other players will catch you (if you're as bad at it as I am).

A: If you look around after several hands you can tell who is bluffing and who has a good hand. You can also use it to determine if you can get away with cheating.


Q: I'm having trouble rounding decimals while encoding in python import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.preprocessing import OrdinalEncoder

df = pd.read_csv("mushrooms.csv",index_col=False,header=None)
def n(target):
   if target == 'p':
       return 1
   elif target == 'e':
       return 0

df[0] = df[0].apply(n)
#manually encoding the targets

targets = df[0]
inputs = df[df.columns[1:]]

def test_train_split(mydf, inputs, tratio, target):
   splitter = StratifiedShuffleSplit(n_splits = 1, test_size = tratio, random_state = 42)
   train_index, test_index = next(splitter.split(inputs, target))
   strat_train = mydf.iloc[train_index]
   strat_test = mydf.iloc[test_index]
   return strat_train, strat_test

def print_test_train_dfs(train_df, test_df, target_column = 'None'):
   print("\nTraining data:")
   train_df.info()
   if target_column != 'None':
       print(train_df[target_column].value_counts())
   print('\nTest data:')
   test_df.info()
   if target_column != 'None':
       print(test_df[target_column].value_counts())

traindf, testdf = test_train_split(df, inputs, 0.2, targets)

enc = OrdinalEncoder()
enc.fit(traindf)
df = enc.transform(testdf)
for i in range(len(df)):
   for j in range(len(df[1])):
       df[i][j].round(0)
df = pd.DataFrame.from_records(df)
print(df)

df always ends up with decimals like 1.0 instead of just 1 which is what I want.
The dataset I'm using is here
https://www.kaggle.com/uciml/mushroom-classification
I'll also add that after .transform, df is in more of an array than a dataframe

A: df.astype(int) should load as integer
Refer to this question for more information
Change data type of columns in Pandas


Q: Linear algebra confusion T/F TRUE or FALSE?
For any line $l$ through the origin in $R^2$, if $P:R^2\to R^2$ is an orthogonal projection onto $l$,
then $P^2=P$.
There exists a $3 × 4$ matrix $A$ of rank $2$ such that $\ker(A)$ contains the vector $v=\begin{bmatrix}1 \\1 \\ 1 \\1\end{bmatrix}$
 and $\mathrm{image}(A)$ contains the vector $w=\begin{bmatrix}1 \\ 1 \\1\end{bmatrix}$.
I'm studying for an exam and these two questions came up. For the first, I'm getting confused about what $P^2$ means. I'm trying to come up with an example matrix for the latter, but nothing is working yet.

A: I think, it would first be best to think about this intuitively.
If we project $X$ onto $L$ then we get a vector with direction $L.$  If we run our projection operation on a vector with direction L, it does nothing.
$P^2 = P$
If we get a little bit more concrete.
$PX = \frac {X\cdot L}{\|L\|^2} L\\
P^2X = P(\frac {X\cdot L}{\|L\|^2} L)\\$
$\frac {X\cdot L}{\|L\|^2}$ is a scalar and can be pulled outside
$P^2X = \frac {X\cdot L}{\|L\|^2} PL = \frac {X\cdot L}{\|L\|^2} \frac {L\cdot L}{\|L\|^2} L = \frac {X\cdot L}{\|L\|^2} L$
Taking it down one more level.
$X = (x,y), L = (a,b)\\
PX = (\frac {ax + by}{a^2+b^2} a, \frac {ax + by}{a^2+b^2} b) $
If we want a matrix representation $P = \frac {1}{a^2 + b^2}\begin{bmatrix} a^2 & ab\\ab&b^2 \end{bmatrix}$
And indeed $P^2 = P$
As for the second question
$\begin{bmatrix}
1&-1&1&-1\\
1&1&-1&-1\\
1&0&0&-1 \end{bmatrix}$
The image is spaned by, $\begin{bmatrix} 1\\1\\1 \end{bmatrix}, \begin{bmatrix} 1\\-1\\0 \end{bmatrix}$
Rank is 2
The kernel is spaned by $\begin{bmatrix} 1\\0\\0\\1 \end{bmatrix},\begin{bmatrix} 0\\1\\1\\0 \end{bmatrix}$ and $\begin{bmatrix} 1\\1\\1\\1 \end{bmatrix}$ is in the span

A: In general, if you want $\ker(A) \supseteq \operatorname{span}\{(a_1,\dots,a_n)^\top\}$ (i.e. a single vector) and $\operatorname{span}\{w_1,\dots,w_m\} \subseteq\operatorname{im}(A)$ with $m < n$. Then you can make the first $m$ columns of $A$, $w_1,\dots,w_m$ (so they are in the image) and then if $w_{m+1}, \dots, w_n$ are the remaining columns (to be chosen), they must satisfy $$A(a_1,\dots,a_n)^\top = a_1w_1 + \dots + a_nw_n = 0.$$
To arrange this, you can let $w_{m+1},\dots,w_{n-1}$ be whatever you want, and then simply set $$w_n = -\frac{1}{a_n}\left(a_1w_1 + \dots + a_{n-1}w_{n-1}\right).$$
So for your example, $A = (w,-w,0,0)$ or $A = (w,w,w,-3w)$ or $A = (w,-w,w,-w)$ are all examples with $\operatorname{rank}(A) = 1$. For rank 2, we can let $w'$ be any vector not in the span of $w$ and take $A = (w,w',-w,-w')$ or maybe $A = (w,w',0,-w - w')$.
Some questions to think about:

*

*How do we make this work if $a_n = 0$?

*How does this calculation change if we require the kernel and image to be equal to the given spans (rather than containing them). Also what does rank-nullity imply about the size of the inputs in this case?

*How do we deal with multiple vectors in the kernel. E.g. $\operatorname{im}(A) = \operatorname{span}\{w_1, w_2\}$ and $\ker(A) = \operatorname{span}\{(1,1,1,1)^\top, (1,2,3,4)^T\}$?


Q: Error: A "url" property or function must be specified, except url is specified I have a Conversation model and a view that displays this model. This model is fetched from the server without any problem (the url property works fine then), and the view is rendered.
However, when I attempt to destroy the model in a function of the view, I get the error 'A "url" property or function must be specified', even though when I display said url right before the destroy call, it is exactly the url it should be.
Here is the code for the model:
MessageManager.models.Conversation = Backbone.Model.extend({
    defaults: {
        uid: '',
        title: '',
        messages: [],
        users: [],
        dateUpdated: null,
        isNew: true,
        message: ''
    },
    url: function(){
        var url = '/api/conversations';
        if(this.get('uid').length > 0) url += '/'+this.get('uid');
        return url;
    }
});

And the view:
MessageManager.views.ConversationFull = Marionette.CompositeView.extend({
    template: this.template(MessageManager.templates.ConversationFull),
    childView: MessageManager.views.MessageListItem,
    childViewContainer: '#message-container',
    events: {
        'click a#btn-delete-conversation': 'deleteConversation'
    },
    deleteConversation: function(e){
        e.preventDefault();
        var self = this;
        console.log(self.model.url()); //This returns a correct url

        self.model.destroy({//This fires the error
            error: function(model, result, xhr){
                console.log(result.responseText);
            },
            success: function(model, response, options){
                MessageManager.conversations.sync();
                AMMain.router.pNavigate('welcome/');
            }
        });
    }
});

Can anyone give some insight on how to resolve this problem? Is there something wrong in the way I declare the model?
EDIT: It should be noted that other calls (like fetch or sync) on this model fire the same error, even though the original fetch works without a problem.
EDIT2: Well, not completely out of the frying pan yet, but I changed the way I defined the model's url, using urlRoot and the "id" attribute, and now the DELETE request is sent to the server without error.

A: It happens because you have to specify urlRoot property of the model. Without it url is not considered. So try this maybe:
MessageManager.models.Conversation = Backbone.Model.extend({
    defaults: {
        uid: '',
        title: '',
        messages: [],
        users: [],
        dateUpdated: null,
        isNew: true,
        message: ''
    },
    urlRoot: function() {
        var url = '/api/conversations';
        if (this.get('uid').length > 0) url += '/'+this.get('uid');
        return url;
    }
});

Documentation says:

urlRootmodel.urlRoot or model.urlRoot()
  Specify a urlRoot if you're using a model outside of a collection, to enable the default url function to generate URLs based on the model id. "[urlRoot]/id"
  Normally, you won't need to define this. Note that urlRoot may also be a function.

And source code for Backbone.Model url method:
url: function() {
  var base =
    _.result(this, 'urlRoot') ||
    _.result(this.collection, 'url') ||
    urlError();
  if (this.isNew()) return base;
  return base.replace(/([^\/])$/, '$1/') + encodeURIComponent(this.id);
},

A: defsq answer is good. The only thing missing is to define the idAttribute on your model, since it's not the convention-based id field, but uid.
MessageManager.models.Conversation = Backbone.Model.extend({
    idAttribute: 'uid',
    defaults: {
        uid: '',
        title: '',
        messages: [],
        users: [],
        dateUpdated: null,
        isNew: true,
        message: ''
    },
    urlRoot: "/api/conversations"
});

You don't need to append the "id" manually. Just tell Backbone that your id attribute is uid and everything else will work. In fact, you can event call mymodel.id to get the id of the model -event if it's stored internally as uid. :)
http://backbonejs.org/#Model-idAttribute
Personally I don't like all that default values. Everything will be undefined if you don't set default values, which you can simply guard against with an if (undefined is a falsey value).
if(!model.get("messages")){
   //no messages
}


Q: Handler from Looper.getMainLooper didn't receive message I have an activity and a handler created inside its onCreate function which looks like this:
private Handler mHandler;
private Button helloBtn;
private TextView helloText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(...);

    helloBtn = (Button)findViewById(R.id.hello);
    helloBtn.setOnClickListener(this);
    helloText = (TextView)findViewById(R.id.text);

    mHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case MSG_REPORT_PROGRESS:
                    int progress = msg.arg1;
                    seekBar.setProgress(progress);
                    break;
                case MSG_HELLO:
                    helloText.setText("hello world");
                    break;
            }
        }
    };
}
public void onClick(View view) {
    if(view == helloBtn)
    {
        Handler mainHanlder = new Handler(Looper.getMainLooper());
        Message msg = new Message();
        msg.what = MSG_HELLO;
        mainHandler.sendMessage(msg);
    }

}

the mainHandler didn't receive message when helloBtn been clicked. Why? it works if I directly use mHandler to replace the mainHandler, why?

A: use the below code.. and let me know the feedback. To show the text, handler is not needed.
/** The m handler. */
private Handler mHandler;

/** The hello btn. */
private Button helloBtn;

/** The hello text. */
private TextView helloText;

/** The msg hello. */
private final int MSG_HELLO = 2;

/*
 * (non-Javadoc)
 *
 * @see android.app.Activity#onCreate(android.os.Bundle)
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    helloBtn = (Button) findViewById(R.id.btn_hello);
    helloBtn.setOnClickListener(this);
    helloText = (TextView) findViewById(R.id.txt_hello);

    mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MSG_HELLO:
                helloText.setText("hello world");
                break;
            }
        }
    };
}

/*
 * (non-Javadoc)
 *
 * @see android.view.View.OnClickListener#onClick(android.view.View)
 */
public void onClick(View view) {
    if (view.getId() == R.id.btn_hello) {
        Message msg = new Message();
        msg.what = MSG_HELLO;
        mHandler.sendMessage(msg);
    }
}

A: The class Message has a field "target" which is used to store the handler that you used to send message. When you call a Handler's sendMessage(msg) method, the reference of the handler will be stored in the message. When the Looper dispatch your message it'll call msg.target.dispatchMessage(msg), which means that your msg will be dispatched to the same handler that you used to send it. The method dispatchMessage(msg) will call handleMessage(msg) eventually.
You can use a BroadcastReceiver to solve your problem. Register a BroadcastReceiver in the Activity that you want to update in the future, and send a Broadcast to it from the other part of you app.


Q: Is there way to position border with css (IMAGE EXAMPLE)? Below are a couple of examples of what I want:
Example 1:

Example 2:

I tried by using background but I don't know how to make the background smaller than its container, so I decided to try with border-bottom and to position it with sth like 10px-top.
I've tried:
background: rgba(196,196,196,0.8);
background-position: -10px 10px;

However, I cant find how to postion border... Is there some way?

A: You can use the border-image css property. More info here
DEMO

#borderimg1 {
  border: 10px solid transparent;
  padding: 15px;
  -webkit-border-image: url(https://www.w3schools.com/cssref/border.png) 30 round;
  -o-border-image: url(https://www.w3schools.com/cssref/border.png) 30 round;
  border-image: url(https://www.w3schools.com/cssref/border.png) 30 round;
}

#borderimg2 {
  border: 10px solid transparent;
  padding: 15px;
  -webkit-border-image: url(https://www.w3schools.com/cssref/border.png) 30 stretch;
  -o-border-image: url(https://www.w3schools.com/cssref/border.png) 30 stretch;
  border-image: url(https://www.w3schools.com/cssref/border.png) 30 stretch;
}

Here, the image tiles to fill the area. The image is rescaled if necessary, to avoid dividing tiles.

Here, the image is stretched to fill the area.

A: You could achieve this with :before
HTML

Lorem ipsum dolor sit amet

Amet cum et ad earum commodi

CSS
.wrap {
  padding: 50px;
  background: url(https://placedog.net/1000/500?id=12);
  background-size: cover;
}
.text {
  position: relative;
  z-index: 1;
  margin: 0 0 50px;
  font-size: 40px;
  font-family: sans-serif;
  display: inline-block;
}
.text:before {
  content: '';
  position: absolute;
  display: block;
  top: 15px;
  bottom: 15px;
  left: -20px;
  right: -20px;
  background: rgba(255,255,255,0.8);
  z-index: -1;
}

Change the values top, bottom, left, right in the :before to suit your needs.
JSFiddle:
https://jsfiddle.net/74kLwyxb/


Q: Magmi- products are assigning to new categories instead of existing categories we are using magmi to import products and also we are assigning products to categories using csv format as below :
sku::categories

sku1::Mobile Cases and Covers/Photography/Apple iPhone 4

products are uploading fine, but instead of assigning to exisitng categories, its creating new categories and assigning products to new categories.

A: If a category branch does not exist, it will be created on the fly during the import process and your products will be assigned to it. Maybe any typo in your category name. Just check once again and for more details,
http://www.blinkdata.com/magmi-on-the-fly-category-creator/


Q: Bootstrap Button Collapse in navbar While following "Bootstrap 3 Tutorials - #2 - Responsive Collapsing Navbar [1080p]", I got stuck w/ this button; https://www.youtube.com/watch?v=qpWlaOeGZ_4
When button is cliked, home link is supposed to show in mobile size of the page.
But nothing happens, can anyone help me with this ?
<!DOCTYPE html>

    <meta charset="ISO-8859-1">
    <title>Insert title here</title>

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="css/bootstrap.min.css" rel = "stylesheet">
    <link href="css/styles.css" rel="stylesheet">

            My Home

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navHeaderCollapse">Button Test</button>

Home


Q: Conditional validations in angular2 I want to use same template for guest and customer registration forms but validations may varies as follows
Let us assume it is a Register form for Guests - firstName is required
<form #f="ngForm" novalidate (ngSubmit)="save()">
                First Name:
                <input type="text" name="firstName" [(ngModel)]="values.FirstName" required #firstName="ngModel">

You must include a first name.

</form>

And this is for Customer - firstName is optional
<form #f="ngForm" novalidate (ngSubmit)="save()">
                    First Name:
                    <input type="text" name="firstName" [(ngModel)]="values.FirstName" #firstName="ngModel">

</form>

I want to use same/onlyone template for both forms but validations varies! how could i achieve it. TIA!

NOTE: by using reactive forms I could achieve it, but knowingly I want
  to achieve in Template-Driven forms.

A: Based on this topic you can try
<input name="first" ngModel [required]="isRequired">


Q: Study of a function I have this function $\displaystyle  g(s)=\frac{s^{2-\sigma}}{1+s^2}, ~\text{for all} ~s\in \mathbb{R}$ , i need to find the interval of $\sigma$ and the maximum of the function $g$.
I calculate the derivative $\displaystyle g'(s)=\frac{s^{1-\sigma}(2-\sigma(1+s^2))}{(1+s^2)^2} $
$g'(s)=0$ implies that $s^{1-\sigma}=0$ or $s^2=\frac{2-\sigma}{\sigma}$
but i canf find where is $\sigma$, for example if it is in $[0,1)$, a what is the maximum of $g$
Please help me
Thank you.

A: First note that you need $2-\sigma>0$ in order to have the function defined for all $s$. Based on your computation, you don't want the critical point at $0$ (since it won't be a maximum), so you need $\dfrac{2-\sigma}{\sigma}>0$. This means we need $0<\sigma<2$. For any such $\sigma$, you now know the critical points, so plug in and find the maximum value.

A: I don't really understand what you mean with finding the interval of $\sigma$. In general the function can have three different kinds of extrema: critical points, singular points and boundary points. Critical points are points where the derivative is equal to zero, and singular points are, in this case, points where the denominator of the function is equal to zero.
edit: Oops, I just saw the real-analysis tag. Maybe this hints that a more rigorous answer is needed.


Q: How to prove that $3ab(a+b)$ cannot be a cube? Consider the diophantine equation: $ 3ab(a+b)=c^3 $ where $a,b,c$ are non-zero integers,how do you prove that this equation has no integral solutions?

A: Edition/Revision 2.
Equation
$$
3ab(a+b) = c^3
$$
has non-zero integer solutions.
One of "obvious" solutions is
$$
(a,b,c) = (1,8,6);\tag{A}
$$
other (not so obvious) sulutions that I've found so far, are:
$$
(a,b,c) = (3087, 4913,7140) \\
\color{gray}{ = (9 \cdot 7^3, 17^3, 3 \cdot 7\cdot 17 \cdot 20)},\tag{B}
$$
$$
(a,b,c) = (756249048, 19902511, 327250386) \\
\color{gray}{ = (9 \cdot 438^3, 271^3, 3 \cdot 438 \cdot 271 \cdot 919)},\tag{C}
$$
$$
(a,b,c) = (6646883738818239, 48707103808000, 1866552387462840) \\
\color{gray}{ = (9 \cdot 90391^3, 36520^3, 3 \cdot 90391 \cdot 36520 \cdot 188479)}.\tag{D}
$$
These solutions can be represented as sum of $3$ cubes (as metacompactness noted in comments to the question):
$$
\color{gray}{a^3 + b^3 + c^3 = (a+b)^3;}\\
\color{gray}{1^3 + 8^3 + 6^3 = (1+8)^3 = 9^3;}\\
\color{gray}{3087^3 + 4913^3 + 7140^3 = (3087+4913)^3 = 8000^3;}\\
...
$$

Here I consider only solutions with co-prime $a,b$. (It is clear why).

Way to find solutions:
we'll focus on co-prime $a,b$.
If $3| c^3$, then $27| c^3$, then $9| ab(a+b)$.
$3$ cases are here:
A) $9\mid a, \quad 3\nmid b$;
A') $3\nmid a, \quad 9\mid b$; (symmetric to case A) )
B) $3\nmid a, \quad 3\nmid b, \quad 9\mid (a+b)$.
case A):

$a,b,(a+b)$ are co-prime pairwice.
So, $a,b,(a+b)$ have different prime factors.
Then every of numbers $3a, b, (a+b)$ has each prime factor in $3\times$ power.
Other words, $3a,b,(a+b)$ are co-prime cubes:
$$3a = 27 p^3,\qquad b = q^3, \qquad (a+b) = r^3.$$
Then
$$3ab(a+b) = 27p^3q^3r^3 = (3pqr)^3.$$
$$c = 3pqr.$$
Thus for searching $(a,b,c)$ one needs to consider co-prime pairs $(p,q)$, such that
$$
9p^3+q^3 = r^3.\tag{*}
$$
Triple $(p,q,r) = (7,17,20)$ generates solution $(B)$,
triple $(p,q,r) = (438,271,919)$ generates solution $(С)$,
triple $(p,q,r) = (90391,36520,188479)$ generates solution $(D)$.
case B):

Similar thinking.
$a,b,3(a+b)$ are co-prime cubes:
$$a = p^3,\qquad b = q^3, \qquad 3(a+b) = 27r^3. $$
Then
$$ab\cdot3(a+b) = 27p^3q^3r^3 = (3pqr)^3.$$
Thus for searching $(a,b,c)$ one needs to consider co-prime pairs $(p,q)$, where $3\nmid p$ and/or $3\nmid q$, such that
$$
p^3+q^3 = 9r^3.\tag{**}
$$
Triple $(p,q,r)=(1,2,1)$ generates solution $(A)$.


Q: 'Project.API.Hubs.ChatHub.OnDisconnected()': no suitable method found to override public override Task OnDisconnected()
{
    var name = dic.FirstOrDefault(x => x.Value ==    Context.ConnectionId.ToString());
    string s;
    dic.TryRemove(name.Key, out s);
    return Clients.All.disconnected(name.Key);
}

I don't know why I am getting this error.

A: They changed signature of the method in SignalR 2.1
It now looks like
 public override Task OnDisconnected(bool stopCalled)


Q: X11 Not Forwarding over SSH ($DISPLAY not getting set) I am running CentOS/RHEL 6 and having the same issues as described in the referenced question below.
I have tried all of the settings suggested in this almost identical question, but to no avail.
On the server-side I have the following sshd_config settings:

X11Forwarding yes
X11DisplayOffset 10

xauth is installed on the server, and after successfully connecting over SSH I do get a MAGIC-COOKIE in ~/.Xauthority. I do not get any xauth related errors.
When I ssh in using -X (and add verbosity for troubleshooting -vvv), I successfully connect.  When I try to run xclock it fails with an error of "Can't open display: localhost:10.0". This is a STDOUT error and not an error from the ssh -vvv.  I do NOT receive any failed X11 attempts in ssh.
Then I try to verify the $DISPLAY variable, but get no output (it's not set).
It there some other setting somewhere that sets $DISPLAY properly?  In this particular case, I can force the setting export DISPLAY=localhost:10.0, which then returns correctly after running echo $DISPLAY.  Unfortunately, I still do NOT get any X-Windows program (e.g., xlcock) to come back.  I still get the "Can't open display: localhost:10.0" error.
I'm at a loss.  Any suggestions? Anything else that can set $DISPLAY during an SSH session?

A: Have you tried using ssh -Y to connect?  It appears X11 forwarding still isn't happening and you're it attempts to run remote X programs locally instead of remotely using your local display.

A: Turns out the guidance here is correct.
However, I did run into a unique issue that may help others. I started troubleshooting with -vvv and because there was so much data, I missed a critical warning (lesson learned is to start broader (-v)).  The host key for the server changed (new build) and I disabled key checking in my ssh_config, so because it was a mismatched key X11 forwarding was disabled by SSH.

A: Maybe some options set in ~/.ssh/config prevent X forwarding from working, so temp move the file out of way:
mv ~/.ssh/config ~/.ssh/config.backup

A: X11DisplayOffset seems to cause the blockage.
X11Forwarding yes       # < You only need this one.

# X11DisplayOffset 10   # < comment it out here
# X11UseLocalhost no

Compression yes         # < helps with transmission of data```

A: For me, I had the same issue but the suggestions were already done before I installed X11.  Turns out the issue was that I forgot to log off and back on after installing X11.  Just in case anyone else had that same brain fart.

A: I met the same problem. I solved it by switching ssh client from OpenSSH to Putty. It seems that OpenSSH does not support x11 forwarding.


Q: Getting empty string on h:selectOneMenu I do not know why it is empty because I have the same piece of code in my system for a user register.
This is mu xhtml page
<!DOCTYPE html>

<ui:composition template="/template/main.xhtml">
    <ui:define name="content">

             Denunciar

            <h:form id="cadastrarDenuncia" styleClass="form-horizontal" p:role="form">

                <h:inputHidden value="#{denunciaBean.denuncia.ndenuncia}"/>

                           <h:outputLabel for="idTipoCrime" class="col-md-4 control-label">Tipo de Crime: </h:outputLabel>

                             <h:selectOneMenu class="form-control" id="idTipoCrime" value="#{denunciaBean.denuncia.tipoCrime}" required="true" requiredMessage="Campo obrigatório!">
                                <f:selectItem itemValue="" itemLabel="Selecione"/>
                                <f:selectItem itemValue="Roubo" itemLabel="Roubo"/>
                                <f:selectItem itemValue="Furto" itemLabel="Furto"/>
                                <f:selectItem itemValue="TraficoEntorpecentes" itemLabel="Tráfico de Entorpecentes"/>
                                <f:selectItem itemValue="Homicidio" itemLabel="Homicídio"/>
                                <f:selectItem itemValue="Latrocinio" itemLabel="Latrocício"/>
                                <f:selectItem itemValue="Receptacao" itemLabel="Receptação"/>
                                <f:selectItem itemValue="Estupro" itemLabel="Estupro"/>
                                <f:selectItem itemValue="Quadrilha" itemLabel="Quadrilha"/>
                                <f:selectItem itemValue="CrimeAmbiental" itemLabel="Crime Ambiental"/>
                                <f:selectItem itemValue="Sequestro" itemLabel="Sequestro"/>
                                <f:selectItem itemValue="ViolenciaDomestica" itemLabel="Violência Doméstica"/>
                                <f:selectItem itemValue="Assassinato" itemLabel="Assassinato"/>
                                <f:selectItem itemValue="Agressao" itemLabel="Agressão"/>
                                <f:selectItem itemValue="Ameaca" itemLabel="Ameaça"/>
                                <f:selectItem itemValue="Pedofilia" itemLabel="Pedofilia"/>
                             </h:selectOneMenu>

<h:message for="idTipoCrime"/>

                            <h:outputLabel class="col-md-4 control-label">Clique no local aproximado do acontecimento: </h:outputLabel>

                            <h:inputHidden id="lat" value="#{denunciaBean.denuncia.latitude}" />
                            <h:inputHidden id="lng" value="#{denunciaBean.denuncia.longitude}" />

                            <h:outputLabel class="col-md-4 control-label" for="idDataHoraCrime">Data e Hora do crime: </h:outputLabel>

                                <h:inputText id="data" label="Data e Hora do Crime" value="#{denunciaBean.denuncia.dataHoraCrime}"
                                size="16" maxlength="16" required="true">
                                    <f:convertDateTime dateStyle="long" pattern="dd/MM/yyyy HH:mm" />
                                </h:inputText>

<h:message for="idDataHoraCrime"/>

                            <h:outputLabel class="col-md-4 control-label" for="idObservacao">Observações: </h:outputLabel>

                                <h:inputTextarea class="form-control input-md" value="#{denunciaBean.denuncia.observacao}" id="idObservacao" placeholder="Observacao"/>

<h:message for="idObservacao"/>

                            <h:commandButton id="idConfirmarBt" styleClass="btn btn-primary" action="#{denunciaBean.salvar}" value="Confirmar"
                                onclick="if (!confirm('Confirmar denúncia?')) return false;"/>
                            <h:commandButton styleClass="btn btn-danger" value="Cancelar" onclick="redirecionar()"/>

            </h:form>

    </ui:define>
</ui:composition>

This is the class
package br.com.smartpatrolling.denuncia;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;

import br.com.smartpatrolling.usuario.Usuario;

@Entity
@Table(name = "denuncia")
public class Denuncia implements Serializable {

    private static final long serialVersionUID = -387555820515169694L;
    @Id
    @GeneratedValue
    private Integer ndenuncia;
    @ManyToOne
    // Permite excluir todas as denuncias do usuario ao excluir um usuário
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JoinColumn(nullable = false)
    private Usuario usuario;
    private String tipoCrime;
    /** Local do crime */
    private double latitude;
    private double longitude;
    private String observacao;
    /** Data e hora aproximados do crime */
    private Date dataHoraCrime;
    /** Data e hora do cadastro da denuncia */
    @Column(nullable = false, updatable = false)
    private Date dataHoraCadastro;

    public Integer getNdenuncia() {
        return ndenuncia;
    }

    public void setNdenuncia(Integer ndenuncia) {
        this.ndenuncia = ndenuncia;
    }

    public Usuario getUsuario() {
        return usuario;
    }

    public void setUsuario(Usuario usuario) {
        this.usuario = usuario;
    }

    public String getTipoCrime() {
        return tipoCrime;
    }

    public void setTipoCrime(String tipoCrime) {
        this.tipoCrime = tipoCrime;
    }

    public String getObservacao() {
        return observacao;
    }

    public void setObservacao(String observacao) {
        this.observacao = observacao;
    }

    public Date getDataHoraCrime() {
        return dataHoraCrime;
    }

    public void setDataHoraCrime(Date dataHoraCrime) {
        this.dataHoraCrime = dataHoraCrime;
    }

    public Date getDataHoraCadastro() {
        return dataHoraCadastro;
    }

    public void setDataHoraCadastro(Date dataHoraCadastro) {
        this.dataHoraCadastro = dataHoraCadastro;
    }

    public double getLatitude() {
        return latitude;
    }

    public void setLatitude(double latitude) {
        this.latitude = latitude;
    }

    public double getLongitude() {
        return longitude;
    }

    public void setLongitude(double longitude) {
        this.longitude = longitude;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((dataHoraCadastro == null) ? 0 : dataHoraCadastro.hashCode());
        result = prime * result + ((dataHoraCrime == null) ? 0 : dataHoraCrime.hashCode());
        long temp;
        temp = Double.doubleToLongBits(latitude);
        result = prime * result + (int) (temp ^ (temp >>> 32));
        temp = Double.doubleToLongBits(longitude);
        result = prime * result + (int) (temp ^ (temp >>> 32));
        result = prime * result + ((ndenuncia == null) ? 0 : ndenuncia.hashCode());
        result = prime * result + ((observacao == null) ? 0 : observacao.hashCode());
        result = prime * result + ((tipoCrime == null) ? 0 : tipoCrime.hashCode());
        result = prime * result + ((usuario == null) ? 0 : usuario.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Denuncia other = (Denuncia) obj;
        if (dataHoraCadastro == null) {
            if (other.dataHoraCadastro != null)
                return false;
        } else if (!dataHoraCadastro.equals(other.dataHoraCadastro))
            return false;
        if (dataHoraCrime == null) {
            if (other.dataHoraCrime != null)
                return false;
        } else if (!dataHoraCrime.equals(other.dataHoraCrime))
            return false;
        if (Double.doubleToLongBits(latitude) != Double.doubleToLongBits(other.latitude))
            return false;
        if (Double.doubleToLongBits(longitude) != Double.doubleToLongBits(other.longitude))
            return false;
        if (ndenuncia == null) {
            if (other.ndenuncia != null)
                return false;
        } else if (!ndenuncia.equals(other.ndenuncia))
            return false;
        if (observacao == null) {
            if (other.observacao != null)
                return false;
        } else if (!observacao.equals(other.observacao))
            return false;
        if (tipoCrime == null) {
            if (other.tipoCrime != null)
                return false;
        } else if (!tipoCrime.equals(other.tipoCrime))
            return false;
        if (usuario == null) {
            if (other.usuario != null)
                return false;
        } else if (!usuario.equals(other.usuario))
            return false;
        return true;
    }
}

this is the bean
package br.com.smartpatrolling.web;

import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.primefaces.event.FlowEvent;

import br.com.smartpatrolling.denuncia.Denuncia;
import br.com.smartpatrolling.denuncia.DenunciaRN;

@ManagedBean(name = "denunciaBean")
@RequestScoped
public class DenunciaBean {

    private Denuncia denuncia = new Denuncia();
    private List<Denuncia> lista = null;
    @ManagedProperty(value = "#{contextoBean}")
    private ContextoBean contextoBean;

    public String salvar() {
        this.denuncia.setUsuario(this.contextoBean.getUsuarioLogado());
        DenunciaRN denunciaRN = new DenunciaRN();
        denunciaRN.salvar(this.denuncia);
        this.denuncia = new Denuncia();
        this.lista = null;
        return "minhasDenuncias";
    }

    public String excluir() {
        DenunciaRN denunciaRN = new DenunciaRN();
        denunciaRN.excluir(this.denuncia);
        this.denuncia = new Denuncia();
        this.lista = null;
        return null;
    }

    public List<Denuncia> getLista() {
        if (this.lista == null){
            DenunciaRN denunciaRN = new DenunciaRN();
            this.lista = denunciaRN.listarDenuncias(this.contextoBean.getUsuarioLogado());
        }
        return lista;
    }

    public void onPointSelect(ActionEvent event) {
        FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_INFO, "Point Selected", "Lat:" + denuncia.getLatitude() + ", Long:" + denuncia.getLongitude()));
    }

    public void setLista(List<Denuncia> lista) {
        this.lista = lista;
    }

    public Denuncia getDenuncia() {
        return denuncia;
    }

    public void setDenuncia(Denuncia denuncia) {
        this.denuncia = denuncia;
    }

    public String onFlowProcess(FlowEvent event) {
            return event.getNewStep();
    }

    public ContextoBean getContextoBean() {
        return contextoBean;
    }

    public void setContextoBean(ContextoBean contextoBean) {
        this.contextoBean = contextoBean;
    }
}

This is my data base when i make a dennounce. tipocrime is empty
enter image description here

A: My mistake was that I was using @RequestScoped instead of @ViewScoped in my bean.


Q: WHILE loop script I am trying to write a script that will continue to prompt a user to enter a grade, until the user enters 999.
If the user enters 90 or more, echo A.  If the user enters 80 or more, echo B.  If the user enters 70 or more, echo C.  Otherwise echo Failed.
I am thinking this needs a WHILE script.  Below is my current code
#!/bin/bash
# Asuume that the first paramter is going to be a grade
if [ $# -lt 1 ];
then
    echo -n "Please  pass a a grade "
fi
gr=$1
if [ $gr -ge 90 ]
then
    echo "A"
elif [ $gr -ge 80 ]
then
    echo "B"
elif [ $gr -ge 70 ]
then
    echo "C"
else
    echo "Failed"
fi
exit 0

The script prompts me, but closes after I enter 1 grade.
Thanks in advance

A: That's not a prompt, it's just a message.
Prompting would be:
read -p "Please pass a grade: " gr

But this get's into conflict with your following gr=$1, so put this into an else block:
if [ $# -lt 1 ]
then
    read -p "Please pass a grade: " gr
else
    gr=$1
fi

Note that you don't need a semicolon at the line end; it's the line break, which can be substituted by the semicolon.
And you don't need an exit to end a script, if you don't want to exit prematurely.

A: As you want to prompt the user to input grades until he enters 999, you should use read instead of command line arguments. As bash doesn't have a do-while loop, we can emulate it's behavior using while as shown below:
#!/bin/bash
read -p "Please  pass a grade " gr
while [ $gr -ne 999 ]; do
        if [ $gr -ge 90 ]
        then
            echo "A"
        elif [ $gr -ge 80 ]
        then
            echo "B"
        elif [ $gr -ge 70 ]
        then
            echo "C"
        else
            echo "Failed"
        fi
        read -p "Please  pass a grade " gr
done
exit 0

A: Please try below code.
 while  true
     do
       read -p "Please  pass a grade:" gr
       if [ ${gr} -eq 999 ]
          then
              exit 0
       elif [ ${gr} -ge 90 ]
          then
            echo "A"
       elif [ ${gr} -ge 80 ]
            then
                echo "B"
       elif [ ${gr} -ge 70 ]
           then
                echo "C"
            else
                echo "Failed"
       fi
    done


Q: String concatenation of algebric term I would like to add two integers and concatenate their result to a string, that is:
Add 1 to $i, and concatenate that result to the string 'icon'. I thought the following syntax would work:
$x = 'icon'.$i+1;

However it doesn't do what I want - it keeps returning the value 'icon1', disregarding the value of $i.
What's the right way to do what I want?

A: Try with:
$i = 0; // init $i
$x = 'icon'.($i+1);

If you want to regularly increment $i variable:
$x = 'icon'.(++$i);

A: try this :
$temp = $i+1;
$x = 'icon'.$temp;

You are getting wrong answer because of "Operator Precedence",
Ref this link : http://php.net/manual/en/language.operators.precedence.php
Here see the line : left   + - .   arithmetic and string
. has more Precedence than +, So your expression will be like : $x = ('icon'.$i)+1;
To solve it either use the method i mentioned above or hsz answer
ie : $x = 'icon'.($i+1);

A: Operator Precedence explains why this is happening.
You can use brackets:
$x = 'icon'.($i+1);

This should do the job.
My test:
$i = 18;
$x = 'icon'.($i+1);
var_dump($x);

--> string(6) "icon19"


Q: Querying data from data extension using SOAP I am trying to extract the data in one of my data extensions. The data extension currently has one field which is the client ID.
I am using the SOAP api and following the guide located here:
https://developer.salesforce.com/docs/atlas.en-us.mc-apis.meta/mc-apis/retrieving_data_from_a_data_extension.htm
I am writing a java application and and sending the soap envelope from there. This is what I have at the moment:
    public static void main(String[] args) throws IOException, SOAPException {
    try {
        String URL = "https://@@@@@@@@@@@.soap.marketingcloudapis.com/Service.asmx";
        java.net.URL obj = new URL(URL);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type","application/soap+xml; charset=utf-8");
        String XML = "<soapenv:Envelope xmlns:soapenv=\\\"http://schemas.xmlsoap.org/soap/envelope/\\\" xmlns:xsd=\\\"http://www.w3.org/2001/XMLSchema\\\" xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\">\n" +
                " <soapenv:Header>\n" +
                " <wsse:Security soapenv:mustUnderstand=\\\"1\\\" xmlns:wsse=\\\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\\\">\n" +
                " <wsse:UsernameToken wsu:Id=\\\"UsernameToken-24440876\\\" xmlns:wsu=\\\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\\\">\n" +
                " <wsse:Username>@@@@@@@</wsse:Username>\n" +
                " <wsse:Password Type=\\\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\\\">@@@@@@@@@</wsse:Password>\n" +
                " </wsse:UsernameToken>\n" +
                " </wsse:Security>\n" +
                " </soapenv:Header>\n" +
                " <soapenv:Body>\n" +
                " <RetrieveRequestMsg xmlns=\\\"http://exacttarget.com/wsdl/partnerAPI\\\">\n" +
                " <RetrieveRequest>\n" +
                " <ObjectType>SMS_Unsub_Report</ObjectType>\n" +
                " <Properties>Client_id__c</Properties>\n" +
                " <Filter xsi:type=\\\"SimpleFilterPart\\\">\n" +
                " </RetrieveRequest>\n" +
                " </RetrieveRequestMsg>\n" +
                " </soapenv:Body>\n" +
                "</soapenv:Envelope>";
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(XML);
        wr.flush();
        wr.close();
        String responseStatus = con.getResponseMessage();
        System.out.println(responseStatus);
        BufferedReader in = new BufferedReader(new InputStreamReader(
                con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        System.out.println("response:" + response.toString());
    } catch (Exception e) {
        System.out.println("caught excepion");
        e.printStackTrace();
    }
}

I am currently getting a Bad Request along with a response code of 400 as the response. Not sure why.
I have got the wsdl from the settings and generated the java classes from it using wsimport but not sure how to use them either.
ErrorMessage:
java.io.IOException: Server returned HTTP response code: 400 for URL: https://@@@@@@@@@@@.soap.marketingcloudapis.com/Service.asmx
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at sun.net.www.protocol.http.HttpURLConnection$10.run(HttpURLConnection.java:1944)
at sun.net.www.protocol.http.HttpURLConnection$10.run(HttpURLConnection.java:1939)
at java.security.AccessController.doPrivileged(Native Method)
at sun.net.www.protocol.http.HttpURLConnection.getChainedException(HttpURLConnection.java:1938)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1508)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:263)


Q: distributed associative domains in Chapel Are there any working examples of distributed domain maps for associative and/or opaque domains in Chapel, or any hints on how one would distribute a non-rectangular structure such as a graph over multiple locales? I know about distributed sparse arrays, but I am looking at less structured data. The documentation mentions a prototype domain map for associative domains -- is it available anywhere to experiment with? Thank you.

A: Yes, these distributed associative domains are new in 1.19 (which as of this writing will be released soon, but you can try them out using a master branch before then). The documentation for them here has an example:
https://chapel-lang.org/docs/master/modules/dists/HashedDist.html


Q: How to download files from a FTP using PhantomJS I have a file on a FTP Server. I´m trying to download it using PhantomJS. I´ve tried using the following code:
var page = require('webpage').create();

page.open('ftp://USERNAME:PASSWORD@www.mywebsite.com/exempleFIle.xlsx');
phantom.exit();

It runs without throwing any errors, however the file is not downloaded. Is it possible to download it with PhantomJS?
My main goal is synchronizing the files in the FTP with my computer, so I can put it in my Google Drive and from there using it in my reports. I use PhantomJS to access some webpages and get some data for the same purpose. Since I´m already using PhantomJS, I thought I could do the same for the ftp server, but if there is a simpler solution that use other methods, I´m open to trying it.
Thank You

A: PhantomJS is a headless web-browser, it's not an FTP client, so it won't be able to help you.

My main goal is synchronizing the files in the FTP with my computer

I'd suggest using lftp.
lftp -u user,password -e 'mirror /remote/server/files/ /local/computer/files/' ftp.myserver.com
This will get files from the remote server to the local computer.


Q: Symfony 3 - Form with OneToMany association in database I work on a OneToMany association in my database. This association work perfectly when I try to add data from fixtures and when I try to return data from database.
The problem is with my FormType CommandType which does'nt work. Symfony and Doctrine return this error message :

An exception occurred while executing 'INSERT INTO command_product (quantity, command_id, product_id) VALUES (?, ?, ?)' with params [3, null, 1]:\n\nSQLSTATE[23000]: Integrity constraint violation: 1048 Column 'command_id' cannot be null

CommandType's code :
class CommandType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('establishment', EntityType::class, array(
                'class' => Company::class,
                'required' => true
            ))
            ->add('dateCreation', DateTimeType::class, array(
                'widget' => 'single_text',
                'format' => 'yyyy-MM-dd',
                'required' => true
            ))
            ->add('contains', CollectionType::class, array(
                'entry_type' => CommandProductType::class,
                'required' => true,
                'allow_add' => true
            ))
            ->add('state',TextType::class, array(
                'required' => true
            ))
            ->add('totalAmount', MoneyType::class, array(
                'required' => true
            ));
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => Command::class
        ));
    }

    public function getBlockPrefix()
    {
        return 'appbundle_command';
    }
}

CommandProductType's code :
class CommandProductType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('quantity', NumberType::class, array(
                'required' => true
            ))
            ->add('product', EntityType::class, array(
                'class'    => Product::class,
                'required' => true
            ));
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => CommandProduct::class
        ));
    }

    public function getBlockPrefix()
    {
        return 'appbundle_commandproduct';
    }
}

Command's code class :
class Command
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var Company $establishment
     *
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Company")
     * @ORM\JoinColumn(name="establishment_id", referencedColumnName="id", nullable=false)
     */
    private $establishment;

    /**
     * @var DateTime $dateCreation
     *
     * @ORM\Column(name="dateCreation", type="datetime", nullable=false)
     * @Assert\Type("datetime")
     */
    private $dateCreation;

    /**
     * @var string $state
     *
     * @ORM\Column(name="state", type="string", length=255, nullable=false)
     * @Assert\Type("string")
     */
    private $state;

    /**
     * @var float $totalAmount
     *
     * @ORM\Column(name="totalAmount", type="float", precision=10, scale=2, nullable=false)
     * @Assert\NotBlank()
     * @Assert\Type(type="float")
     */
    private $totalAmount;

    /**
     * @var mixed $contains
     *
     * @ORM\OneToMany(targetEntity="AppBundle\Entity\CommandProduct", mappedBy="contain", cascade={"persist", "remove"})
     */
    private $contains;

    public function __construct()
    {
        $this->contains = new ArrayCollection();
    }

    /**
     * @var CommandProduct $commandProduct
     */
    public function addContain(CommandProduct $commandProduct = null)
    {
        $commandProduct->setContain($this);

        $this->contains->add($commandProduct);
    }

    /**
     * @param CommandProduct $commandProduct
     */
    public function removeContain(CommandProduct $commandProduct)
    {
        if ($this->contains->contains($commandProduct)) {
            $this->contains->removeElement($commandProduct);
        }
    }
}

CommandOrder's code class :
class CommandProduct
{
    /**
     * @var int $id
     *
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @var Command $contain
     *
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Command", inversedBy="contains")
     * @ORM\JoinColumn(name="command_id", referencedColumnName="id", nullable=false)
     */
    private $contain;

    /**
     * @var int $quantity
     *
     * @ORM\Column(name="quantity", type="integer", nullable=true, options={"default": 1})
     * @Assert\NotBlank()
     * @Assert\Type(type="int")
     */
    private $quantity;

    /**
     * @var Product $product
     *
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Product")
     * @ORM\JoinColumn(name="product_id", referencedColumnName="id")
     */
    private $product;
}


Q: Signalr: firsttime user, cannot get 'server button event' to 'hub' to 'client' to work hey guys I am trying out siqnalr for the first time and am having some issues getting it to work.
I can get the client to call the hub method with no issues.
I can get the hub to call the client with no issues.
But I want to call the hub from my server side button click event so I can update the client with processing info but no matter what I try I cannot get it to work.
does anyone have any ideas?
I am probably missing some thing simple but I have no idea what is wrong.
here is my code:
Global.asax
protected void Application_Start(object sender, EventArgs e)
    {
        RouteTable.Routes.MapHubs();
    }

TestHub.cs
  using System;
  using System.Linq;
  using Microsoft.AspNet.SignalR;

    namespace Hubs
    {

        ///
        /// Summary description for TestHub
        ///
        public class TestHub : Hub
        {

            public void Send(string name, string message)
            {
                // Call the broadcastMessage method to update clients.
                Clients.Caller.broadcastMessage(name, message);
            }

            internal static void Send2(string name, string message)
            {

                //test 1
                IHubContext context = GlobalHost.ConnectionManager.GetHubContext<TestHub>();
                context.Clients.All.Send(name, message);

                //test 2
                IHubContext context2 = GlobalHost.ConnectionManager.GetHubContext<TestHub>();
                context2.Clients.All.broadcastMessage(name, message);

            }

        }

    }

default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="Signalr2._default" %>

<!DOCTYPE html>

<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>

    <title></title>

    <form id="form1" runat="server">

        <telerik:RadScriptManager ID="RadScriptManager1" Runat="server">

        </telerik:RadScriptManager>

        <telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">

        </telerik:RadScriptBlock>

        <asp:Button ID="Button1" runat="server" Text="Server To Client Test" OnClick="Button1_Click" />

    </form>

default.aspx.cs
using System;
using System.Linq;
using Hubs;
using Microsoft.AspNet.SignalR;

namespace Signalr2
{
    public partial class _default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {

            //test 1
            IHubContext context = GlobalHost.ConnectionManager.GetHubContext<TestHub>();
            context.Clients.All.broadcastMessage("Now", DateTime.Now.ToString());

            //test 2
            IHubContext context2 = GlobalHost.ConnectionManager.GetHubContext<TestHub>();
            context2.Clients.All.Send("Now", DateTime.Now.ToString());

            //test 3
            TestHub.Send2("Now", DateTime.Now.ToString());

            string test = "";

        }
    }
}

A: Methods on hubs to be called from clients need to be public- try switching from Internal to Public for Send2-


Q: Returning Video file to a view on laravel 5.4 I am encountering a problem rendering video to my view in Laravel 5.4.
I have a view as follows:

    @if(!empty($video))
      <video id="my-video" class="video-js vjs-big-play-centered" controls data-setup="{}">
      <source src="{{url('video/'.$token.'/'.$video)}}" type="{{$video_mime_type}}">

          Please upgrade your browser.

        </video>
        @else

 Lesson video is unavailable!!!

        @endif

The route for getting the video content is as follows:
Route::get('video/{token}/{video}','ResourceController@show_video');

And the ResourceController class is as shown below:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Storage;
use Response;
use File;
use GuzzleHttp\Mimetypes;
use App\Mime;

class ResourceController extends Controller
{

 public function __construct()
{
   $this->middleware('auth')->only('show_video');
}
........
........
public function show_video($token,$filename)
{
    $token=\App\VideoPermission::where('token',$token)->first();
    if(!empty($token))
    {
    $token->delete();
    $mime_type=Mime::from_extension($filename);
    return response()->file(storage_path('app/lesson-files/'.$filename),[
        'Content-Type' => $mime_type,
        'Content-Disposition' => 'inline; filename="Lesson-file"'
        ]);
    }
    return false;
  }
}

When I play it on laptop browser, it plays well as expected but when I try to play the same video on a mobile phone browser (same Chrome browser on both situations), it throws the following exception:

UnexpectedValueException: The Response content must be a string or object implementing __toString(), "boolean" given. in /home/username/domainname.com/vendor/symfony/http-foundation/Response.php:409

Please could anyone help me figure out the source of the issue.
Thank you

A: I have later discovered that the problem is a result of an 'if' condition in the method that returns the file content. So, when the condition is not met for any reason, it returns 'false' as a response instead of the video file therefore resulting in the boolean response I receive.
That is the way the code is written to function when the required token is missing as shown below
if(!empty($token))
{
$token->delete();
$mime_type=Mime::from_extension($filename);
return response()->file(storage_path('app/lesson-files/'.$filename),[
    'Content-Type' => $mime_type,
    'Content-Disposition' => 'inline; filename="Lesson-file"'
    ]);
}
return false;

}
I later discovered that this happens when the user tries to access the application with an outdated browser which does not fulfill one of the conditions expected to return the video content.
In other words, the system is actually working as intended.
Thank you to all who tried to assist in one way or the other. I appreciate you all.


Q: Writing a database analysis document I've been tasked with writing an analysis of a database that is currently used on a small scale. The intent of the document is to show to the business (as well as technically) that the database can scale to support other business divisions. I've struggled to find any database documentation standards on the web. It seems as though most databases are not documented; let alone have a basic ER diagram.
I'm more specifically concerned with the technical side and this is the outline I've come up with:

*

*Non-functional Requirements

*

*Storage needs

*Server reliability

*Schema Design & Normalization

*

*Relational Integrity

*Domain Integrity

*

*Data types

*(FOREIGN KEY, DEFAULT, NOT NULL constraints)

*Referential Integrity

*

*Parent/child references

*Query Design

Is there any aspects that I'm missing or should focus more on?

A: I would actually verify how it scales up: set up a test environment, expose to to the workload you are expecting, and see what happens. That done, describing your tests would be easy.
If you skip this essential step, your write-up might look good on paper and be completely useless.


Q: How to show the custom user control(s) in flow layout panel dragging and at the same with a move icon mouse cursor in Winform in c#? How to show the custom user control(s) in flow layout panel dragging and at the same with a move icon mouse cursor in Winforms in c#?
I have been working on a Winforms Application and is using drag and drop functionality. I have the drag and drop functionality working, but need to make it more intuitive and user friendly.
Part of this will involve actually showing the item being dragged, preferably semi-transparent when dragging and also considered with the mouse down location at the item. What is the easiest way to do this?
The items I am dragging are custom user control(s) with text, pictures, data auto-created and in flow layout panel,but I am not even sure where to look for how to do this.
I added my code worked here :
A)   In the main form :
public main_form()
    {
        InitializeComponent();
        flowLayoutPanel1.AllowDrop = true;
        flowLayoutPanel1.DragDrop += new DragEventHandler(this.flowLayoutPanel1_DragDrop);
        flowLayoutPanel1.DragEnter += new DragEventHandler(this.flowLayoutPanel1_DragEnter);
        foreach (uploaded_items c in flowLayoutPanel1.Controls)
            c.MouseDown += new MouseEventHandler(c_MouseDown);
    }

    private void c_MouseDown(object sender, MouseEventArgs e)
    {
        uploaded_items data=new uploaded_items();
        foreach (uploaded_items c in flowLayoutPanel1.Controls)
        {
              if (c._isDragging == true) data = c;
        }
        Bitmap bmp = new Bitmap(data.Size.Width, data.Size.Height);
        data.DrawToBitmap(bmp, new Rectangle(Point.Empty, bmp.Size));
        bmp.MakeTransparent(Color.White);
        Cursor cur = new Cursor(bmp.GetHicon());
        Cursor.Current = cur;
    }

    private void flowLayoutPanel1_DragEnter(object sender, DragEventArgs e)
    {
        e.Effect = DragDropEffects.Move;
    }

    private void flowLayoutPanel1_DragDrop(object sender, DragEventArgs e)
    {
        uploaded_items data = (uploaded_items)e.Data.GetData(typeof(uploaded_items));
        FlowLayoutPanel _destination = (FlowLayoutPanel)sender;
        Point p = _destination.PointToClient(new Point(e.X, e.Y));
        var item = _destination.GetChildAtPoint(p);
        int index = _destination.Controls.GetChildIndex(item, false);
        _destination.Controls.SetChildIndex(data, index);
        _destination.Invalidate();

    }

B) In the user control :
public partial class uploaded_items : UserControl
{
    public uploaded_items()
    {
        InitializeComponent();
        AllowDrag = true;
    }

    public bool AllowDrag { get; set; }
    public bool _isDragging = false;
    private int _DDradius = 4;  //the min distance the mouse req to dragged so that drag action would be taken
    private int _mX = 0;        //positon on mouse down
    private int _mY = 0;

    protected override void OnGotFocus(EventArgs e)
    {
        this.BackColor = Color.SandyBrown;
        base.OnGotFocus(e);
    }

    protected override void OnLostFocus(EventArgs e)
    {
        this.BackColor = Color.Transparent;
        base.OnLostFocus(e);
    }

    protected override void OnClick(EventArgs e)
    {
        this.Focus();
        base.OnClick(e);
    }

    protected override void OnMouseDown(MouseEventArgs e)
    {
        this.Focus();
        base.OnMouseDown(e);
        _mX = e.X;
        _mY = e.Y;
        this._isDragging = false;
    }

    protected override void OnMouseMove(MouseEventArgs e)
    {
        if (!_isDragging)
        {
            // This is a check to see if the mouse is moving while pressed.
            // Without this, the DragDrop is fired directly when the control is clicked, now I have to drag a few pixels first.
            if (e.Button == MouseButtons.Left && _DDradius > 0 && this.AllowDrag)
            {
                int dist_x_dragged = e.X - _mX ;
                int dist_y_dragged = e.Y - _mY ;
                if (((dist_x_dragged ^ 2) + (dist_y_dragged ^ 2)) > _DDradius)
                {
                    DoDragDrop(this, DragDropEffects.All);
                    _isDragging = true;
                    return;
                }
            }
            base.OnMouseMove(e);
        }
    }

    protected override void OnMouseUp (MouseEventArgs e)
    {
        _isDragging = false;
        base.OnMouseUp(e);
    }

    #region Properties
    private string _title;
    private string _msg;
    private Image _icon;
    [Category("Custom Props")]
    public string title
    {
        get { return _title; }
        set { _title = value; lbl_title.Text = value; }
    }
    [Category("Custom Props")]
    public string msg
    {
        get { return _msg; }
        set { _msg = value; lbl_msg.Text = value; }
    }
    [Category("Custom Props")]
    public Image icon
    {
        get { return _icon; }
        set { _icon = value; pictureBox1.Image = value; }
    }
    #endregion
}

The primary drag and drop function is ok,
but I found I could not show the control / picture of the control dragging in this scheme:

*

*Limited area covered:
the bmp only appears when it's mouse down and dragged "carefully" on the user control, and it's only limited on the user control but not the text/ picture on the user control or the flow layout panel

*When I try to drag, the bmp disappeared

*the bmp is centered at mouse instantaneous location, but I wish it situated at the location at which the mouse initially down on the user control


Q: How to get output of a php file in separate html form at the middle of screen of lesser size How to get output of a php file in separate html form at the middle of screen of lesser size. See tyhe below part. It is not working. Help pl.

  <form>

   </form>

    <form id = "qform" name="qform" action="getques.php" style="visibility:hidden"
      method="post" target="_blank">
   <input type="text" name="subnm1" >

   <input type="text" name="chpno1" >

   <input type="text" name="qnumber1" >

   <input type="submit">
   </form>

The above code is opening a new window but i want the size of that window not full screen but less. How to do that?

A: If I understand your question then, The easiest way would be to open create a page which takes all these parameter as query string. You can then open the new page in the window by making it a hyperlink. The new page can also process your input by taking all these parameter from query string.

Submit


Q: LCC-- How to stop debugger from breaking at the start of the application? I'm not sure of how many users there are out there that use the LCC C compiler and the WEdit GUI for Windows but it has a "feature" that is can get to be quite annoying.  When you start an application with the debugger, it breaks the application at the start of the Main function.  How can I cut this off so that the debugger immediately executes the code until I halt it or it hits a break point that I've created?

A: Wow, people still use LCC... Last time I used it was ~10 years ago.
I decompiled wedit.exe and can confirm there is no official way to disable this behavior.
I patched the binary if that works for you. I uploaded it here.
To those who concerned about viruses and such I patched wedit taken from here. About box says it's version 4.0 compiled at Sep 16 2009.
Here is patched function to those who interested:
int __cdecl sub_44CF0D(HANDLE hProcess)
{
  int result; // eax@1
  int v2; // ST0C_4@10
  int v3; // eax@20
  int v4; // eax@23
  int v5; // eax@25
  int v6; // [sp+10h] [bp-68h]@11
  int v7; // [sp+14h] [bp-64h]@1
  struct _DEBUG_EVENT DebugEvent; // [sp+18h] [bp-60h]@1

  v7 = 1;
  result = WaitForDebugEvent(&DebugEvent, dwMilliseconds);
  if ( result )
  {
    sub_44C67A(&DebugEvent);
    if ( DebugEvent.dwDebugEventCode == 1 )
    {
      if ( DebugEvent.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_ACCESS_VIOLATION
        && !(dword_482860 & 1)
        && !dword_484328
        && DebugEvent.u.Exception.dwFirstChance )
      {
        sub_44E1A5(0);
        sub_44CEB2(v2);
        return ContinueDebugEvent(DebugEvent.dwProcessId, DebugEvent.dwThreadId, 0x80010001u);
      }
      v6 = 0;
      v7 = sub_44D2C4((int)&DebugEvent, hProcess, (int)&v6);
      if ( v6 && DebugEvent.u.Exception.dwFirstChance )
        return ContinueDebugEvent(DebugEvent.dwProcessId, DebugEvent.dwThreadId, 0x80010001u);
      goto LABEL_41;
    }
    if ( DebugEvent.dwDebugEventCode == 3 )
    {
      if ( dword_483C94 )
      {
        dword_48428C = 1;
LABEL_41:
        if ( dword_483C6C )
          sub_44ECDC();
        if ( v7 )
        {
          result = ContinueDebugEvent(DebugEvent.dwProcessId, DebugEvent.dwThreadId, 0x10002u);
        }
        else
        {
          dword_49BF68 = 1;
          ResetEvent(dword_484AE4);
          dword_4843C8 = DebugEvent.dwThreadId;
          result = sub_4524CD();
        }
        return result;
      }
      Sleep(0x32u);
      dword_49BF64 = 1;
      dword_49BF68 = 1;
      qword_483C74 = __PAIR__(
                       (unsigned int)DebugEvent.u.Exception.ExceptionRecord.ExceptionAddress,
                       DebugEvent.u.Exception.ExceptionRecord.ExceptionInformation[2]);
      if ( dword_484288 )
        ::hProcess = (HANDLE)DebugEvent.u.Exception.ExceptionRecord.ExceptionFlags;
      else
        ::hProcess = hProcess;
      dword_483C84 = DebugEvent.dwProcessId;
      hThread = DebugEvent.u.Exception.ExceptionRecord.ExceptionRecord;
      dword_483C9C = (HANDLE)DebugEvent.u.Exception.ExceptionRecord.ExceptionCode;
      dwThreadId = DebugEvent.dwThreadId;
      dword_483C94 = 0;
      if ( sub_45A83A() )
      {
        v4 = sub_4026A6(28);
        dword_484330 = v4;
        *(_DWORD *)(v4 + 4) = hThread;
        *(_DWORD *)(v4 + 8) = dwThreadId;
        if ( dword_484288 )
        {
          sub_455B58();
        }
        else
        {
          Sleep(0x64u);
          v5 = sub_45AAFC();
          if ( !v5 )
            return PostMessageA(dword_4849EC, 0x111u, 0x64u, 0);
          if ( dword_484354 )
            goto LABEL_50;
          sub_455B58();
          if ( dword_483C70 && *(_DWORD *)(dword_483C70 + 52) )
            *(_DWORD *)(*(_DWORD *)(dword_483C70 + 52) + 36) = sub_451577(**(_DWORD **)(dword_483C70 + 52), 1u);
          v5 = *(_DWORD *)(dword_483C70 + 52);
          if ( v5 && *(_DWORD *)(v5 + 36) )
          {
LABEL_50:
            if ( !dword_483C6C )
              sub_44E92A(v5);
            sub_44CC3D();
            sub_451600();
            PostMessageA(dword_4849EC, 0x111u, 0x154u, 0);
          }
          else
          {
            sub_4029CA("Imposible to find %s\nRunning without source display", *(_DWORD *)(dword_483C70 + 20));
            dword_484344 = 1;
            v7 = 1;
            PostMessageA(dword_4849EC, 0x111u, 0x154u, 0);
          }
        }
        goto LABEL_41;
      }
      dword_484338 = 1;
      v3 = sub_44DB56(qword_483C74);
      if ( v3 )
        *(_BYTE *)(v3 + 29) &= 0xFDu;
      result = ContinueDebugEvent(DebugEvent.dwProcessId, DebugEvent.dwThreadId, 0x10002u);
    }
    else
    {
      if ( DebugEvent.dwDebugEventCode != 5 )
        goto LABEL_41;
      if ( DebugEvent.dwProcessId != dword_483C84 )
      {
        v7 = 1;
        goto LABEL_41;
      }
      dword_49BF64 = 0;
      dword_49BF68 = 1;
      dword_481614 = 0;
      result = sub_402A32(4520, SLOBYTE(DebugEvent.u.Exception.ExceptionRecord.ExceptionCode));
      if ( !dword_483C6C )
        result = sub_40B155(lpCmdLine);
    }
  }
  else
  {
    if ( dword_483C6C )
      result = sub_44ECDC();
  }
  return result;
}

if under LABEL_50 is what I patched (from 0x75 to 0xEB).
It was easy to spot the place because I expected WriteProcessMemory to be used to write 0xCC at entry-point of application that is being debugged.


Q: SCNShadable protocol gives internal error during fragment function compilation on newer devices We have written a shader modifier based on the SCNShadable protocol which works well until the number of uniform variables is rather slow (say 5-10). Later we needed to extend the shader modifier and use new uniforms, a total number of 25, including 8 textures and corresponding float4x4 matrices. Then it stopped working, could not compile the fragment function, which gave the following useless error message:
Error Domain=AGXMetalA12 Code=3 "Internal error during fragment function compilation" UserInfo={NSLocalizedDescription=Internal error during fragment function compilation}

When we reduced the number of float4x4 matrices to 2, it started to work again on an iPhone 7 and other Metal GPU Family 3 devices, but not on Metal GPU Family 4 or newer devices.
Our question is if someone knows any limitations that explain this kind of behaviour.