text:
Q: Cant download qt-components-ubuntu on my machine
Possible Duplicate:
How do I install the QML toolkit on 12.04?

I was trying to get some hands on ubuntu mobile app development and followed the instructions of downloading the qt5-beta. But I was not able to get following components to get installed on my ubuntu 12.04 machine. Am i missing anything on my apt-get? Seems the package hosting server is not available for the below packages.
On apt-get update :
Failed to fetch http://ppa.launchpad.net/ui-toolkit/ppa/ubuntu/dists/precise/main/binary-i386/Packages  404  Not Found
On trying to install from different packages
E: Unable to locate package qt-components-ubuntu
E: Unable to locate package qt-components-ubuntu-demos
E: Unable to locate package qt-components-ubuntu-examples
E: Unable to locate package qt-components-ubuntu-doc
E: Unable to locate package notepad-qml
Appreciate your help in resolving this.
Thanks.

A: That's because these packages are compiled for quantal (12.10), not for precise (12.04).


text:
Q: Getting "(Unsupported) RunInstances operation, when trying to create AWS instances using boto3/python3 When trying to create AWS instances using boto3/python3, i get the following error.
botocore.exceptions.ClientError: An error occurred (Unsupported) when calling the RunInstances operation: The requested configuration is currently not supported. Please check the documentation for supported configurations."

I can list already running instances, see code below
I get the same error, when i run the "ec2.create_instances" from ipython3, same error when removing the KeyName and InstanceType. There is no problem in creating instances from the web interface.
import boto3
ec2 = boto3.resource('ec2')

def list_instances():
 for instance in ec2.instances.all():
    #print (instance.tags)
    for tag in instance.tags:
           print(tag['Value'])

def create_instance():
    ec2.create_instances(
        ImageId='ami-00ee68f73a01ff18d',
        MinCount=1,
        MaxCount=1,
        KeyName='FPCcompute',
        InstanceType='t2.micro')

list_instances()
create_instance()
list_instances()

I would expect it to create an instance for me, but i just get this error that does not really give any good pointers to what is wrong. I can list the currently running instances, so that indicates to me that my credentials are set up correctly
Golden Compute Node
Master Node
Fryns

Traceback (most recent call last):
  File "/tmp/pycharm_project_343/venv/manage_instance.py", line 19, in <module>
    create_instance()
  File "/tmp/pycharm_project_343/venv/manage_instance.py", line 15, in create_instance
    KeyName='FPCcompute')#,
  File "/usr/local/lib/python3.6/dist-packages/boto3/resources/factory.py", line 520, in do_action
    response = action(self, *args, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/boto3/resources/action.py", line 83, in __call__
    response = getattr(parent.meta.client, operation_name)(**params)
  File "/usr/local/lib/python3.6/dist-packages/botocore/client.py", line 357, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/usr/local/lib/python3.6/dist-packages/botocore/client.py", line 661, in _make_api_call
    raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (Unsupported) when calling the RunInstances operation: The requested configuration is currently not supported. Please check the documentation for supported configurations.

A: Check if, for example,  VPC the instances are supposed to be launched into supports the instance type.
Boto3 assumes some parameters if not explicitly provided, so it may be VPC settings, AZ, region or other resource configuration limitations which can affect this launch. Try specifying all of these explicitly identical to settings you use in web console (see boto3 doc)

A: Thank you,
turns out that the problem was me trying to request a t2.micro instance, but that instance type might not exist in eu-north-1. When i changed the requested type to t3.micro i can now launch the machines

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP sessions and checking against SID i developed a php application where users login and a singleton "controller" instance contains all of the user data like their options, permissions and so on. This controller is stored in session and will be always the same every page they change.
Now, i don't really use the SID so if the same user logs in from another pc, he will be able to have two sessions open at the same time, each one with its own SID and independent controllers.
What's the standard way to manage SID? Should i attach to each user their "active SID" in the database and checking against it every time they change page?
This way if they would log from another session they would have "session expired" error in the first one.
I'm using secure and https PHPSSID, if that matters.
Are there particular vulnerabilities issues i could face with this pattern?
thanks


text:
Q: What are some tips on reducing the disk space used by Windows 7? Does anyone have any tips on reducing the space used by Windows 7? So far I've got:

*

*Empty Recycle Bin

*Run Disk Cleanup Wizard

*Use 'Programs & Features' control panel to uninstall unneeded components

However even after all that, my Windows directory is taking up 12GB. I found this other question, but that would require me to hack the windows installation disk and then reinstall my OS from scratch, which I'd like to avoid if possible.
Edit: Reason for this question: I already have a spare drive where I store non-essential stuff, but my main C: drive is a small expensive SSD, so the more space I can clear on there, the better. I already run WinDirStat to find stuff in my home folder, and which apps in Program Files are taking up too much space, this question is specifically for reducing the 12 GB in C:\Windows.

A: Install and frequently run ccleaner. Defragment your disk (which is probably the biggest). And lastly (if you can), just buy a terabyte external hdd, they are about a 100 bucks and you never have to worry about disk space again :)

A: This question may provide some insight as to what is taking up all that space on your computer.
Apart from deleting what you have already, you could also try running CCleaner on your system to clean any unnecessary files from your system. Apart from this, there isnt really much you can do to clean out your system folders.
You could however try and remove files from your home folder. I would suggest going through your 'Downloads' folder (if you have one) and deleting anything you don't need any more. I know on my system I tend to hoard lots of files. Last time I looked at mine, it was coming in at 10 GB.
As well, you could purchase an external hard drive and store lots of your media on that. 1 TB drives are cheap these days, and you could store your entire media collection on them, which, depending on how much music and videos you have, could free up another 10GB.


text:
Q: Mobile web architecture using angularJS I am developing a responsive mobile web app to support maximum devices ( iPhone/Android/windows .. handsets/tablets ).What I am planning is that, extending same architecture, I can build Hybrid Apps.
From a angular architecture point of view,  I am thinking to have a global controller which would decide a app type ( hybrid/web or device type)  and pass the request & invoke the appropriate template from desired view ( assuming view is different for these devices)
I would like to know best practices in implementing such architecture? appreciate for your quick help.
Thank you


text:
Q: Hooking Django (DRF) to an existing database I think I am looking for as much advise as possible.
I have a project that I have inherited. The codebase is absolutely awful. I have a Django project, within this a React app. There's all manner of proxies between to fetch from the API to deliver up content.
However, I want to start to re-write the API, as it is awfully put together. Zero documentation.
To re-write the API, I would like take a copy of the exisiting database - and then work with this to write a more consistent API.
What would be your advise/steps/method to achieve this, and what should I look out for when doing this?
N.B. The database is PostgreSQL.

A: For this Django itself has the inspectdb command.
It will inspect all tables, fields, and foreign-key relations and then create unmanaged models for you. You can fix them manually with (perhaps) missing foreign-keys and then use them in django-rest-framework.


text:
Q: How to distinguish two entities that can play the same role at a given moment I am modeling data from a system.
I have a PATIENT entity. This entity can connect to the site to retrieve his medical data.
Also I want to create a USER entity for those have permission to act on the site (admin, supervisor and input operators).
Since the patient can connect to the site and retrieve information about him, and that members of the service can do the same thing,
is the Patient entity not confused in this case with the User entities?
Or should we distinguish the two entites?
Thank you.
I have created entity PATIENT, but i am in doubt.

A: For purposes of defining the data model, you seem to have a situation where patients are users.
This simply suggests having two separate entities, with the user id being a property of the patient.  So:
create table users (
    user_id int auto_increment primary key,
    -- information about users
    . . .
);

create table patients (
    patient_id int auto_increment primary key,
    user_id int,
    -- information about patients
    . . .
    constraint fk_patients_user_id foreign key (user_id) references users(user_id)
);

Then you can start defining roles, such as "viewer", "editor", "maintainer" and provide a table that assigns roles to users -- and only to users.  For patients, the default role would be "view only my own records".  Others might have broader roles.


text:
Q: Generate a heatmap in Python with xyz dataframe I have x,y,z data stored in a pandas dataframe from which I would like to generate a 2D heatmap (depth plot).
df= pd.DataFrame(np.random.randint(0,100,size=(100, 3)), columns=list('XYZ'))

I am uncertain of how to do this with matplotlib. This example suggests converting to a numpy array and creating a contourf plot. Is there a way to plot directly from pandas? If not, how would I reshape the dataframe into a 2d numpy array?

A: First of all, dataframes are numpy arrays. They are just extended to have a lot of other nice features. So there is no need to "convert" anything here.
Second, plotting random values as a heatmap is not going to work. You will either need to have meaningful coordinates or you will need to have meaningful z-values.
If everything is random the only thing you can do, which would formally work (but not give a meaningful result) is to use a tripcolor or a tricontourf plot.
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

df= pd.DataFrame(np.random.randint(0,100,size=(100, 3)), columns=list('XYZ'))

fig, (ax, ax2)=plt.subplots(ncols=2)
ax.set_title("tripcolor")
ax.tripcolor(df["X"], df["Y"], df["Z"])
ax2.set_title("tricontour")
ax2.tricontourf(df["X"], df["Y"], df["Z"])

plt.show()


text:
Q: Item[String] on System.Text.Json.Nodes.JsonNode: The node must be of type 'JsonObject' Experimenting with System.Text.Json, and not able to cleanly express chain of properties with optional early temination.
I want something like this
((JsonNode)node)?["a"]?["b"]?["c"]
Note, I'm not looking for workarounds (I can write some wrappers, extensions methods, etc). I want to understand if this my issue, doc issue, or framework bug.
Sample code:
            JsonNode rootNode = JsonNode.Parse(@"{""p"": ""v""}");

            // These work as expected
            _ = rootNode["a"]; // Ok
            // _ = rootNode["a"]["b"]; // System.NullReferenceException - expected
            _ = rootNode["a"]?["b"]; // Ok - expected
            _ = rootNode["p"]; // Ok - expected

            // Now this does not work as expected

            // Unexpected exception: The node must be of type 'JsonObject'
            //_ = rootNode["p"]?["x"];

            JsonNode p = rootNode["p"]; // Ok so far, p is not null

            // Unexpected exception: The node must be of type 'JsonObject'
            // How come? Doc says Item[String] Gets or sets the element with the specified property name. If the property is not found, null is returned.
            JsonNode x = p["x"];

Exception:
System.InvalidOperationException
  HResult=0x80131509
  Message=The node must be of type 'JsonObject'.
  Source=System.Text.Json
  StackTrace:
   at System.Text.Json.Nodes.JsonNode.AsObject()
   at System.Text.Json.Nodes.JsonNode.get_Item(String propertyName)
   at JTokenConditional.Program.Main(String[] args) in

Environment: .net 6, VS 2022

A: Docs for the indexer you use state in the Exceptions section:

InvalidOperationException The current JsonNode is not a JsonObject

And it makes sense - you can only obtain a property of something than can have a properties in the first place - that is of JsonObject (any other subtype of JsonNode cannot have properties). However, you have a JsonValue here (string "v"), so trying to obtain a property of that throws exception as it should according to the docs. It would only return null if you try to obtain non-existing property of JsonObject.
So if you are going this route - you have to first check if JsonNode you have is actually JsonObject before trying to access an indexer, if you don't want a possibility of exception.


text:
Q: What I cannot import a verified code in the current directory? So I have the following script, test.py:
>cat test.py
def foo(x):
    y=x*2
    return y

print foo(100)
x = "aaa100"
print x

I can run it well:
>python test.py
200
aaa100

But inside the interactive interpreter, I cannot import it:
>python
Python 2.6.6 (r266:84292, Aug 18 2016, 15:13:37)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test.py", line 6, in <module>
    x + 10
TypeError: cannot concatenate 'str' and 'int' objects

Do you see what is wrong?

A: There is already a test module (https://docs.python.org/3/library/test.html or https://docs.python.org/2/library/test.html), which is loaded before your local test.py on the PYTHONPATH because you used import.
In the interpreter, you can see where it is
> import test
> test
<module 'test' from 'C:\Python27\lib\test\__init__.pyc'>

Yours may not be the test module. It tends to successfully import. You must have another test.py on your PYTHONPATH.
Your command line does not have an import, so it is free to use the local filename when you pass it directly to the python executable as an argument.
A simple way to avoid the name conflict, name your file "test_foo.py" and import test_foo. (unless you use test_foo.py in multiple places)
Additionally, consider a run function, in combination with
if __name__ == __main__:

because right now it will execute those prints as part of the import. You will want to do that also in ... whatever other "test.py" you have.

A: It's either these two cases:
1) Python built-in module "test" (https://docs.python.org/2.7/library/test.html) is being loaded and not your local test.py, however, you shouldn't have any problem importing your local test.py since its a default module, its strange that you are getting an error when you try importing it (unless you have modified it). You can try this to see the imported module cache and check for the test module path
import sys
 print sys.modules
If this is the case then you simply have to open a new python interpreter to make sure no test module has been cached. If its still cached, then change the name of your test.py to something_test.py
2) The code you are representing above is not complete and you have a line "x + 10" and since you are assigning x as a string and trying to add integer, your import isn't working. I doubt this being true as I am sure if this was the case you would be aware of it :-)


text:
Q: Finding base and dimension of the intersection of Ker(T) and Im(T) Given the Linear Transformation $T:\mathbb{R}^3\rightarrow\mathbb{R}^3 $ that satisfies:
$$
T\left(
\begin{array}{c}
1\\
1\\
1\\
\end{array}
\right)=\left(
\begin{array}{c}
2\\
3\\
5
\end{array}
\right),T\left(
\begin{array}{c}
1\\1\\0
\end{array}
\right)=\left(
\begin{array}{c}
2\\2\\4
\end{array}
\right),T\left(
\begin{array}{c}
1\\0\\0
\end{array}
\right)=\left(
\begin{array}{c}
1\\2\\3
\end{array}
\right)$$
I need to find the base & dimension of $ker(T)\cap Im(T)$
I've found the bases for $ker(T)$ and $Im(T)$ and after doing the old wishy washy way my lecturer taught me to find the intersection, I've gotten this result:
$ker(T)\cap Im(T)=${$\left(
\begin{array}{c}
0\\0\\0
\end{array}
\right)$}
thus resulting in $dim(ker(T)\cap Im(T))=0$.
I am uncertain that I did right, I am also not sure about how to (and if I'm able to) find a base for group I got.
(My guess is that the group represented by the zero-vector has no base, as it's dimension is $0$).

A: The set $\beta=\{(1,1,1),(1,1,0),(1,0,0)\}\subseteq \mathbb{R}^{3}$ is a basis for vector space $\mathbb{R}^{3}$ over $\mathbb{R}$.
Then $$\begin{bmatrix} a\\b\\ c\end{bmatrix}=\alpha_{1}\begin{bmatrix} 1\\ 1\\ 1\end{bmatrix}+\alpha_{2}\begin{bmatrix} 1\\ 1 \\ 0\end{bmatrix}+\alpha_{3}\begin{bmatrix} 1\\ 0 \\ 0\end{bmatrix} \implies \begin{cases} &\alpha_{1}= c,\\ \quad &\alpha_{2}= b-c,\\ \quad &\alpha_{3}=a-b\\ \end{cases}$$
Hence since $T$ is a linear trasnformation, we have
$$\color{red}{T}\begin{bmatrix} a\\b\\ c\end{bmatrix}=c \color{red}{T}\begin{bmatrix} 1\\ 1\\ 1\end{bmatrix}+(b-c)\color{red}{T}\begin{bmatrix} 1\\ 1 \\ 0\end{bmatrix}+(a-b)\color{red}{T}\begin{bmatrix} 1\\ 0 \\ 0\end{bmatrix}$$
$$T\begin{bmatrix} a\\b\\ c\end{bmatrix}=\begin{bmatrix} a+b\\ 2a+c\\ 3a+b+c\end{bmatrix}$$
By definition,
\begin{align*}
{\rm ker}(T)&=\{(a,b,c)\in \mathbb{R}^{3}: T(a,b,c)=(0,0,0)\}\\
&=\left\{(a,b,c)\in \mathbb{R}^{3}: a=-\frac{1}{2}c, b=\frac{1}{2}c, c\in \mathbb{R}\right\}\\
&={\rm span}\left\{\begin{bmatrix}-\frac{1}{2}\\ \frac{1}{2}\\ 1\end{bmatrix} \right\} \implies \dim {\rm ker}(T)=1
\end{align*}
By definition,
\begin{align*}
{\rm im}(T)&=\left\{(x,y,z)\in \mathbb{R}^{3}\exists (a,b,c)\in \mathbb{R}^{3}: T(a,b,c)=(x,y,z)\right\}\\
&=\left\{(x,y,z)\in \mathbb{R}^{3}: x+y-z=0\right\}\\
&=\left\{(x,y,z)\in \mathbb{R}^{3}: x=-y+z,y,z\in \mathbb{R}\right\}\\
&={\rm span}\left\{\begin{bmatrix} -1\\ 1\\ 0\end{bmatrix}, \begin{bmatrix} 1\\ 0 \\ 1\end{bmatrix} \right\} \implies \dim {\rm im}(T)=2
\end{align*}
Therefore,
\begin{align*}
{\rm ker}(T)+{\rm im}(T)&={\rm span}\left\{ \beta_{{\rm ker}(T)}\cup \beta_{\rm im}(T) \right\}\\
&={\rm span}\left\{\color{red}{\begin{bmatrix}-\frac{1}{2}\\ \frac{1}{2}\\ 1\end{bmatrix}}, \color{green}{\begin{bmatrix} -1\\ 1\\ 0\end{bmatrix}, \begin{bmatrix} 1\\ 0 \\ 1\end{bmatrix}} \right\}
\end{align*}
Since $$\det \begin{bmatrix} -\frac{1}{2} & \frac{1}{2} & 1\\ -1 & 1 & 0\\ 1 & 0 & 1\end{bmatrix} =-1\not=0$$
so  ${\rm ker}(T)\oplus {\rm im}(T)= \mathbb{R}^{3}$ hence a basis for ${\rm ker}(T)+ {\rm im}(T)$ is given by
$$\beta_{{\rm ker}(T)+ {\rm im}(T)}=\left\{\begin{bmatrix}-\frac{1}{2}\\ \frac{1}{2}\\ 1\end{bmatrix}, \begin{bmatrix} -1\\ 1\\ 0\end{bmatrix}, \begin{bmatrix} 1\\ 0 \\ 1\end{bmatrix} \right\}$$
Hence $$\dim {\rm ker}(T)+ {\rm im}(T)=3.$$
Therefore,
$${\rm ker}(T)\cap {\rm im}(T)={\rm span} \left\{ \begin{bmatrix} 0\\ 0 \\ 0 \end{bmatrix} \right\} \implies \dim {\rm ker}(T)\cap {\rm im}(T)=0.$$
Alternatively, direct by definition
\begin{align*}
{\rm ker}(T)\cap {\rm im}(T)&=\left\{(x,y,z)\in \mathbb{R}^{3}: \begin{cases} x+y-z=0\\ x+\frac{1}{2}z=0,\\ y-\frac{1}{2}z=0\end{cases} \right\}\\
&=\left\{(x,y,z)\in \mathbb{R}^{3}: x=y=z=0 \right\}\\
&={\rm span}\left\{ \begin{bmatrix} 0\\ 0\\ 0\end{bmatrix}\right\}
\end{align*}
Therefore a basis for ${\rm ker}(T)\cap {\rm im}(T)$ is given by $\emptyset$ and then the dimension is $0$.

A: Let $\beta_1=(1,1,1)$, $\beta_2=(1,1,0)$ and let $\beta_3=(1,0,0)$. Let $e_1,e_2,e_3$ denote the standard basis on $\mathbb{R}^3$. Note that $e_1=\beta_3$, $e_2=\beta_2-\beta_3$ and that $e_3=\beta_1-\beta_2$. Let $v_i=T\beta_i, \ i=1,2,3.$ Then $Te_1=T\beta_3=v_1=(1,2,3)$, $Te_2=T(\beta_2-\beta_3)=v_2-v_3=(1,0,1)$, $Te_3=T(\beta_1-\beta_2)=v_1-v_2=(0,1,1)$. This gives you the matrix corresponding to $T$ with respect to the standard basis, and is sufficient for what you need and perhaps the more familiar.
You can also ponder the question by drawing a square split in two between $\ker T$ and some other set $U$ - call it the complement of $\ker T$ -  and another square split between Image $T$ and some  other set $V$, the latter you may call the complement of Image $T$. You could ask yourself where elements of $U$ go, and where elements of $\ker T$ end up, draw some arrows and so on.


text:
Q: Execute CMD.EXE with CreateProcessWithLogonW() without a new console I have to run cmd.exe with CreateProcessWithLogonW() but in the context of my program without creating another console, but MSDN says the CREATE_NEW_CONSOLE flag has been set by default. How can I unset this flag so this API doesn't create a new window for my child process?
The following code shows how this API is used in my program. I don't want the new program to run in a new console, but I could not find a solution for that.
BOOL status = FALSE;
DWORD process_flags = 0 | arg_process_flags;
DWORD logon_flags = 0 | arg_logon_flags;
PTSTR duplicate_command_Line;
PPROCESS_INFORMATION ptr_process_info;
STARTUPINFO startup_info;
RtlZeroMemory(&startup_info, sizeof(STARTUPINFO));
startup_info.cb = sizeof(STARTUPINFO);

if (ptr_process_info = arg_process_infos ? arg_process_infos : (PPROCESS_INFORMATION)LocalAlloc(LPTR, sizeof(PROCESS_INFORMATION)))
{
    if (duplicate_command_Line = _wcsdup(arg_command_Line))
    {
        switch (arg_type)
        {
            case KULL_M_PROCESS_CREATE_NORMAL:
                status = CreateProcess(NULL, duplicate_command_Line, NULL, NULL, FALSE, process_flags, NULL, NULL, &startup_info, ptr_process_info);
                break;

            case KULL_M_PROCESS_CREATE_USER:
                status = CreateProcessAsUser(arg_user_token, NULL, duplicate_command_Line, NULL, NULL, FALSE, process_flags, NULL, NULL, &startup_info, ptr_process_info);
                break;

            case KULL_M_PROCESS_CREATE_LOGON:
                status = CreateProcessWithLogonW(arg_user, arg_domain, arg_password, logon_flags, NULL, duplicate_command_Line, process_flags, NULL, NULL, &startup_info, ptr_process_info);
                break;
        }

        if (status && (arg_auto_close_handle || !arg_process_infos))
        {
            CloseHandle(ptr_process_info->hThread);
            CloseHandle(ptr_process_info->hProcess);
        }

        if (!arg_process_infos)
            LocalFree(ptr_process_info);

        free(duplicate_command_Line);
    }
}

A: You could redirected input and output of child process
Here's my test program(remove the error checking).
Parent:
#include <windows.h>
#include <iostream>
#define BUFSIZE 4096
void main()
{
    printf("in Parent \n");
    HANDLE R_In, R_Out, R_err, W_In, W_Out, W_err;
    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
    HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
    SECURITY_ATTRIBUTES saAttr;
    BOOL bSuccess;
    saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
    saAttr.bInheritHandle = TRUE;
    saAttr.lpSecurityDescriptor = NULL;

    CreatePipe(&R_In, &W_In, &saAttr, 0);
    CreatePipe(&R_Out, &W_Out, &saAttr, 0);
    CreatePipe(&R_err, &W_err, &saAttr, 0);
    PROCESS_INFORMATION process_info;
    STARTUPINFO startup_info;
    RtlZeroMemory(&startup_info, sizeof(STARTUPINFO));
    startup_info.cb = sizeof(STARTUPINFO);
    startup_info.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
    startup_info.wShowWindow = SW_HIDE;
    startup_info.hStdInput = R_In;
    startup_info.hStdOutput = W_Out;
    startup_info.hStdError = W_err;

    BOOL ret = CreateProcessWithLogonW(L"username",L"domain",L"password", 0,L"ChildProcess.exe",NULL, CREATE_NO_WINDOW,NULL,NULL,&startup_info,&process_info);
    CloseHandle(R_In);
    CloseHandle(W_Out);
    CloseHandle(W_err);
    CHAR chBuf[BUFSIZE];
    DWORD dwRead, dwWritten;
    bSuccess = ReadFile(hStdin, chBuf, BUFSIZE, &dwRead, NULL);
    bSuccess = WriteFile(W_In, chBuf, dwRead, &dwWritten, NULL);
    while (1)
    {
        bSuccess = ReadFile(R_Out, chBuf, BUFSIZE, &dwRead, NULL);
        if (bSuccess == 0 & GetLastError() == ERROR_BROKEN_PIPE) // child process exit.
            break;
        bSuccess = WriteFile(hStdout, chBuf, dwRead, &dwWritten, NULL);
    }
    WaitForSingleObject(process_info.hProcess, INFINITE);
    printf("Parent exit\n");
}

Child:
#include <windows.h>
#include <iostream>
#define BUFSIZE 4096
#pragma warning(disable : 4996)
void main()
{
    CHAR chBuf[BUFSIZE];
    scanf("%s", chBuf);
    printf("in Child %s\n", chBuf);
    printf("Child exit\n");
    return;
}

Result:

A: Do you mean you don't want to create a new window?
try startup_info.dwFlags = STARTF_USESHOWWINDOW;startup_info.wShowWindow = SW_HIDE; then it won't create a window.

A: It's been awhile, but passing DETACHED_PROCESS should work.
If not, you can call CreateProcessWithLogonW passing it a win32 binary that you provide (possibly your own with different options) that in turn will call CreateProcess opening cmd.exe without passing CREATE_NEW_CONSOLE.
Unless you're already admin, creating in the same console is utterly impossible, and if you are admin, it's an arcane technique you're better off not using.


text:
Q: Is it possible for a pitcher to hit a homerun in RBI Baseball? In the original RBI Baseball game on NES all the pitchers had the same batting stats; a 150 batting average and 0 home runs (I think).  A friend of mine has always claimed that he has hit a home run with a pitcher.
Is it possible to determine how far a pitcher can hit the ball and if they are capable of hitting a home run?

A: According to this fan based website:
Is it possible to hit a home run with the pitcher?

Apparently, it is. I have received more than a few emails and read messages on my forums confirming the pitcher homer. The people on the forums are reliable folks and I am certain they are telling the truth, so it is possible. In every case I've read, the ball is lined down the left/right field line and goes through the top of the wall (aka the wallzie)>. That being said, none of the Dee-Nee crew or anyone I know personally has ever gone yard with the pitcher. But we will...

Just some additional information on the pitchers when it comes to batting as far as determining the hitting of the ball:

all pitchers have the exact same batting characteristics

I'm not 100% sure how reliable the resource is, but there doesn't seem to be a lot of other information out there for this game that I have found.

A: A pitcher can definitely score a home run... although maybe not in the usual way. I was curious so I spent about an hour looking at various videos of the game, and while I did not come across a straight home-run, I did find this:

There were also a few videos of what was either a glitch or cheat that seemed to turn contact into a home run.

A: This happened to me and I recall most of the circumstances.  Although I almost always
played a 2 player game because 1 player isn't interesting, I was bored so I played a
1 player game against Detroit.  I can't remember who I used...probably St. Louis...
Anyway, my starter (Tudor?) was worn down and I was lobbing meat pitches straight
down the middle.  Doyle Alexander hit a weak fly down the left field line and it had
just enough juice to make it pass through the bottom of the fence.
Now mind you, I've played thousands of games in RBI baseball and saw this only once.
I could hard believe it and my buddies, to this day, claim I'm lying.


text:
Q: Access 2016 Records between two dates query Currently trying to grab records from a table between two dates, in this case between 4/1/2021 and 3/31/2022. I'm pulling from a linked table to the database and yet cannot get any records from either query I've pulled.
I've used the following queries:
SELECT [Req Update].[ASSET #], [Req Update].[ADHOC DATE]
FROM [Req Update]
WHERE ((([Req Update].[ASSET #]) Is Not Null)
 AND (([Req Update].[ADHOC DATE])>=[Start Date]
 And ([Req Update].[ADHOC DATE])<=[End Date]));

This one above I have set up to enter in the start and end date since next year it will have to change. I'd prefer to have it like this going forwards.
This query below though has the dates I need without manually entering the start and end dates.
SELECT [Req Update].[ASSET #], [Req Update].[ADHOC DATE]
FROM [Req Update]
WHERE ((([Req Update].[ASSET #]) Is Not Null)
AND (([Req Update].[ADHOC DATE])>='4/1/2021'
And ([Req Update].[ADHOC DATE])<='3/31/2022'));

The Req Update linked table has 5 records that should show up, all are within the dates I add/need.
Specifically I'm thinking either I'm missing something or maybe the data isn't matching up correctly. Any assistance with this would be appreciated. Thank you.

A: In Microsoft Access dates are not in quotes, they are between pound-signs (#).  Change this:
AND (([Req Update].[ADHOC DATE])>='4/1/2021'
And ([Req Update].[ADHOC DATE])<='3/31/2022'

to this:
AND (([Req Update].[ADHOC DATE])>=#4/1/2021#
And ([Req Update].[ADHOC DATE])<=#3/31/2022#

Better yet, change it to
AND [Req Update].[ADHOC DATE]) between #4/1/2021# and #3/31/2022#


text:
Q: Html 5 Download attribute in iPhone I have a requirement where I need to download and view files( pdf, word, jpg etc) from the server in ionic progressive web app without navigating away from the page. What would be the best and easiest way to get it done ?
I have achieved this by using html5-Download attribute in android but its not working as expected in iPhone.
Any help would be great.
Regards
TA

A: According to MDN Web Docs, the Download attribute is not supported in Safari on iOS. See: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#Browser_compatibility. There is also a requirement that the file to be downloaded is served from the same origin. I'm not familiar with Ionic 2 or Angular, however in regular HTML5 Web Apps, we have just used target="_blank" which downloads the file. If you need to stay on the same page, just use target="_self".

A: The upcoming release of iOS 13 will support the download attribute. The underlying WebKit Bug #102914 is now marked as RESOLVED FIXED.
caniuse.com also lists the feature as supported in that version by now. Therefore, libraries like file-saver are expected to just work in that version.


text:
Q: How to programmatically trigger a click while holding cmd key Is there a way to programmatically trigger a click through JavaScript that also simulates the cmd key held down?
For example if I do document.getElementById("anchor-tag-element").clickWithCmdHeldDown() the link would open in a new tab.
I also want this to work for non-anchor tags, so document.getElementById("div-element").clickWithCmdHeldDown() would have a normal click behavior on the div.

A: For what the OP wants to achieve one has to implement an own/custom link-like behavior and event handling ...

function triggerCustomMetaKeyClick() {
  document
    .querySelector('p[data-link-like-src]')
    .dispatchEvent(new MouseEvent('click', { metaKey: true }));
}

function handleLinkLikeBehavior(evt) {
  evt.preventDefault(); // one never knows.

  const { currentTarget, metaKey } = evt;
  const {
    linkLikeSrc: href,
    linkLikeTarget: target = '_self',
  } = currentTarget.dataset;

  const isNewWindow =
    (metaKey === true) || (target !== '_self');

  if (href) {
    if (isNewWindow) {
      const windowTarget =
        ((target === '_self') && '_blank') || target;

      console.log('before "allow-popups" permission error ...', {
        href,
        windowTarget,
      });
      window.open(href, windowTarget);
    } else {
      location.href = href;
    }
  }
}

function initializeLinkLikeBehavior(elmNode) {
  elmNode.addEventListener('click', handleLinkLikeBehavior);
}
function initialize() {
  document
    .querySelectorAll('[data-link-like-src]')
    .forEach(initializeLinkLikeBehavior);
  document
    .querySelector('button')
    .addEventListener('click', triggerCustomMetaKeyClick);
}

initialize();
a[data-link-like-src] { display: block; }

[data-link-like-src] { margin: 10px 0; color: #00f; text-decoration: underline; cursor: pointer; }
[data-link-like-src]:hover { color: #f00; }

.as-console-wrapper { min-height: 100%!important; top: 0; left: auto!important; right: 0!important; width: 54%!important; }
English Wikipedia in same window
via click (or new tab via CMD)

English Wikipedia in new window/tab
via click

  English Wikipedia in same window
via click (or new tab via CMD)

<button>
  trigger custom 'click'-type mouse-event

  with CMD-context on last link-like element
</button>


text:
Q: Access MTP storage with System.IO from PowerShell I'm trying to access MTP device storage to automate file copy, backup, etc.
If Windows Explorer is able to open and browse Android device Internal Storage and connected SD card, how can I access these storages with PowerShell?
I've found a lots of hints, such as "get device ID and use WMI"
What is the way the Windows Explorer uses to open and browse especialy Android's storages?
Is it possible to use some System.IO Class like here?
$drives = [System.IO.DriveInfo]::GetDrives()
$r = $drives | Where-Object { $_.DriveType -eq 'Removable' -and $_.IsReady }
if ($r) {
    return @($r)[-1]
}

I'm able to access and browse content of local MTP (android) device with this:
$WIAdialog = New-Object -ComObject "WIA.CommonDialog"
$Device = $WIAdialog.ShowSelectDevice()
$Device = $WIAdialog.ShowAcquireImage()
$Device = $WIAdialog.ShowAcquisitionWizard()
$Device = $WIAdialog.ShowDeviceProperties()
$Device = $WIAdialog.ShowItemProperties()
$Device = $WIAdialog.ShowPhotoPrintingWizard()
$Device = $WIAdialog.ShowSelectItems()
$Device = $WIAdialog.ShowTransfer()

But this code is loading information about stored pictures which is too slow even at local computer. Is it possible to avoid loading info about pictures to speed up loading and accessing remotely connected devices?
Thanks in advance for any information and hints!

A: This is my first answer on Stack Overflow (Stack Exchange) please take it into the consideration.
I am dealing with the same issue - I want to be able to work with android internal storage in PowerShell as I am able in Explorer.
My only suggestion is that we could install FTP Server (my favourite is FTP Server)
and sort it this way. What I have found so far are these answers on superuser:
Open command prompt to access folders of a USB connected Android phone  13 votes & accepted
In order to assign a drive letter to a removable device, that device must support UMS (USB Mass Storage) protocol. Unfortunately most newer Android phones, especially those without a removable SD Card, do not support UMS. Instead, they support MTP (Media Transfer Protocol) and PTP (Picture Transfer Protocol) protocols. In such devices it's not possible to map storage as a drive in Windows.
See more details on this Superuser.com question: How do I access MTP devices on the command line in Windows?

24 votes & accepted
Unfortunately, APIs exposed by MTP are very different from a normal filesystem APIs. Therefore exposing MTP device as a read/write filesystem is not possible. The main reason:
Wikipedia says:

Neither the MTP nor the PTP standards allow for direct modification of objects. Instead, modified objects must be reuploaded in their entirety, which can take a long time for large objects. With PTP/MTP, the file size must be known at the opening stage.

Your common file copy program just opens a source and a target file, and copies data in chunks from the source file to the target. This won't work with MTP, since you need to use MTP special functions, and generic filesystem primitives (read, seek, write) are not available.
There are also other limitations. For example, the number of files that can be read or written simultaneously on an MTP device is severely limited. The device simply does not behave like a filesystem.
I suppose read-only filesystem driver for an MTP device might be possible, but because of the problems outlined above, it will be of very little use, so nobody bothered to create it.
edited May 12 '12 at 6:33
  Peter Mortensen
  8,075
answered Jan 10 '12 at 20:08
  haimg
  15.9k

The read-only filesystem driver seems to exist now: ptpdrive.com – Arne de Bruijn Sep 12 '13 at 12:25

ptpdrive.com

Actually, it's not "not possible". When you consider that I've got gphotofs and mtpfs as FUSE filesystems on Linux that're COMPLETELY Read/Write - its' quite possible to accomplish this as a "drive letter" under Windows... they've just not made it available or easy. – Svartalf May 9 '14 at 19:57

With that said, on some selected Samsung and Sony Android devices it's  possible to enable the UMS mode for external storage only (SD Card).
See this app SG USB Mass Storage Enabler.
Also, if your goal to simply copy files to and from an Android device via command prompt, ADB will allow you to do so. This utility is part of Android SDK tools. You will need USB drivers for your android phone to be installed, USB Debugging activated in Developer Settings on the phone, and authorize the PC to debug the phone (via a prompt on the device.) After that is done, you will be able to use adb push and adb pull commands to copy files & directories, and various Linux shell commands via adb shell <command> (e.g.adb shell ls /sdcard/) to navigate the directory structure on the phone.
edited Mar 20 '17 at 10:18
Community♦
1
answered Nov 21 '13 at 16:14
Chahk
18.5k
App mentioned in above answer looks to me very limiting because its age.

A: Function fn_PhoneFolder {
    Param($PhoneName, $PhoneFolder)

    Write-Host "Searching....$($PhoneName)" -ForegroundColor Green

    $Shell = new-object -com Shell.Application
    $ShellItem = $Shell.NameSpace(17).self #17 = My Computer (https://learn.microsoft.com/en-gb/windows/win32/api/shldisp/ne-shldisp-shellspecialfolderconstants?redirectedfrom=MSDN)
    $Phone = $ShellItem.GetFolder.items() | where { $_.name -eq $PhoneName }

    $FolderParts = @( $PhoneFolder.Split([system.io.path]::DirectorySeparatorChar) )

    $PhonePath = $Phone
        ForEach ($Part in $FolderParts) {
            If ($Part) {
                $PhonePath = $PhonePath.GetFolder.items() | where { $_.Name -eq $Part }
                }
            }

    $ReturnFiles = New-Object System.Collections.Generic.List[System.Object]

    $Files =  @($PhonePath.GetFolder.items())

    $Files

    ForEach ($File in $Files) {
        $TempFiles = @{}
        $TempFiles.Name = $File.Name
        $TempFiles.Path = $File.Path
        $TempFilesObject = New-Object PSobject -Property $TempFiles
        $ReturnFiles.Add($TempFilesObject)
        }

    Return $ReturnFiles

}

$MyPhoneFiles = fn_PhoneFolder -PhoneName "X19" -PhoneFolder "Internal shared storage\WhatsApp\Media\WhatsApp Images\Sent"

Change PhoneName and PhoneFolder on the last line to match your Phone Name as displayed in My Computer. This function will pull back an array of all files in the folder selected. Thanks to https://blog.daiyanyingyu.uk/2018/03/20/powershell-mtp/ for the idea of searching through the shell folders to find the phone.


text:
Q: Python / Pandas; How to hold value of column until next event I've been struggling with a problem for a while and haven't been able to find something similar elsewhere. I'm pretty new to Python so appologies if this is pretty straight forward.
So I have a series that I put into a pandas df:
series_ = [0, 0, 0, 1, 0, 0, 0, 4, 4, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 4, 0, 0]
df = pd.DataFrame(series_, columns = ['Values'])

The series can have two 'signal values':
Every time the series value is 1, I want the corresponding value to be 'YES'
If the value is 4, it should be 'NO'.
When the series is not 1 or 4, it should replicate the previous signal value (either 'YES' or 'NO') until the next signal value. I sadly can't find a formula that fills up these empty spots.
So what I currently have is my series ('Values') and the translation of these signal values in the column ('Modified'). I am trying to find a formula that will get me the column ('Expected'), a formula which basically replaces the 'UNDECLARED' values with either 'YES' or 'NO' based on the last available signal value.

Would appreciate all help!
Thanks in advance.
Tom

A: I am certain, that there is a better way to do this but here is a quick and dirty solution, not sure if speed is important to you...
df['Expected']=df['Values'].replace(0,np.NaN).ffill().replace({1:'NO', 4: 'YES'}).fillna('UNDECLARED')


text:
Q: execute two methods at the same time I am working on my first multithreaded app in many years.  The problem im having is i need to execute two methods at the same time.  here's my engine class:
public class ThreadPoolEngine {

    // create BlockingQueue to put fund transfer objects
    private BlockingQueue<GlobalSearchRequest> searchQueue;

    public ThreadPoolExecutor executor;

    private HashMap<String, GlobalSearchProcessorCallable> callableMap;

    private ArrayList<Future<Integer>> futurList;

    Logger logger = Logger.getLogger(ThreadPoolEngine.class);

    private Integer gthreadCount;
    private Integer gjobPerThread;

    public ThreadPoolEngine(Integer threadCount, Integer jobPerThread) {
        gthreadCount = threadCount;
        gjobPerThread = jobPerThread;
        // create a thread pool with the entered no of threads
        executor = new HammerThreadPoolExecutor(threadCount, threadCount, 0L,
                TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());

        searchQueue = new ArrayBlockingQueue<GlobalSearchRequest>(jobPerThread);

        callableMap = new HashMap<String, GlobalSearchProcessorCallable>();

        // create list to store reference to Future objects
        futurList = new ArrayList<Future<Integer>>();
    }

    public void createAndSubmitTasks() {
        // create Callables
        for (int i = 0; i < gthreadCount; i++) {

            GlobalSearchProcessorCallable callable1 = new GlobalSearchProcessorCallable(
                    "SearchProcessor_" + i, searchQueue);
            callableMap.put(callable1.getThreadName(), callable1);

            // submit callable tasks
            Future<Integer> future;
            future = executor.submit(callable1);
            futurList.add(future);
        }
    }

    public void populateSearchQueue() throws InterruptedException {
        // put orderVO objects in BlockingQueue
        KeywordFactory key = KeywordFactory.getInstance();

        for (int i = 0; i < gjobPerThread*gthreadCount; i++) {
            // this method will put SearchRequest object in the order queue
            try {
                searchQueue.put(new GlobalSearchRequest(key.getRandomPhrase(3)));
            } catch (KeywordNoDataFileException e) {
                e.printStackTrace();
            }
        }
    }

    public void printProcessorStatus() throws InterruptedException {
        // print processor status until all orders are processed
        while (!searchQueue.isEmpty()) {
            for (Map.Entry<String, GlobalSearchProcessorCallable> e : callableMap
                    .entrySet()) {
                logger.debug(e.getKey() + " processed order count: "
                        + e.getValue().getProcessedCount());
            }
            Thread.sleep(1000);
        }
    }

    public void shutDown(boolean forceShutdown) {
        if (!forceShutdown) {
            // shutdown() method will mark the thread pool shutdown to true
            executor.shutdown();
            logger.debug("Executor shutdown status " + executor.isShutdown());
            logger.debug("Executor terninated status "
                    + executor.isTerminated());

            // Mark threads to return threads gracefully.
            for (Map.Entry<String, GlobalSearchProcessorCallable> orderProcessor : callableMap
                    .entrySet()) {
                orderProcessor.getValue().setRunning(false);
            }
        } else {

            for (Future<Integer> f : futurList) {
                f.cancel(true);
            }

            // shutdown() method will mark the thread pool shutdown to true
            executor.shutdownNow();
        }
    }

    public void printWorkersResult() {
        for (Future<Integer> f : futurList) {
            try {
                Integer result = f.get(1000, TimeUnit.MILLISECONDS);
                logger.debug(f + " result. Processed orders " + result);
            } catch (InterruptedException e) {
                logger.error(e.getMessage(), e);
            } catch (ExecutionException e) {
                logger.error(e.getCause().getMessage(), e);
            } catch (TimeoutException e) {
                logger.error(e.getMessage(), e);
            } catch (CancellationException e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
}

ok, i have a main class that instantiates this one and calls two methods on this class, the populateSearchQueue and the createAndSubmitTasks to run my worker class and process the items in the search queue.
The problem
the populateSearchQueue method could take a VERY long time to build (im going to hammer the system with one billion queries at a time) and it could take a lot of memory.  Is there a way in java where my main class can call the populateSearchQueue and the createAndSubmitTasks at the same time so the worker threads can start working on the queue while its still being built by the populateSearchQueue method?

A: I actually solved it.  I read my code again and realized that it takes a tiny amount of time to create the thread pool. So call createAndSubmitTasks that creates the thread pool and each assigned a worker class waiting to do something.  When that method is done, I now have my pool of 1000 threads sitting there doing nothing. Then the moment I call populateSearchQueue, those worker threads that were sitting idle for the few milliseconds it took to move to the next method, now start grabbing jobs out of the queue, and I get my desired result. The method that is putting stuff in the queue is processing at the same time the worker threads are grabbing jobs out of that queue and running them.
So I reverse the order I'm calling the methods. It's a thing of beauty.


text:
Q: Ensuring latest version of website is displayed I have a static HTML site operational and I recently made quite extensive changes to it. However by default, browsers show the old version of the site unless the page is refreshed. I had a couple of my friends try to load the site as well and they had the same problem, but it sorted itself out after one refresh.
My question is how do I ensure the latest version of the site is displayed to visitors without them having to refresh the page?
Does this have something to do with the cache?
Any help would be greatly appreciated.
Thanks.

A: Check the cache-control meta tag.


text:
Q: Using more than one flag in python re.findall I would like to use more than one flag with the re.findall function. More specifically, I would like to use the IGNORECASE and DOTALL flags at the same time.
x = re.findall(r'CAT.+?END', 'Cat \n eND', (re.I, re.DOTALL))

Error :
Traceback (most recent call last):
  File "<pyshell#78>", line 1, in <module>
    x = re.findall(r'CAT.+?END','Cat \n eND',(re.I,re.DOTALL))
  File "C:\Python27\lib\re.py", line 177, in findall
    return _compile(pattern, flags).findall(string)
  File "C:\Python27\lib\re.py", line 243, in _compile
    p = sre_compile.compile(pattern, flags)
  File "C:\Python27\lib\sre_compile.py", line 500, in compile
    p = sre_parse.parse(p, flags)
  File "C:\Python27\lib\sre_parse.py", line 673, in parse
    p = _parse_sub(source, pattern, 0)
  File "C:\Python27\lib\sre_parse.py", line 308, in _parse_sub
    itemsappend(_parse(source, state))
  File "C:\Python27\lib\sre_parse.py", line 401, in _parse
    if state.flags & SRE_FLAG_VERBOSE:
TypeError: unsupported operand type(s) for &: 'tuple' and 'int'

Is there a way to use more than one flag ?

A: You can't put the flags within a tuple. Use the pipe character (OR operand) within your flags:
x = re.findall(r'CAT.+?END','Cat \n eND',flags=re.I | re.DOTALL)

A:
Is there a way to use more than one flag ?

It wasn't mentioned, but you can use inline (?...) modifiers as well.
x = re.findall(r'(?si)CAT.+?END', 'Cat \n eND')

A: Yes, but you have to OR them together:
x = re.findall(pattern=r'CAT.+?END', string='Cat \n eND', flags=re.I | re.DOTALL)


text:
Q: Can dplyr join two data frames using a regular expression in by=? Is there a way to join two data frames using dplyr's join operators, but using a regular expression instead of a straight by=c('foo' = 'bar')?
Something like:
people  <- data.frame(
     id = 1:10
   , emp = c("Caterpillar", "FEMA", "Community Hospital", "Gessert Grp.", "AT&T", "IBM Corp.", NA, "Smartguy Community College", NA, NA))

employers  <- data.frame(
     employerID     = c(1, 2, 3, 4, 5)
   , employerName   = c("Caterpillar Foundation", "Eli Lilly and Company Foundation Inc.", "Archer Daniels Midland Co", "IBM Corporation", "State Farm Co.  Foundation Matching Gifts")
   , employerRegexp = c("Caterpillar", "El *Lilly", "Archer *Daniels|ADM", "IBM", "State *Farm")
   )

peoplewRealEmployerNames  <- people  %>%
     left_join(employers,by=c('emp' ~= 'employerRegexp')

Obviously, that ~= won't really work, but maybe there's something similar?
Dplyr isn't a hard requirement, but it is the style I've written the rest of my code in, so it's my first choice for a solution.

A: The package fuzzyjoin does exactly this, using more or less the same syntax as dplyr does.
So, you just need to change the last two lines in your code to:
library(fuzzyjoin)

peoplewRealEmployerNames <- people %>%
  regex_left_join(employers, by=c('emp' = 'employerRegexp'))


text:
Q: Grant database user folder access I'm trying to create a csv export of data from mysql using the following query:
SELECT * INTO OUTFILE '/tmp/result.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\n'
FROM getfreepellets WHERE 1

And I get the following error:
#1045 - Access denied for user '[username]'@'localhost' (using password: YES)

(removed username but it's the right one)
How would I go about granting access to this user to create a file on the server?
Edit:
I changed the first line to be my exact home path, and received the same error.

A: first you must define what your database is with:
use database_name;

Then you can run your query.
If that still not working it is because you create those but you havent defined access to it for that given user.
GRANT ALL ON database_name.* TO 'someuser'@'somehost';

You can read more about the Grant usage at http://dev.mysql.com/doc/refman/5.1/en/grant.html

A: #1045 - Access denied for user '[username]'@'localhost' (using password: YES)

That error has nothing to do with file or directory permissions. That's MySQL telling you that the MySQL logon credentials you used are incorrect for that query. This may be because, as Prix pointed out, you haven't specified the database to use.

A: I spent hours trying to understand the suggestions on this page and many other pages of StackOverflow.
No matter how I changed the permissions in MySql, I couldn't get anything to work.
I reverted back to the permissions I started with.
Ultimately what worked for me was simpler than others' suggestions:
echo "select id, emailAddress FROM contacts" | mysql --user=myusername --password mydatabasename > /home/my_output_file.tsv


text:
Q: Tyring to import import { HttpClient, Headers, RequestOptions } from '@angular/common/http'; Im working with ionic 4 project. and now im trying to make an http post and im follwoing the tut on this link: https://www.techiediaries.com/ionic-http-post/. now it is saying that he cant find Headers, RequestOptions in @angular/common/http';
I tried different thing i find on stack overflow.
import { Component, OnInit } from '@angular/core';
import { HttpClient, Headers, RequestOptions } from
'@angular/common/http';

@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {

constructor(public httpClient: HttpClient) {
 }
 ngOnInit(){}

  sendPostRequest() {
var headers = new Headers();
headers.append("Accept", 'application/json');
headers.append('Content-Type', 'application/json' );
const requestOptions = new RequestOptions({ headers: headers });

let postData = {
        "name": "Customer004",
        "email": "customer004@email.com",
        "tel": "0000252525"
}

this.http.post("http://127.0.0.1:3000/customers", postData, requestOptions)
  .subscribe(data => {
    console.log(data['_body']);
   }, error => {
    console.log(error);
  });
  }

A: Hi try this insted of headers use HttpHeaders:
import { HttpClient, HttpHeaders , RequestOptions } from '@angular/common/http';

A: Angular 5 Onward, If you want to communicate in JSON only then it is not required to set Content-Type as application/json. It will default communicate in JSON format.
So you can just use it as
For GET call
this.http.get('YOUR API').subscribe((response) => {
    console.log(response);
});

For POST call
this.http.post('YOUR API', `{JSON OBJECT}`).subscribe((response) => {
    console.log(response);
});

You can also add Custom Headers for example Authorization token as below
import { HttpClient, HttpHeaders } from '@angular/common/http';
requestHeaders = new HttpHeaders().set('Authorization', 'Token');
and use it as below
For GET call
this.http.get('YOUR API', {headers: this.requestHeaders}).subscribe((response) => {
    console.log(response);
});

For POST call
this.http.post('YOUR API', `{JSON OBJECT}`, {headers: this.requestHeaders}).subscribe((response) => {
    console.log(response);
});

HttpHeaders includes the methods like set(), append() etc.

A: this is how we can add header
  import { HttpHeaders } from '@angular/common/http';

    let yourheaders = new HttpHeaders({
    'Content-Type': 'application/json'
    });

    let youroptions = {
    headers: yourheaders
    }

Take look this
look at this also

A: Keep it Simple:
import { HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) {
}

Get Api:
this.http.get('https://someapi.com/posts').subscribe((response) => {
    console.log(response);
});

Post Api:
    let YourHeaders = {'Content-Type':'application/json'};
    this.http.post(url, YourData, {headers: YourHeaders})
      .subscribe(data => {
      console.log(data)
    },
    (error) => {
            console.log("Error" + error)
    })


text:
Q: How to configure webHttpBinding using user name/password authentication I am working on a WCF service with webHttpBinding for json ajax calls. The service works fine until I turned on the security part. Here is my web.config.

      <serviceCredentials >
        <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="UserNamePasswordValidator, WebServices" />
      </serviceCredentials>
      <serviceAuthorization principalPermissionMode="Custom">
        <authorizationPolicies>
          <add policyType="AuthorizationPolicy, WebServices" />
        </authorizationPolicies>
      </serviceAuthorization>
      <!---->
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="WebHttpBehaviour">
      <enableWebScript />
      <webHttp automaticFormatSelectionEnabled="false" defaultBodyStyle="Wrapped" defaultOutgoingResponseFormat="Json" helpEnabled="true" />
    </behavior>
  </endpointBehaviors>
</behaviors>

Here is my javascript call.
  $.ajax({
       headers: {
                "Authorization": "Basic " + Base64.encode('John:Doe')
            },
            type: "POST",
            url: "https://localhost/StatusService.svc/CheckStatus",
            data: JSON.stringify({"companyName":"test"}),
            contentType: "text/json; charset=utf-8",
            dataType: "json",
            processdata: false,
            success: function (data) {
                alert('ok!');
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(textStatus + ' / ' + errorThrown);
            }
        });
I got error message: object error when I do the ajax call. Is there anything I am doing wrong? Thanks.

A: Find the following solution. Works great.
http://sameproblemmorecode.blogspot.com/2011/10/creating-secure-restfull-wcf-service.html


text:
Q: How can I show specific data un my Django form? I'm a begginner at Django and I'm making an app for lending books and now I'm trying to make a Form using these models:
In my app Books
Class CopyB(models.Model):
     Copy= models.Autofield(primary key=True)
     Condition= models.Charfield(max_lenght=20)
     IdBook=models.ForeignKey(Book, blank= false, null= false ,on_delete= models.CASCADE)

Also in my app Users
Class User(models.Model):
      Myid= models.Charfield(primary_key=True, max_length=20)
      Name= models.Charfield(max_length=20)
      Lastname= models.Charfield(max_length=20)

And in my app loans
From apps.books.models import CopyB
From apps.users.models import User

Class loan(models.Model):
      IdLoan= models.Autofield(primary_key=True)
      IdB= models.ForeignKey(CopyB,blank=False, null=False)
      IdU= models.ForeignKey(User,blank=False, null=False)

What I want to do is making a Form from the model loan and on that form on the field IdB I only want to show in the select input just Books in the model CopyB that in the field Condition is equal to available
But I don't know how to make it!
Thanks in advance

A: You have to filter the objects that meet the condition that you want and fill out the choice field with those.
class LoanForm(forms.ModelForm):

  IdB= forms.ModelChoiceField(queryset=CopyB.objects.filter(condition='available'))

  class Meta:
    model = Loan
    fields = "__all__"

OR
class LoanForm(forms.ModelForm):

  class Meta:
    model = Loan
    fields = "__all__"

  def __init__(self, *args, **kwargs):

    super(LoanForm, self).__init__(*args, **kwargs)
    self.fields['IdB'].queryset = CopyB.objects.filter(condition='available')


text:
Q: Design Question - OO food application Say I have a number of usercontrols, each usercontrol inside a tabitem, inside a window.
For example, let say this is a food collection application. Then we have tabs Fruit, Vegetables and Snacks. Each tab will show a list of food of that subject, and allow the user to add, delete, modify the food in each section. The food is stored in seperate textfiles, i.e. Fruit.txt, Vegetable.txt, Snack.txt
The actual text files might look something like this (vegetable.txt):
Name        Carbs    Fat
Eggplant    2        1.1
Cucumber    3        0.5
etc

Now this is a large list and there is a load method which pulls all the vegetables out into a List
The question I have is this loadVegetables method is in the code behind file, and I end up repeating this load method all over the place, because I have another of other screens like ReviewAllFood, AddVegetable, etc. along with all the other load methods for fruit and snacks.
This is more of a design question, I'm wondering how I set this up to not repeat this code. I could have a VegetableManager (or something) class where the load method is, but does this actually mean less repeated code? Then in each screen I have to create object of VegetableManager and call its load method anyway. So I guess efficiency wise its no better, but I do achieve a better design.
I think I'm missing something here. It's been a while since I studied cohesion and coupling and I think i'm confusing myself with these concepts at the moment. Appreciate if someone could suggest a design for this situation and explain why they chose it and why its better than how i'm doing it at the moment.
Thanks for reading.

A:
I could have a VegetableManager (or
  something) class where the load method
  is, but does this actually mean less
  repeated code? Then in each screen I
  have to create object of
  VegetableManager and call its load
  method anyway.

The point of doing this is not efficiency (i.e. performance). The point is to encapsulate the details of loading that data into a single isolated object. Say for example that your site gets really big and you decide to move the data storage to a database for scalability and performance. In the existing code as you described, you'll have to go through each user control or page and change the logic of the load method. At the best this is a pain, and at the worst you miss some or copy-paste incorrectly.  If the logic is encapsulated into a dedicated object, whose only responsibility is to know how to load the data from somewhere, then you only have to make the change once.
codebehind of user control:
protected void Page_Load(object sender, EventArgs e) {
  var veggieManager = new VegetableManager();
  VeggieListControl.DataSource = veggieManager.GetAll();
  VeggieListControl.DataBind();
}

VegetableManager.cs:
public class VegetableManager {
  private static Collection<Vegetable> _veggies;
  private static object _veggieLock;

  public ReadOnlyCollection<Vegetable> GetAll() {
    if (_veggies == null) {
      lock(_veggieLock) { //synchronize access to shared data
        if (_veggies == null) { // double-checked lock
          // logic to load the data into _veggies
        }
      }
    }

    return new ReadOnlyCollection(_veggies);
  }

  public void Add(Vegetable veggie) {
    GetAll(); // call this to ensure that the data is loaded into _veggies
    lock(_veggieLock) { //synchronize access to shared data
      _veggies.Add(veggie);
      // logic to write out the updated list of _veggies to the file
    }
  }
}

Because _veggies is static, there is only one collection of veggies in memory, despite the fact that multiple callers will instantiate VegetableManager. But because it's static, if you have a multi-threaded application (e.g. a website) you must synchronize access to that field across all threads (hence the locks).
This is the tip of the iceberg in terms of good object-orientation. I recommend perusing UncleBob's SOLID principles, and Domain-Driven Design (free e-book).
So, yes you are repeating something, but all you're repeating is a method call, and that is ok to repeat. DRY means to mitigate the duplication of "logical" code, i.e. decision-making and algorithms; simple method calls do not fall under this. However, if you want, you can consolidate logic into a base class do this, effectively isolating the user controls from having to know about VegetableManager, though I think this is object-orientation overkill, or OOO :-)
public abstract class FoodUserControl : UserControl {
  protected List<Vegetable> GetVeggies() {
    return new VegetableManager().GetAll();
  }
}

Then your actual controls would derive from this instead of from UserControl.
Update
Eager-loading VegetableManager.cs:
public class VegetableManager {
  private static Collection<Vegetable> _veggies;
  private static object _veggieLock;

  static VegetableManager() {
    // logic to load veggies from file
  }

  public ReadOnlyCollection<Vegetable> GetAll() {
    return new ReadOnlyCollection(_veggies);
  }

  public void Add(Vegetable veggie) {
    lock(_veggieLock) { //synchronize access to shared data
      _veggies.Add(veggie);
      // logic to write out the updated list of _veggies to the file
    }
  }
}

Notice this eager-loading version doesn't have to do double-checked locking around the load code in the constructor. Also notice that the load code is in a static constructor, since this code initializes a static field (otherwise, you'd be reloading the data from the file on every construction into the same shared static field). Because veggies are eager-loaded, you don't need to load in GetAll or Add.

A: I would suggest pulling the vegetables (or whatever it is you're loading) out once when you read the file. Then  you store them in some underlying data model. You can bind the list, and whatever other controls you need to, to the underlying data model. The data gets loaded once, but various views can display it.
EDIT: Adding code
List<T> loadObjects(File file, ILineConversionStrategy strategy) {
   // read eaqch line of the file
   // for each line
   T object = strategy.readLine(line);
   list.add(object);
   return listOfObjects;
}

EDIT 2: Data model
class FoodModel {
   List<Vegetable> getVegetables();
   List<Fruit> getFruit();
   // etc
}

A:     public interface IEatable {}

    class Vegitable : IEatable
    { string Name { get; set; } }
    class Fruit : IEatable
    { string Name { get; set; } }

    public interface IEatableManager
    {
        List<Vegitables> LoadEatables(string filePath);
    }
    public class VetabaleManager : IEatableManager
    {
        #region IEatableManagerMembers
        public List<Vegitable> LoadVegs(string filePath)
        {
            throw new NotImplementedException();
        }
        #endregion
    }
    .
    .
    .

There are several things you need to consider for using a design like above

*

*Dependency Injection pattern

*Continuous Integration

*DRY
and a must read:

*

*How can I practice better
object-oriented programming?

A: I would use the repository pattern for this. As a start, create one class containing methods to retrieve the objects from each text file:
public class FoodRepository
{
    public IList<Vegetable> GetVegetables() { ... }
    public IList<Fruit> GetFruit() { ... }
    // etc.
}

This class should be the only class in your application that is aware that foods are actually stored in text files.
Once you get that working you might want to consider caching frequently used data to improve performance.


text:
Q: How to append to wxPython ListCtlr within a button click I'm hoping someone can help me.  I'm not sure where to look.  I'm creating a GUI application with wxPython.  I would simple window with a listctlr and a button.  When you click on the button I need to run a process.  This process has a loop that opens a browser with selenium, does some processing.  For each iteration I would like to append that result to the listctrl.  As of now the list does not update until the process is complete.  I would like it to update the list after each loop iteration. Can you please help or point me in the right direction?
    import sys
    import wx

    from collections import defaultdict
    from selenium import common
    from selenium import webdriver
    from selenium.webdriver.support.ui import Select

    class MainWindow(wx.Frame):

        def __init__(self, parent, title):
            super(MainWindow, self).__init__(parent, title=title)

            def process_applications(event):
                my_cursor = wx.Cursor(wx.CURSOR_WAIT)
                self.panel.SetCursor(my_cursor)

                for x, y in app.items():
                    index = self.list.InsertItem(sys.maxsize, student_application['FirstName'] + " " + student_application['LastName'])

                    .... Process selenium and data....

                    self.list.SetItem(index, 1, 'Success')
                    self.list.SetItem(index, 2, '12452134234')
                    self.list.SetItemBackgroundColour(index, wx.GREEN)
                    my_cursor = wx.Cursor(wx.CURSOR_DEFAULT)
                    self.panel.SetCursor(my_cursor)

            self.panel = wx.Panel(self)

            box = wx.BoxSizer(wx.VERTICAL)

            icon = wx.Icon()
            icon.CopyFromBitmap(wx.Bitmap("icon.ico", wx.BITMAP_TYPE_ANY))
            self.SetIcon(icon)

            self.button = wx.Button(self.panel, wx.ID_ANY, 'Process Applications', size=(200, 50))
            self.button.Bind(wx.EVT_BUTTON, process_applications)
            self.list = wx.ListCtrl(self.panel, -1, style=wx.LC_REPORT)
            self.list.InsertColumn(0, "Student's Name", width=150)
            self.list.InsertColumn(1, 'Status', wx.LIST_FORMAT_CENTER, 100)
            self.list.InsertColumn(2, 'Confirmation #', wx.LIST_FORMAT_RIGHT, 100)
            box.Add(self.list, 1, wx.EXPAND)
            box.AddSpacer(5)
            box.Add(self.button, 1, wx.CENTER)
            box.AddSpacer(5)
            self.panel.SetSizer(box)
            self.panel.Fit()
            self.Centre()
            self.Show(True)

    if __name__ == '__main__':
        ex = wx.App()
        MainWindow(None, 'NCCCO Application Process')
        ex.MainLoop()


text:
Q: `Gem.find_files` interacts with itself Suppose I have not installed a certain gem, let's say "oj". If I do the following, then the gem will be installed, and Gem.find_files at the end returns the paths where it was installed.
require "open3"
name = "oj"
_, out, err, thread = Open3.popen3("sudo gem install #{name}")
thread.join
puts out.read, err.read
p Gem.find_files(name)

However, if I (uninstall the gem and) run the following, which has an extra line of Gem.find_files(name) before the occurrence of the same call at the end,
require "open3"
name = "oj"
if Gem.find_files(name).empty?
  _, out, err, thread = Open3.popen3("sudo gem install #{name}")
  thread.join
  puts out.read, err.read
  p Gem.find_files(name)
end

then Gem.find_files at the end returns an empty array. It seems that the first call of Gem.find_files (before installation) makes the second call of Gem.find_files (after installation) return an empty array.

*

*Why does it return an empty array?

*How can I fix either or two occurrences of Gem.find_files so that the first one (before installation) returns an empty array and the latter one (after installation) returns the included paths?

A: The first time you call find_files the Gem code caches a bunch of info, including the current gem specs and their directories.
The second time you call find_files, the Gem code uses the same cached info, so doesn't know your new gem is added.
The solution is install your new gem, then reset the cache like this:
Gem::Specification.reset


text:
Q: Play framework 2.2.1 Can not run application - "PAGE DOES NOT EXISTS" I have tried to run existing play application, it compiles and runs correctly (without errors in the console).
But when I opened home page (http://localhost:9000/):
PAGE DOES NOT EXISTS message is displayed.
Also I found in the debug logs messsage:
[application]-[ERROR] - [play-akka.actor.default-dispatcher-12] - SessionElements: Brand Exception Unique expecting 0 or 1 rows but got [18].
Could someone explain what does this message mean?
Also good to know, should be used only play run for project start or something else?
Console output:
--- (Running the application from SBT, auto-reloading is enabled) ---

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/C:/MyProject/lib/logback_classic.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/C:/play-2.2.1/repository/local/ch.qos.logback/logback-classic/1.0
.13/jars/logback-classic.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]
[info] play - Listening for HTTP on /0:0:0:0:0:0:0:0:9000

(Server started, use Ctrl+D to stop and go back to the console...)

[info] application - Cobrand details added into UserSession from ConfigurationFile
[info] application - Config loaded.
09:25:34,485 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback.groovy]
09:25:34,485 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback-test.xml]
09:25:34,485 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Found resource [logback.xml]
at [jar:file:/C:/play-2.2.1/repository/local/com.typesafe.play/play_2.10/2.2.1/jars/play_2.10.jar!/logback.xml]
09:25:34,485 |-INFO in ch.qos.logback.core.joran.spi.ConfigurationWatchList@1383357 - URL [jar:file:
/C:/play-2.2.1/repository/local/com.typesafe.play/play_2.10/2.2.1/jars/play_2.10.jar!/logback.xml] is not of type file
09:25:34,563 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - debug attribute not set
09:25:34,610 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate append
er of type [ch.qos.logback.core.ConsoleAppender]
09:25:34,610 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [STDOUT]

09:25:34,626 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default t
ype [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
09:25:34,641 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOT
logger to ERROR
09:25:34,641 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named
 [STDOUT] to Logger[ROOT]
09:25:34,641 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.
09:25:34,641 |-INFO in ch.qos.logback.classic.joran.JoranConfigurator@b29b88 - Registering current c
onfiguration as safe fallback point
09:25:34,657 |-INFO in ch.qos.logback.core.joran.spi.ConfigurationWatchList@1315e - URL [jar:file:/C
:/play-2.2.1/repository/local/com.typesafe.play/play_2.10/2.2.1/jars/play_2.10.jar!/logger.xml] is n
ot of type file
09:25:34,657 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - debug attribute not set
09:25:34,657 |-INFO in ch.qos.logback.core.joran.action.ConversionRuleAction - registering conversio
n word coloredLevel with class [play.api.Logger$ColoredLevel]
09:25:34,657 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate append
er of type [ch.qos.logback.core.FileAppender]
09:25:34,657 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [FILE]
09:25:34,657 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default t
ype [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
09:25:34,657 |-INFO in ch.qos.logback.core.FileAppender[FILE] - File property is set to [C:\MyProject/l
ogs/application.log]
09:25:34,657 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate append
er of type [ch.qos.logback.core.ConsoleAppender]
09:25:34,657 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [STDOUT]

09:25:34,657 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default t
ype [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
09:25:34,657 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [play] to INFO
09:25:34,657 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [application] to DEBUG
09:25:34,657 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [com.avaje.ebean.config.PropertyMapLoader] to OFF
09:25:34,657 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [com.avaje.ebeaninternal.server.core.XmlConfigLoader] to OFF
09:25:34,657 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [com.avaje.ebeaninternal.server.lib.BackgroundThread] to OFF
09:25:34,657 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [com.gargoylesoftware.htmlunit.javascript] to OFF
09:25:34,657 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOTlogger to ERROR
09:25:34,657 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [STDOUT] to Logger[ROOT]
09:25:34,657 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [FILE] to Logger[ROOT]
09:25:34,657 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.
09:25:34,657 |-INFO in ch.qos.logback.classic.joran.JoranConfigurator@501773 - Registering current c
onfiguration as safe fallback point
09:28:48,426 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - debug attribute not set
09:28:48,481 |-INFO in ch.qos.logback.core.joran.action.ConversionRuleAction - registering conversio
n word coloredLevel with class [play.api.Logger$ColoredLevel]
09:28:48,481 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate append
er of type [ch.qos.logback.core.FileAppender]
09:28:48,481 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [FILE_PLAY]
09:28:48,481 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default t
ype [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
09:28:48,482 |-INFO in ch.qos.logback.core.FileAppender[FILE_PLAY] - File property is set to [C:\MyProject/logs/application.log]
09:28:48,482 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate append
er of type [ch.qos.logback.core.ConsoleAppender]
09:28:48,482 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [STDOUT]

09:28:48,483 |-ERROR in ch.qos.logback.core.joran.spi.Interpreter@13:16 - no applicable action for [
pattern], current ElementPath  is [[configuration][appender][encoder][pattern]]
09:28:48,483 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate append
er of type [ch.qos.logback.core.rolling.RollingFileAppender]
09:28:48,484 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [FILE_DEBUG]
09:28:48,486 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default t
ype [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
09:28:48,495 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - No compression will be used
09:28:48,496 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - Will use the pattern C:/MyProject/lo
gs/debug_log.%d{yyyy-MM-dd_HH}.log for the active file
09:28:48,499 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - The date p
attern is 'yyyy-MM-dd_HH' from file name pattern 'C:/MyProject/logs/debug_log.%d{yyyy-MM-dd_HH}.log'.
09:28:48,499 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Roll-overat the top of every hour.
09:28:48,501 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Setting in
itial period to Sat May 19 09:28:48 EEST 2018
09:28:48,502 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[FILE_DEBUG] - Active log file
 name: C:/MyProject/logs/debug_log.2018-05-19_09.log
09:28:48,502 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[FILE_DEBUG] - File property is set to [null]
09:28:48,502 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate append
er of type [ch.qos.logback.core.rolling.RollingFileAppender]
09:28:48,502 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [FILE_WARN]
09:28:48,503 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default t
ype [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
09:28:48,504 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - No compression will be used
09:28:48,504 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - Will use the pattern C:/MyProject/lo
gs/warn_log.%d{yyyy-MM-dd}.log for the active file
09:28:48,504 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - The date p
attern is 'yyyy-MM-dd' from file name pattern 'C:/MyProject/logs/warn_log.%d{yyyy-MM-dd}.log'.
09:28:48,504 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Roll-overat midnight.
09:28:48,504 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Setting in
itial period to Sat May 19 09:28:48 EEST 2018
09:28:48,504 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[FILE_WARN] - Active log file
name: C:/MyProject/logs/warn_log.2018-05-19.log
09:28:48,504 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[FILE_WARN] - File property is set to [null]
09:28:48,504 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate append
er of type [ch.qos.logback.core.rolling.RollingFileAppender]
09:28:48,504 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [FILE_ERROR]
09:28:48,504 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default t
ype [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
09:28:48,505 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - No compression will be used
09:28:48,505 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - Will use the pattern C:/MyProject/lo
gs/ERROR/error_log.%d{yyyy-MM-dd_HH}.log for the active file
09:28:48,506 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - The date p
attern is 'yyyy-MM-dd_HH' from file name pattern 'C:/MyProject/logs/ERROR/error_log.%d{yyyy-MM-dd_HH}.log'.
09:28:48,506 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Roll-over
at the top of every hour.
09:28:48,506 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Setting in
itial period to Sat May 19 09:28:48 EEST 2018
09:28:48,506 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[FILE_ERROR] - Active log file
 name: C:/MyProject/logs/ERROR/error_log.2018-05-19_09.log
09:28:48,506 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[FILE_ERROR] - File property i
s set to [null]
09:28:48,506 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate append
er of type [ch.qos.logback.classic.db.DBAppender]
09:28:48,509 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [DB]
09:28:48,856 |-INFO in ch.qos.logback.core.db.DriverManagerConnectionSource@33aa43 - Driver name=MySQL-AB JDBC Driver
09:28:48,856 |-INFO in ch.qos.logback.core.db.DriverManagerConnectionSource@33aa43 - Driver version=
mysql-connector-java-5.1.18 ( Revision: tonci.grgin@oracle.com-20110930151701-jfj14ddfq48ifkfq )
09:28:48,856 |-INFO in ch.qos.logback.core.db.DriverManagerConnectionSource@33aa43 - supportsGetGeneratedKeys=true
09:28:48,893 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [application] to DEBUG
09:28:48,893 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [DB] to Logger[application]
09:28:48,893 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [application] to DEBUG
09:28:48,893 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [FILE_DEBUG] to Logger[application]
09:28:48,893 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [FILE_WARN] to Logger[application]
09:28:48,893 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [FILE_ERROR] to Logger[application]
09:28:48,893 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [play] to INFO
09:28:48,893 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [FILE_PLAY] to Logger[play]
09:28:48,893 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOTlogger to INFO
09:28:48,893 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [STDOUT] to Logger[ROOT]
09:28:48,893 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.
09:28:48,893 |-INFO in ch.qos.logback.classic.joran.JoranConfigurator@1ef40eb - Registering currentconfiguration as safe fallback point

warning log file output:
2018-05-19 09:23:59,382 [application]-[ERROR] - [play-akka.actor.default-dispatcher-7] - SessionElements: Brand Exception Unique expecting 0 or 1 rows but got [18]
2018-05-19 09:23:59,463 [application]-[ERROR] - [play-akka.actor.default-dispatcher-7] - SessionElements: Brand Exception Unique expecting 0 or 1 rows but got [18]
2018-05-19 09:23:59,501 [application]-[WARN] - [play-akka.actor.default-dispatcher-7] - SessionElements:  Provider Exception null
2018-05-19 09:23:59,555 [application]-[ERROR] - [play-akka.actor.default-dispatcher-7] - SessionElements: Brand Exception Unique expecting 0 or 1 rows but got [18]
2018-05-19 09:23:59,596 [application]-[ERROR] - [play-akka.actor.default-dispatcher-7] - SessionElements: Brand Exception Unique expecting 0 or 1 rows but got [18]
2018-05-19 09:25:01,634 [application]-[ERROR] - [play-akka.actor.default-dispatcher-9] - SessionElements: Brand Exception Unique expecting 0 or 1 rows but got [18]
2018-05-19 09:25:01,755 [application]-[ERROR] - [play-akka.actor.default-dispatcher-9] - SessionElements: Brand Exception Unique expecting 0 or 1 rows but got [18]

The issue was with application configuration, so I just added 127.0.0.1:9000 to database and all works correct. It was strange for me, that if localhost is not associated with user in the datapase then displays error page. But someone wrote it.
  Thanks for responses!

A: It may also be related to cookies session of your project, look at application.conf and check out the cookies session/flash config, database config and such.
Answering your other question, sometimes you need to pass other specific configuration file like
run -Dconfig.resources = otherconfigfilename.conf, or application secret key like
run -Dplay.http.secret.key="fnglksjgajadljglaj",
but for simpler projects sbt run does the trick


text:
Q: symfony4 - What to use instead of Bundles? The symfony4 documentation states that you shouldn't use Bundles in your main code anymore:

In Symfony versions prior to 4.0, it was recommended to organize your
own application code using bundles. This is no longer recommended and
bundles should only be used to share code and features between
multiple applications.

Any ideas how I can organize my code instead?
I think about having 200 entities. When they live all on the same level inside the Entity dir... that's a f****ing chaos!
Maybe namespacing/subfoldering?
PS: In django I'd think in the term of an app.

A: yes, I think organize your entity by domain is a good solution. Like Entity\Shop, Entity\Forum. This is also applicable to controllers, views, etc


text:
Q: Recovering a deleted 128-bit encrypted .dmg file I need to recover a recently deleted 15 GB .dmg file, which was deleted from a drive which is otherwise not in use. It should be easy to recover, but neither Data Rescue 3 nor Disk drill seem to find anything. I made sure .dmg is scanned for in the file types, but the file is not showing up after a deep scan.
How can i recover this .dmg file?
I'm on a Mac, the drive is an SSD (HFS+), the OS is OSX Yosemite 10.10.4


text:
Q: What are x and y values after the invocation of foo()? var x = 'hello';
var x = 'world';

function foo(){
    var y = x = 'hello from foo';
}
foo();

Is it x = 'hello from foo', y = 'hello from foo'?

A: With your code, x is 'hello from foo', y is undefined.
In foo, you assigned 'hello from foo' to the global variable x, and then assigned it x to the local variable y.


text:
Q: parsing JSON data I am getting this response in $.ajax success method.
{\"ID\":18,"TSName":"testSuit"}

How can I parse it like
success: function (response) {
  var tr = response.d;
  alert(tr.TSName);

A: Check out the dataType option of jQuery's .ajax call. If you specify JSON, jQuery will parse it for you in to the object you're looking for.
Alternatively, you can pass the data to .parseJSON and you will get a JSON object back.

A: test this:
$.getJSON('yoururl', function(data) {
  ...
});


text:
Q: CSS(3) columns, multiple ul's i'm working on a horizontal scrolling site. The elements on the site are al placed in a UL > LI structure, to create multiple blocks.
The problem that i am having is the i want 2 sets of UL after eachother, but they will overlap. Tried searching for this on the internet, but none have made what i did.
And example of what i trying to do can be found here: http://jsfiddle.net/DHbtx/2/
There you will see that the 2 UL overlap because of the "float: left" and no block elements. i have tried adding an :after pseudo element, but didn't work (from: Multi-column issue with horizontal scroll)
li:last-of-type:after {
  content: '';
  display: block;
  width: 15px;
  height: 1px;
  float: right;
  margin-right: -15px;
  margin-top: -1px;
}

Could anyone help me with this problem? I really appreciate any help you can provide.

A: Try giving the ul elements a width, say 50%.
ul
{
  width: 50%;
  ...
}

FIDDLE


text:
Q: How to call this.props from children class? So I make a gallery for my app that allows user to get images from their social media account. I use Redux for my app..and I already save facebook ID and TOKEN on my app store when the user login. I have no problem when I called this.props.fbLoginData.TOKEN from parent class.. however I always get

undefined is not an object(evaluating 'this.props.fbLoginData.TOKEN')

when I called this.props from my children class.
here is my Gallery(Parent) class:
_renderScene = ({ route }) => {
switch (route.key) {
case '1':
  return <View style={styles.page} />;
case '2':
  return <View style={styles.page} />;
case '3':
  return <FBPhotos />;
default:
  return null;
}
};

render() {
return (
  <TabViewAnimated
    style={[ styles.container, this.props.style ]}
    navigationState={this.state}
    renderScene={this._renderScene}
    renderHeader={this._renderHeader}
    onRequestChangeTab={this._handleChangeTab}
    initialLayout={initialLayout}
  />
);

}
}
and here is my fbPhotos class
componentWillMount(){
//this._facebookPhotoIDs();
fbToken = this.props.fbLoginData.TOKEN;
}

render(){
return (
 prop to style the items.
  <ListView contentContainerStyle={styles.list}
    dataSource={this.state.dataSource}
    renderRow={this._renderRow}
  />
);
}

I've tried to bind this.props.fbLoginData.TOKEN but it will become empty.
How can I get fbLoginData state from fbPhotos class?

A: In your renderScene method :
_renderScene = ({ route }) => {
  switch (route.key) {
    case '1':
      return <View style={styles.page} />;
    case '2':
      return <View style={styles.page} />;
    case '3':
      return <FBPhotos fbLoginData={this.props.fbLoginData} />;
    default:
      return null;
  }
};


text:
Q: Home directory vs Working directory In unix like systems what is the difference between a home directory and working directory ?

A: The home directory is a directory associated with a user name in the system's user account database. It's the 6th field in the entry returned by getent passwd some-user.
When you log in, the HOME environment variable is initialized from that value and applications use that variable or query the user database to know what your home directory is.
That directory is usually owned and writable by the corresponding user, and it's typically where applications store the user settings and where the user stores their files.
In shells, ~ expands to your home directory, and ~user to the home directory of user user.
The kernel has no notion of what a user name or home directory is. The home directory is entirely a user-space concept.
On the other hand, the working directory is an attribute of each process. It can be changed with the chdir(2)/fchdir(2) system calls (and the cd/pushd/popd commands in a shell) and queried using getcwd() or pwd in a shell. The current working directory is the base for finding a file using a relative path. A relative path (as in "foo/bar.txt") is relative to the current working directory of a process.
The working directory is inherited upon a fork and preserved upon execution of a command. For instance, ls lists the content of its working directory which is the same as the working directory of the shell that called it.
When a user logs in, the working directory of the first process that is run under his name is set to his home directory, and as a result, unless anything changes it, every process started under that login session will have the home directory as the current working directory.
shells don't start in the home directory, they start wherever the current directory was when they were executed, though shells started by a terminal emulator itself started by a window manager itself started by the login manager will likely start in the home directory since there's no reason why the window manager or terminal emulator would change their working directory.

A: A home directory is where most terminal emulators start when you open a shell. The working directory is where you are right now. You can usually go directly to the home directory with the command cd and you can find out what the working directory is with pwd.


text:
Q: Application Development for Windows CE I have a POS software and need to develop a collecting module for windows CE to run on a Honeywell Dolphin 6100 device.
I need to develop a simple application to run on a Honeywell 6100 device. This application should:

*

*Get a list of products (code, description and price) from my POS software

*Process Sales reading product's barcode showing Total due and number of items

*Upload that sale to my POS software (via network, files, or something like that)

What are my options? Are there any Application builder for Windows CE? If not what could I use to develop such application?

A: You have a few options, but few (if any) of them will allow you to create the application without writing code.  I'm aware of no "application builder" products that will get you there in Windows CE, and I've been working with CE for some time.  That's not to say some obscure thing might not exist, but I am not aware of one.

*

*You can write your application in .NET - either C# or VB.NET are supported - using the .NET Compact Framework (CF).  For that you will need Visual Studio 2008 Professional and really little else, other than a device.  There are lots of tutorials and online resources for CF development, so I won't put in a list of them here.

*You can write your application in C/C++. For this, again you'd want to use Visual Studio 2008 Professional.  Yes, there are options that use other compilers, but if you want to spend time actually writing the app and not building up a development tool chain and figuring out how to get it connected and debugging, then Visual Studio is the route you want.

*If you'd like a non-Microsoft solution, there are others that are supported to more or less of a degree. NS Basic has been around a long time, so it's probably pretty robust and has reasonable support.  I've never used it, but I've heard good things about it from those who have.

Anything else and you're a bit off the reservation.  Support will likely be minimal at best, tooling will likely not be robust, support, tutorials and all of the other goodness that developers often rely on to move forward will be scant.  You can likely get any language working under CE, given enough time and resources, but the options above are the most likely to lead to success.

A: Since you said you know Delphi and didn't want to learn another language, you can use Delphi Prism to write a client app to run on windows CE, pull the data you need, and post it to a webservice:
Is Delphi Prism a new version of Delphi .net?
http://en.wikipedia.org/wiki/Oxygene_(programming_language)
(edit) Just checked and it's now a part of this package:
http://www.embarcadero.com/products/rad-studio/faq


text:
Q: React-native onPress() event doesn't work in Android I am experiencing a very weird behaviour in my android emulator when using react-navigation v5 in my react native application, which makes me think is a bug. I found out that there is an open issue on the official react-native-navigation page. See here.
In every secondary screen (see UserProfileScreen below), in many react native-elements like TouchableOpacity Button or TextInput the onPress event doesn't work.  It only works in the main screen of the navigator.  (See HomeScreen below)
Here is an example of how I create my stack navigator:
import {createStackNavigator} from '@react-navigation/stack';

// some imports here

const HomeStackNavigator = createStackNavigator();
export const HomeNavigator = () => {
   return (
       <HomeStackNavigator.Navigator>
         <HomeStackNavigator.Screen name="HomeScreen" component={HomeScreen}/>
         <HomeStackNavigator.Screen name="UserProfileScreen" component={UserProfileScreen}/>
         <HomeStackNavigator.Screen name="UserSettingsScreen" component={UserSettingsScreen}/>
       </HomeStackNavigator.Navigator>
    )
};

As a PoC I have the same code in the main and secondary screen:
<TouchableOpacity
   onPress={() => Alert.alert("You pressed me!")} >
   <Text> touch me</Text>
</TouchableOpacity>

and I see the alert only in the main screen (HomeScreen).
If I make UserProfileScreen as the fist screen in my stack navigator above then it works (the onPress event) fine on this screen but not in the HomeScreen. So it seems that the onPress event is triggered only in the main screen!.  On IOS it works fine in all screens. Any idea ? Let me know if you need some more code snippets.