text:
Q: Want to table fit in the sheet How I make this table more attractive for the reader? (because the The reader cannot read the numbers of the table and I wanna want the table fit in the sheet).
\documentclass{article}
\usepackage{booktabs,array,tabularx,threeparttablex}
\usepackage{scalefnt}
\usepackage{mathtools,float}
\begin {document}
\subsubsection{Tabela que relaciona o per\'{i}odo com o comprimento do fio e
que cont\'{e}m o resultado de todas as m\'{e}dias e desvios padr\~{a}o para os
v\'{a}rios comprimentos do fio:}
\begin{table}[H]
\scriptsize
\centering
\scalefont{0.75}
\begin{tabular}{ccccccc}
\toprule
L - comprimento do fio (m) & M\'{e}dia do Per\'{i}odo (s) & Desvio Padr\~{a}o da
m\'{e}dia & N$^{\circ}$ contagens & Per\'{i}odo ao quadrado ($s^2$) &
$log\;L$ & $log\;T$\\
\midrule
0 & 0 & & & 0\\
\hline 0,4500 & 1,5278 & 1E-04 & 16 & 1,8616 & -0,7985 & 0,3107\\
\hline 0,5750 & 1,5280 & 1E-04 & 18 & 2,3345 & -0,5534 & 0,4239\\
\hline 0,6550 & 1,5278 & 1E-04 & 9 & 2,6576 & -0,4231 & 0,4887\\
\hline 0,7100 & 1,5281 & 5E-04 & 33 & 2,8917 & -0,3425 & 0,5309\\
\hline 0,7550 & 1,5276 & 1E-04 & 17 & 3,0804 & -0,2810 & 0,5625\\
\hline 0,8550 & 1,5282 & 4E-04 & 20 & 3,4767 & -0,1567 & 0,6230\\
\hline 0,9500 & 1,5294 & 1E-04 & 13 & 3,8310 & -0,0513 & 0,6716\\
\hline 1,0870 & 1,5273 & 2E-04 & 21 & 4,4019 & 0,0834 & 0,7409\\
\hline 1,1500 & 1,5278 & 1E-04 & 16 & 4,6393 & 0,1398 & 0,7673\\
\bottomrule
\end{tabular}
\begin{tablenotes}
\item[\textasteriskcentered] Nota: $log$ neste caso corresponde ao logaritmo neperiano
\end{tablenotes}
\caption{Representa\c{c}\~{a}o dos dados finais para todos os ensaios realizados do p\^{e}ndulo simples}
\end{table}
\end{document}

A: I would rotate the table. However, if you do not want to do that, I would do something like the following.

*

*Do not scale fonts, especially those which come in multiple optical sizes. The shape of the letters at smaller sizes is not the same as the shape at larger sizes. 0.75 of 12pt is not equivalent to 8pt. Computer Modern and Latin Modern both feature multiple optical sizes, as do other high quality font families. especially don't scale a font to 0.75 when it is already \scriptsize.

*Personally, I would not use the H specifier. If you don't want something to move, don't make it a float. You can use \captionof from caption or capt-of if you nonetheless need a caption. I let tables float, but \captionof is a perfectly reasonable alternative.

*Don't use an excess of horizontal lines.

*tabularx can be used with a custom X column specifier for the first 5 columns to get multiline headers, effectively.

*Use geometry to get less excessive margins and a larger \textwidth.
This produces something like the following:

I would also recommend aligning the columns according to the relevant number format. siunitx can help with this and with the correct typesetting of SI units and number formats generally.
\documentclass[letterpaper]{article}
\usepackage{geometry}
\usepackage{booktabs,array,tabularx,threeparttablex}
\usepackage{mathtools}
\newcolumntype{C}{>{\centering\arraybackslash}X}
\begin {document}
\subsubsection{Tabela que relaciona o per\'{i}odo com o comprimento do fio e que cont\'{e}m o resultado de todas as m\'{e}dias e desvios padr\~{a}o para os v\'{a}rios comprimentos do fio:}
\begin{table}
  \scriptsize
  \centering
  \begin{threeparttable}
  \begin{tabularx}{\textwidth}{*{5}{C}cc}
    \toprule
    L - comprimento do fio (m) & M\'{e}dia do Per\'{i}odo (s) & Desvio Padr\~{a}o da m\'{e}dia & N$^{\circ}$ contagens & Per\'{i}odo ao quadrado ($s^2$) & $log\;L$ & $log\;T$\\
    \midrule
    0 & 0 & & & 0\\
    0,4500 & 1,5278 & 1E-04 & 16 & 1,8616 & -0,7985 & 0,3107\\
    0,5750 & 1,5280 & 1E-04 & 18 & 2,3345 & -0,5534 & 0,4239\\
    0,6550 & 1,5278 & 1E-04 & 9 & 2,6576 & -0,4231 & 0,4887\\
    0,7100 & 1,5281 & 5E-04 & 33 & 2,8917 & -0,3425 & 0,5309\\
    0,7550 & 1,5276 & 1E-04 & 17 & 3,0804 & -0,2810 & 0,5625\\
    0,8550 & 1,5282 & 4E-04 & 20 & 3,4767 & -0,1567 & 0,6230\\
    0,9500 & 1,5294 & 1E-04 & 13 & 3,8310 & -0,0513 & 0,6716\\
    1,0870 & 1,5273 & 2E-04 & 21 & 4,4019 & 0,0834 & 0,7409\\
    1,1500 & 1,5278 & 1E-04 & 16 & 4,6393 & 0,1398 & 0,7673\\
    \bottomrule
  \end{tabularx}
  \begin{tablenotes}
    \item[\textasteriskcentered] Nota: $log$ neste caso corresponde ao logaritmo neperiano
  \end{tablenotes}
  \caption{Representa\c{c}\~{a}o dos dados finais para todos os ensaios realizados do p\^{e}ndulo simples}
  \end{threeparttable}
\end{table}
\end{document}


text:
Q: using preposition 'of' to mean 'possess' Is using the preposition 'of' in places where you want to say that the subject is possessing the 'something' which follows 'of' (basically an adjective) a common practice and correct?
example:

My girl of beautiful eyes and dark tresses showed up at the hall in her wedding dress.

The meaning intended: The girl has beautiful eyes and dark tresses.

A: Of:

made or consisting of; having:

*

*a woman of great charm

(Cambridge Dictionary)

A: It doesn't  really work with the example provided by the question, though I wouldn't rule out A girl of green eyes and ruddy complexion stepped forward.
Also consider some of the following:
Intangible things possessed:
Joseph wore a coat of many colours.
He was a man of very few words.
It turned out to be a day of very few surprises.
She was a player of great potential.
Tangible things:
Obama's memoirs are contained in a book of over 600 pages.
They found themselves in a field of sheep
A bottle of water, a tank of petrol, a hive of bees, a shelf of books, a line of cars
One could go on for a long time adding to this list, including tangible things. Hence I am finding it difficult to formulate a rule for what works and what doesn't. Perhaps the linguistics specialists know of one.
It doesn't seem to work with anatomical things, nor work as well with tangible things such as a car of white wheels, though one could say a car of white appearance.
One can say A man of 6ft 4inches was seen to enter the open door but not  a man of large ears sat in the chair.
But "of" following a noun to indicate possession is certainly alive and well in many everyday expressions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why are Hamilton's equations sometimes written with a gradient? I am used to seeing Hamilton's written as:
$$\frac{dq_j}{dt} = \frac{\partial H}{\partial p_j}\\
\frac{dp_j}{dt} = - \frac{\partial H}{\partial q_j}.$$
However I have also seen it written as
$$\frac{dq_j}{dt} = \nabla_{p_i} H\\
\frac{dp_j}{dt} = - \nabla_{q_i}H.$$
Why introduce the $\nabla$ here? I thought the first set of equations is already sufficiently general to $n$-dimensions. Or is this just a notational difference?
My best guess is that the latter is running the indices $i$ and $j$ over say an $n$-particle system, but is treating each $q_i$ and $p_i$ as a vector in $\mathbb{R}^3$.

A: Your best guess is correct. Let's take the example of an $N$ particle system in $\text{3D}$. If I wanted to define my generalized coordinates as just the position of each particle, then one way I could label them is:
$$q_1 = x_1, \quad q_2 = y_1, \quad q_3 = z_1, \quad q_4 = x_2\quad ,  ..., \quad q_{3N} = z_N.$$
In this case, I would write the equations of motion as
\begin{align}
&\dot{q}_j = \frac{\partial H}{\partial p_j}\\
&\dot{p}_j = - \frac{\partial H}{\partial q_j} \tag{1}
\end{align}
But, sometimes people like to bundle the coordinates for each particle into its own vector, i.e.
$$\mathbf{q}_1 = (x_1, y_1,z_1), \quad ,  ..., \quad \mathbf{q}_N = (x_N, y_N,z_N).$$
In this case, the equations of motion would be
\begin{align}
&\dot{\mathbf{q}}_j = \boldsymbol{\nabla}_{p_j} H\\
&\dot{\mathbf{p}}_j = -\boldsymbol{\nabla}_{q_j} H \tag{2}
\end{align}
so it's just a matter of convention.
Response to GiorgioP's Comment
To further clarify my point, suppose I have a system with an 8-dimensional phase space. Let's call some set of generalized coordinates for this system $q_1$, $q_2$, $q_3$ and $q_4$. I can just as well re-label these quantities as $\tilde{q}_{11} \equiv q_1$, $\tilde{q}_{12} \equiv q_2$, $\tilde{q}_{21} \equiv q_3$ and , $\tilde{q}_{22} \equiv q_4$. I'm just changing the way I'm referring to them. Then, Eq.$(1)$ would take the form
\begin{align}
&\dot{\tilde{q}}_{ij} = \frac{\partial H}{\partial {\tilde{p}}_{ij}}\\
&\dot{\tilde{p}}_{ij} = - \frac{\partial H}{\partial {\tilde{q}}_{ij}} \tag{3}
\end{align}
Now, if I wanted to, I could define the vectors $\mathbf{\tilde{q}}_j = (\tilde{q}_{1j},\tilde{q}_{2j})$, for $j \in \{1,2\}$, and then rewrite Eq.$(3)$ as
\begin{align}
&\dot{\mathbf{\tilde{q}}}_j = \boldsymbol{\nabla}_{\tilde{p}_j} H\\
&\dot{\mathbf{\tilde{p}}}_j = -\boldsymbol{\nabla}_{\tilde{q}_j} H \tag{4}
\end{align}
It's just a matter of notational convenience. For example, I might want to bundle together all generalized coordinates of each subsystem into a separate vector, so that I can keep track of them easier (E.g. it's easier to see that $q_{3x}$ is the $x$ position of the third particle rather than $q_{7}$ in my first example).
To clarify, none of this requires that the generalized coordinates are a-priori components of a vector. $q_1$ might be some angle and $q_2$ might be some length for some subsystem, and you might still find it convenient to work with $\mathbf{q} = (q_1,q_2)$ so that you have all coordinates of that subsystem in one collection. I'm also not claiming that you can always do this kind of re-labeling (other than the trivial way of having single-element vectors of course).

A: The simplest answer is, that it's a far more compact/applicable form of notation generalization, especially when dealing with various types of field theories (both classical or quantum).
In general, the Hamiltonian is used to probe all time-translational invariants of any given dynamical field theory; e.g. the canonical observables within phasespace, or the eigenvalue-spectrum for the time/energy- and position/momentum-observables, respectively. This basically means, that any physically measurable constants of motion, within any given dynamical system, are essentially all determined by the energy conservation requirement of Hamilton's equations.
And there exists a lot of different fundamental varieties of Hamilton's system of equations! Be they expressed as the Poisson bracket's symplectic behavior $\{H,\cdot\}$ in classical mechanics, or  as the (semi-simple) group-algebraic commutation relations for ergodic systems $[H,\cdot]$ in quantum mechanics. But my favorite version/application of Hamilton's equations is with out a doubt expressed as the Noether current in Liouville's theorem
\begin{align}
\frac{d\rho}{d t}&=\frac{\partial\rho}{\partial t}+\sum_{i=1}^N\left(\frac{\partial \rho}{\partial q_i}\dot{q}_i+\frac{\partial\rho}{\partial p_i}\dot{p}_i\right)\\
&=\frac{\partial\rho}{\partial t}+\sum_{i=1}^N\left(\frac{\partial \rho}{\partial q_i}\left(\frac{\partial H}{\partial p^i}\right)+\frac{\partial\rho}{\partial p_i}\left(-\frac{\partial H}{\partial q^i}\right)\right)\\
&=\frac{\partial\rho}{\partial t}+\nabla_{\bf{q}}\rho+\nabla_{\bf{p}}\rho=0
\end{align}
where the directional derivatives $\nabla_{\bf{q}}\rho=\nabla\rho\cdot\dot{\bf{q}}$ and $\nabla_{\bf{p}}\rho=\nabla\rho\cdot\dot{\bf{p}}$ are usually calculated using Greens- or Stokes theorem. My general point, however, is that the invariant Hamiltonian flow satisfies the condition
\begin{equation}
\frac{\partial\rho}{\partial t}=-\{\rho,H\}.
\end{equation}
I hope I didn't stray to far from the topic towards the end, but I wanted to answer you thoroughly. Otherwise, just comment, and I'll try to elaborate further.


text:
Q: When submitting a post via praw, how do I return the url of that post? I'm using the following code to submit a self post. Once that is submitted I would like the url to that post to be stored in a variable. I'm new to python and praw so i'm probably missing something obvious.
import praw

sub_reddit = 'test'
user_agent = 'user agent info'
post_title = 'post title text'
post_body = 'post body text'

r = praw.Reddit(user_agent=user_agent)

def login():
    r.login('USERNAME', 'PASSWORD')

def self_post():
    r.submit(sub_reddit, post_title, text=post_body)

login()
self_post()

Looking through the documentation I found this that states the return of .submit is as follows:

"The newly created Submission object if the reddit instance
  can access it. Otherwise, return the url to the submission.

If that is the case, how do I get that link? I can't run a lot of different test because the API has a limit on submissions so I keep getting blocked from trying new things.

A: return the response and assign it to a variable:
def self_post():
    return r.submit(sub_reddit, post_title, text=post_body)

login()
resp = self_post()

A: After you submit the link, you can use .short_link to get the URL to the submission:
submission = r.submit(sub_reddit, post_title, text=post_body)
submission.short_link


text:
Q: Undefined symbols when referencing static variable inside class The following code doesn't compile and I am not quite sure I understand why:
class A {
public:
    virtual ~A() {}
};

class B : public A {
public:
    virtual ~B() {}
    static B* I() { return &i_; }

protected:
    static B i_;
    explicit B() {}
};

int main() {
    A* a = B::I();
    (void)a;
    return 0;
}

Undefined symbols for architecture x86_64:
  "B::i_", referenced from:
      B::I() in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

The symbol should be accessible to the I() method, but it's not.

Apple LLVM version 9.1.0 (clang-902.0.39.2)

A: Add this to your .cpp's global scope to define the i_ static member:
B B::i_;


text:
Q: Python: 'unicode' object has no attribute 'append' while using pandas I have multiple excel sheets. I want to grab two cell values from a single sheet and make one excel sheet. Here is my code:
import pandas as pd
import numpy as np
import glob
import os
print glob.glob("C:/Users/admin/New folder/*.xlsx")
customer_name = pd.DataFrame()
customer_id= pd.DataFrame()
for f in glob.glob("C:/Users/admin/New folder/*.xlsx"):
    df = pd.read_excel(f,sheetname='Information')
    df1 = df.iloc[2,1]
    customer_name = customer_name.append(df1,ignore_index=True)
    df2 = df.iloc[2,2]
    customer_id = customer_name.append(df2,ignore_index=True)
result = customer_name.join(customer_id)
writer = pd.ExcelWriter('result.xlsx', engine='xlsxwriter')
result.to_excel(writer, sheet_name='Sheet1')
writer.save()

Error says:'unicode' object has no attribute 'append'
For code : customer_name = customer_name.append(df1,ignore_index=True)
I would like to write df1 and df2 in one excel sheet. It should look like this in excel sheet:
John    1514
Bill    5459
If someone can help.I am new to python and searched the forum but cannot find the solution. Thanks.


text:
Q: MySQL C# async methods doesn't work? i have a database in a server and it seems like the async method doesn't work.
Here is my code:
static async void Example()
{
    string connectionString =
        "Server=mydomainname.com;" +
        "Port=3306;" +
        "Database=scratch;" +
        "Uid=Assassinbeast;" +
        "Password=mypass123;" +
        "AllowUserVariables= true;";

    MySql.Data.MySqlClient.MySqlConnection sqConnection = new MySql.Data.MySqlClient.MySqlConnection(connectionString);
    await sqConnection.OpenAsync();

    Console.Write("Opened. Now Click to close");
    Console.ReadLine();

    sqConnection.Close();
}
static void Main(string[] args)
{
    Console.ReadLine();
    Example();
    Console.WriteLine("Done");
    Console.ReadLine();
}

At the "await" statement, its actually supposed to jump back to the Main() function and writeout "Done". But its not doing that. Its just running synchronously like it wasn't an async method and it will first write "Done" once the function is fully completed.
So what am i doing wrong? Is it a bug?
UPDATE
Okay, so after i got some answers, i actually still couldn't see any difference between the OpenAsync() and Open().
I began trying to test more things out and i think i can conclude that the async method DOES NOT WORK
Here is my new code:
static async Task Example()
{
    string connectionString =
        "Server=mydomainname.com;" +
        "Port=3306;" +
        "Database=scratch;" +
        "Uid=Assassinbeast;" +
        "Password=mypass123;" +
        "AllowUserVariables= true;";

    using (var sqConnection = new MySql.Data.MySqlClient.MySqlConnection(connectionString))
    {
        Console.WriteLine("Opening");
        await sqConnection.OpenAsync();
        Console.WriteLine("Opened. Now Closing");
    }
}
static async Task Example2()
{
    //Lets pretend this is a database that my computer will try to connect to

    Console.WriteLine("Opening");
    await Task.Delay(1000); //Lets say it takes 1 second to open
    Console.WriteLine("Opened. Now Closing");
}
static void Main(string[] args)
{
    Console.ReadLine();

    Task.Run(() => Example());
    Task.Run(() => Example());
    Task.Run(() => Example());
    Task.Run(() => Example());
    Task.Run(() => Example());
    Task.Run(() => Console.WriteLine("Done"));
    Console.ReadLine();
}

Here when i run the Example() 5 times, it will output like this:

It takes up to 3 seconds before it will write out "Done".
Note that my computer is not working on the CPU at all, because it is only waiting and connecting to the database which takes around 1 second to connect to.
So its actually blocking my computers thread and not running multithreaded, otherwise it would write out "Done" immediedtly.
So if i called Example2() instead of Example(), then i get this result which is what i want and what i would expect:

Here, it is true async method, because i can do over 6 things at a time on my computer which has only 2 cores.
But the first example, i could only do two things at a time because MySQL async method does not work.
I also tested it with sqConnection.Open(), which had the exact same result as sqConnection.OpenAsync()
So right now, i just cant figure out how to connect to the database 5 times at the same time.

A: Judging from some old code (6.7.2), it appears that the mysql ADO.NET provider does not implement any of the async functionality correctly. This includes the TAP pattern and the older style Begin..., End... async patterns. In that version, the Db* async methods appear to not be written at all; they would be using the base class ones in .NET which are synchronous and all look something like:
public virtual Task<int> ExecuteNonQueryAsync(...) {
    return Task.FromResult(ExecuteNonQuery(...));
}

(100% synchronous with the added overhead of wrapping it in a task; reference source here)
If the Begin and End versions were written correctly (they aren't) it could be implemented something like this:
public override Task<int> ExecuteNonQueryAsync(...) {
    return Task<int>.Factory.FromAsync(BeginExecuteNonQueryAsync, EndExecuteNonQueryAsync, null);
}

(reference source for that method for SqlCommand)
Doing this is dependent on some sort of callback api for the underlying socket to eventually deal with in a pattern where the caller sends some bytes over the socket and then a registered method gets called back from the underlying network stack when it is ready.
However, the mysql connector doesn't do this (it doesn't override that method in the first place; but if it did, the relevant begin and end methods aren't async on some underlying socket api). What the mysql connector does instead is build a delegate to an internal method on the current connection instance and invokes it synchronously on a separate thread. You cannot in the meantime for example execute a second command on the same connection, something like this:
private static void Main() {
    var sw = new Stopwatch();
    sw.Start();
    Task.WaitAll(
        GetDelayCommand().ExecuteNonQueryAsync(),
        GetDelayCommand().ExecuteNonQueryAsync(),
        GetDelayCommand().ExecuteNonQueryAsync(),
        GetDelayCommand().ExecuteNonQueryAsync(),
        GetDelayCommand().ExecuteNonQueryAsync(),
        GetDelayCommand().ExecuteNonQueryAsync(),
        GetDelayCommand().ExecuteNonQueryAsync(),
        GetDelayCommand().ExecuteNonQueryAsync(),
        GetDelayCommand().ExecuteNonQueryAsync(),
        GetDelayCommand().ExecuteNonQueryAsync(),
        GetDelayCommand().ExecuteNonQueryAsync(),
        GetDelayCommand().ExecuteNonQueryAsync());
    sw.Stop();
    Console.WriteLine(sw.Elapsed.Seconds);
}

private static DbCommand GetDelayCommand() {
    var connection = new MySqlConnection (...);
    connection.Open();
    var cmd = connection.CreateCommand();
    cmd.CommandText = "SLEEP(5)";
    cmd.CommandType = CommandType.Text;
    return cmd;
}

(assuming you are connection pooling and the number of tasks there is more than the maximum pool size; if async worked this code would get a number depending on the number of connections in the pool instead of a number depending on both that and the number of threads that can run concurrently)
This is because the code has a lock on the driver (the actual thing that manages the network internals; *). And if it didn't (and the internals were otherwise thread safe and some other way was used to manage connection pools) it goes on to perform blocking calls on the underlying network stream.
So yeah, no async support in sight for this codebase. I could look at a newer driver if someone could point me to the code, but I suspect the internal NetworkStream based objects do not look significantly different and the async code is not looking much different either. An async supporting driver would have most of the internals written to depend on an asynchronous way of doing it and have a synchronous wrapper for the synchronous code; alternatively it would look a lot more like the SqlClient reference source and depend on some Task wrapping library to abstract away the differences between running synchronously or async.
* locking on driver doesn't mean it couldn't possibly be using non-blocking IO, just that the method couldn't have been written with a lock statement and use the non-blocking Begin/End IAsyncResult code that could have been written prior to TAP patterns.
Edit: downloaded 6.9.8; as suspected there is no functioning async code (non-blocking IO operations); there is a bug filed here: https://bugs.mysql.com/bug.php?id=70111
Update July 6 2016: interesting project on GitHub which may finally address this at https://github.com/mysql-net/MySqlConnector (could probably use more contributors that have a stake in its success [I am no longer working on anything with MySql]).

A: Well, it could be that there's a pooled connection that's already open. In which case, it would be returned to you synchronously.
The thing to notice is that await does not necessarily return control back to the calling method. It only returns to the calling method if the status of the task being awaited is TaskStatus.Running. If the task has completed, then execution carries on as normal.
Try awaiting this method, which returns a task with status RanToCompletion:
public Task<int> SampleMethod()
{
    return Task.FromResult(0);
}

A: Avoid using void as return type in async methods. Async void is just meant for event handlers. All other async methods should return Task or Task<T>. Try this:
static async Task Example()
{
    string connectionString =
        "Server=mydomainname.com;" +
        "Port=3306;" +
        "Database=scratch;" +
        "Uid=Assassinbeast;" +
        "Password=mypass123;" +
        "AllowUserVariables= true;";

    MySql.Data.MySqlClient.MySqlConnection sqConnection = new MySql.Data.MySqlClient.MySqlConnection(connectionString);
    await sqConnection.OpenAsync();

    Console.Write("Opened. Now Click to close");
    Console.ReadLine();

    sqConnection.Close();
}
static void Main(string[] args)
{
    Console.ReadLine();
    Task.Run(() => Example()).Wait();
    Console.WriteLine("Done");
    Console.ReadLine();
}

UPDATE
As explained by dcastro, this is how async-await works:
If the awaited task hasn't finished and is still running, Example() will return to its calling method, thus the main thread doesn't get blocked. When the task is done then a thread from the ThreadPool (can be any thread) will return to Example() at its previous state and continue execution.
Or A second case would be that the task has already finished its execution and the result is available. When reaching the awaited task the compiler knows that it has the result and will keep on executing code on the very same thread.


text:
Q: Access to XMLHttpRequest blocked by CORS when sending data from front-end to back-end using POST Here is a bit of a background: I am making a full stack to-do list application. The front-end is based on React and Bootstrap. The backend is using Express, Node and MongoDB. The problem is that when I'm fetching the data from MongoDB using GET, I can view it on frontend. But when I'm sending the data using POST, I get this error:
Access to XMLHttpRequest at 'http://localhost:5035/api/todos' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I'm adding the required code files here.
Frontend
TodoTask.js
// Handles displaying components related to todo task list
import React, { useState, useEffect } from "react";
import TodoForm from "./TodoForm";
import TodoUpdate from "./TodoUpdate";
import axios from "axios";
function TodoTask() {
    //for the list of tasks
    const [todos, setTodos] = useState([]);
    //add task in the list of tasks
    const addTodo = async todo => {
        //check for empty input
        if (!todo.text || /^\s*$/.test(todo.text)) {
            return
        }
        const newTodos = [todo, ...todos];
        setTodos(newTodos);
        console.log(todos);
        try {
            await axios.post("http://localhost:5035/api/todos", {
             todo
            });
          } catch (error) {
            console.log(error);
          }

    }

    const ViewAllTodos = () => {
        useEffect(() => {
            getAllTodo();
        }, []);
    }

    const getAllTodo = async () => {
        const response = await axios.get("http://localhost:5035/api/todos");
        setTodos(response.data.Todo);
        console.log(response.data.Todo);
    }

    const updateTodo = (todoId, newValue) => {
        if (!newValue.text || /^\s*$/.test(newValue.text)) {
            return
        }

        setTodos(prev => prev.map(item => (item.id === todoId ? newValue : item)))
    }

    const removeTodo = id => {
        const remove = [...todos].filter(todo => todo.id !== id);
        setTodos(remove);

    }

    const completeTodo = id => {
        let updatedTodos = todos.map(todo => {
            if (todo.id === id) {
                todo.isComplete = !todo.isComplete;
            }
            return todo;
        });

        setTodos(updatedTodos);
    }

    const [message, setMessage] = useState('');

    return (

My To Do List Application

This is a basic to do list application with complete frontend and backend configuration. For details, check ReadMe.md of this project.

            {/* calling the form component to show a text field */}
            Enter your to do here:
            <TodoForm onSubmit={addTodo} />
            {/* checking if the list is empty, otherwise list all the todos with update and delete button */}
            {todos.length === 0 ?

The list is empty!
 :
                <TodoUpdate todos={todos} completeTodo={setTodos} removeTodo={removeTodo}
                    updateTodo={updateTodo} />
            }
            {/* {todos.length === 0 ?
Empty
 :
                todos.map((todo, index) => (

                      {todo.priority}
                      {todo.todo}

                  ))
            }        */}

    )
}

export default TodoTask;

Backend:
MongooseServer.js
// import dependencies
const express = require('express');
var bodyParser = require('body-parser');
const mongoose = require('mongoose');
const router = require('./routers/routes');
const cors = require('cors');
// const dbUrl = require('./config/db.config/url')
// set up dependencies

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/api/', router);

const corsOptions ={
  origin:'http://localhost:3000',
  credentials:true,            //access-control-allow-credentials:true
  optionSuccessStatus:200,
  methods: "GET, POST"
}

app.use(cors(corsOptions));
//app.use(cors());
// app.use(cors({
//   origin: 'http://localhost:3000',
// }))
// set up mongoose
mongoose.connect("mongodb://127.0.0.1:27017/mytodolist")
  .then(()=> {
    console.log('Database connected');
  })
  .catch((error)=> {
    console.log('Error connecting to database');
  });
// set up port
const port = 5035;
// set up route
app.get('/', (req, res) => {
  res.status(200).json({
    message: 'Welcome to todo list',
  });
});

app.listen(port, () => {
  console.log(`Our server is running on port ${port}`);
});

Model.js
const mongoose = require("mongoose");

const MyTodoListSchema = new mongoose.Schema({
taskId: {
    type: Number,
    required: true,
    unique: true
},
todo: {
type: String,
default: "",
required: true
},
priority: {
    type: String,
    default: "high",
    required: true
    },
});
const MyTodoList = mongoose.model("MyTodoList", MyTodoListSchema);
module.exports = MyTodoList;

Controller.js
// import mongoose from 'mongoose';
const mongoose = require('mongoose')
// import {MyTodoList} from '../models/model';
const MyTodoList = require('../models/model');

exports.createTodo = (req, res) => {
  app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "*");
    next();
});
  const todo = new MyTodoList({
    taskId: req.body.taskId,
    todo: req.body.todo,
    priority: req.body.priority,
  });
  return todo
    .save()
    .then((newTodo) => {
      return res.status(201).json({
        success: true,
        message: 'New todo list created successfully',
        MyTodoList: newTodo,
      });
    })
    .catch((error) => {
      res.status(500).json({
        success: false,
        message: 'Server error. Please try again.',
        error: error.message,
      });
    });
}

//get all todos
exports.getAllTodo = (req, res) => {
      res.setHeader("Access-Control-Allow-Origin", "*")
      res.setHeader("Access-Control-Allow-Credentials", "true");
      res.setHeader("Access-Control-Max-Age", "1800");
      res.setHeader("Access-Control-Allow-Headers", "content-type");
      res.setHeader( "Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, PATCH, OPTIONS" );
  MyTodoList.find()
    .select('taskId todo priority')
    // .then( () => {
    //   res.setHeader("Access-Control-Allow-Origin", "*")
    //   res.setHeader("Access-Control-Allow-Credentials", "true");
    //   res.setHeader("Access-Control-Max-Age", "1800");
    //   res.setHeader("Access-Control-Allow-Headers", "content-type");
    //   res.setHeader( "Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, PATCH, OPTIONS" );
    // })
    .then((allTodo) => {
      // const response = res.status(200).json( {
      //   success: true,
      //   message: 'A list of all todos',
      //   Todo: allTodo
      // });
      return res.status(200).json({
        // success: true,
        // message: 'A list of all todos',
        Todo: allTodo
      });
      // return response;
    })
    .catch((err) => {
      res.status(500).json({
        success: false,
        message: 'Server error. Please try again.',
        error: err.message,
      });
    });
  }

// module.exports = {createTodo, getAllTodo}

Route.js
const express = require("express");
const cors = require("cors");
const todolist_controller = require('../controllers/controller')
const app = express();
const router = express.Router();
router.post('/todos', todolist_controller.createTodo);
router.get('/todos', todolist_controller.getAllTodo);
module.exports = router;

Please guide me on what I'm doing wrong here.
The POST is working fine with Postman. I'm using the MVC pattern for the application. Also, the frontend and backend are two separate directories inside one main directory. Both are running on different ports. Frontend is running on port 3000 and backend on port 5035.
TIA! I'm stuck on this for day. Please help out here!

A: If you would like to whitelist for all API endpoints then cors middleware must be called before your route(and this recommended also) like following
const app = express();
const corsOptions ={
  origin:'http://localhost:3000',
  credentials:true,            //access-control-allow-credentials:true
  optionSuccessStatus:200,
  methods: "GET, POST"
}

app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use('/api/', router); // cors middleware must call before this line

A: Just use the cors middleware at the root of your api project with express for instance :
const cors = require('cors');
app.use(cors());


text:
Q: Extracting relationship status from Facebook in Python running on Google App Engine I'm working on a Facebook application. It's written in Python and running on Google App Engine (GAE).
I know how to get the relationship status of the users network, but the way I do it is running way to slow. There is a time limit on GAE in order to reduce CPU usage which is about 60 seconds. Using the following code I can get the relationship status of about 200 persons in that time frame, before getting the "DeadlineExceededError". Of course that is not good enough, since many/most people have a higher amount of friends on Facebook.
What I do now, is to get the friend list of the user, and then making an API call for each one asking for the name and relationship status.
The code I use:
for f in friends:
    friends_info[f] = facebook.api('/'+f, {u'fields': 'name,relationship_status',
    u'access_token': facebook.access_token})

And then I get the data with:
rel_status = friends_info[f][u'relationship_status']

What I need:
Suggestions for optimization or other ways to extract the relationship status of an entire network.
Thanks in advance :-)
EDIT :
The answers seems to be all good ways to solve my problem. Though, I couldn't find any good tutorials for batch request in Python, so I ended up using a FQL call. By using the following it takes 1-2 seconds to get the data:
Q = 'select uid, sex, relationship_status from user where uid in (select target_id from connection where source_id = me())'

And the actual data is retrieved by:
data = fql.query(Q,facebook.access_token)

which call this function:
def query(self,Q,access_token):
    ENDPOINT = 'https://api.facebook.com/method/'
    params = dict(query=Q, access_token=access_token, format='json')
    url = ENDPOINT + 'fql.query'
    return self._fetch(url, params=params)

def _fetch(self, url, params=None):
    conn = urllib2.urlopen(url, data=urlencode(params))
    try:
        return json.loads(conn.read())
    finally:
        conn.close()

Hope someone can make use of it as well!

A: Each app engine instance can have have max 10 parallel HTTP queries, so you could potentially make this 10 times faster with create_rpc & make_fetch_call. There are scenarios where this doesn't work either, so you need to split the job to several tasks and let them run in parallel.

A: You can use the facebook graph batch query API to query up to 20 users at once


text:
Q: Runtime error: ClassNotFound exception with Spark I want to run an OOTB example of Spark streaming (version 1.6) by itself, to build on it. I am able to compile and run the example as is, bundled with the other code samples.
I.e. :
 ./bin/run-example streaming.StatefulNetworkWordCount localhost 9999

However i am unable to do so (same code) in my own project.
Any help ?
build.sbt:
import sbtassembly.AssemblyKeys
name := "stream-test"

version := "1.0"

libraryDependencies += "org.apache.spark" %% "spark-core" % "1.6.0" % "provided"
libraryDependencies += "org.apache.spark" %% "spark-streaming-kafka" % "1.6.0"
libraryDependencies += "org.apache.spark" %% "spark-streaming" % "1.6.0"
libraryDependencies += "org.json4s" %% "json4s-native" % "3.2.10"

libraryDependencies += "org.scalatest" %% "scalatest" % "2.2.4" % "test"

assemblyJarName in assembly := "stream_test_" + version.value + ".jar"

assemblyMergeStrategy in assembly := {
  case PathList("org", "apache", xs @ _*) => MergeStrategy.last
  case PathList("com", "google", xs @ _*) => MergeStrategy.last
  case PathList("com", "esotericsoftware", xs @ _*) => MergeStrategy.last
  case x =>
    val oldStrategy = (assemblyMergeStrategy in assembly).value
    oldStrategy(x)
}

assemblyOption in assembly := (assemblyOption in assembly).value.copy(includeScala = false)

This compiles fine. However, getting an error upon running:
(note that i am using spark 1.6 to run this):
    $ ../../../app/spark-1.6.0-bin-hadoop2.6/bin/spark-submit --jars /app/spark-streaming_2.11-1.6.0.jar   --master local[4] --class "StatefulNetworkWordCount"    ./target/scala-2.10/stream-test_2.10-1.0.jar localhost 9999
    Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
    16/02/10 22:16:30 INFO SparkContext: Running Spark version 1.4.1
    2016-02-10 22:16:32.451 java[86932:5664316] Unable to load realm info from SCDynamicStore
    16/02/10 22:16:33 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
   ..
    16/02/10 22:16:39 INFO Utils: Successfully started service 'sparkDriver' on port 60720.
    16/02/10 22:16:40 INFO SparkEnv: Registering MapOutputTracker
    16/02/10 22:16:40 INFO SparkEnv: Registering BlockManagerMaster

    16/02/10 22:16:42 INFO SparkUI: Started SparkUI at http://xxx:4040
    16/02/10 22:16:43 INFO SparkContext: Added JAR file://app/spark-streaming_2.11-1.6.0.jar at http://xxx:60721/jars/spark-streaming_2.11-1.6.0.jar with timestamp 1455171403485
    16/02/10 22:16:43 INFO SparkContext: Added JAR file:/projects/spark/test/./target/scala-2.10/stream-test_2.10-1.0.jar at http://xxx:60721/jars/stream-test_2.10-1.0.jar with timestamp 1455171403562
    16/02/10 22:16:44 INFO Executor: Starting executor ID driver on host localhost
    16/02/10 22:16:44 INFO Utils: Successfully started service 'org.apache.spark.network.netty.NettyBlockTransferService' on port 60722.
  ..
    16/02/10 22:16:44 INFO BlockManagerMaster: Registered BlockManager
    Exception in thread "main" java.lang.NoSuchMethodError: org.apache.spark.streaming.dstream.PairDStreamFunctions.mapWithState(Lorg/apache/spark/streaming/StateSpec;Lscala/reflect/ClassTag;Lscala/reflect/ClassTag;)Lorg/apache/spark/streaming/dstream/MapWithStateDStream;
        at StatefulNetworkWordCount$.main(StatefulNetworkWordCount.scala:50)
        at StatefulNetworkWordCount.main(StatefulNetworkWordCount.scala)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:665)
        at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:170)
        at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:193)
        at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:112)
        at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)

This method is in the Jar's class, so i dont understand ..

A: Found the answer ..
Even though i was running spark-submit from 1.6, my SPARK_HOME was still pointing to the previous version of Spark, 1.4.
So setting SPARK_HOME to the 1.6 version instead, same as the spark-submit to run the code, solved the problem.


text:
Q: Why does this code save the screenshot as bmp not gif, and why doesn't it save the whole area? I have a timer tick event set to 250ms:
private void timer4_Tick(object sender, EventArgs e)
{
    if (pictureboximagestosavecount == 72)
    {
        timer4.Enabled = false;
    }
    else
    {
        Bitmap bmp = new Bitmap(this.Width, this.Height);
        Rectangle rect = new Rectangle(this.Location.X, this.Location.Y, this.Width, this.Height);
        pictureboximagestosavecount++;
        savePictureBox(pictureBox1, @"c:\temp\pboximages\" + pictureboximagestosavecount.ToString("D6") + "pbimg.gif");
        this.DrawToBitmap(bmp, rect);
        bmp.Save(@"c:\temp\pboximages\" + pictureboximagestosavecount.ToString("D6") + "form.gif");
    }
}

First I'm saving the pictureBox as gif using the method savePictureBox.
Second I save the form1:
bmp.Save(@"c:\temp\pboximages\" + pictureboximagestosavecount.ToString("D6") + "form.gif");

After timer4 is stopped I have abutton click event where I create animated gif from the saved files:
private void animatedgifbutton_Click(object sender, EventArgs e)
{
    DirectoryInfo di1;
    FileInfo[] fi1;
    di1 = new DirectoryInfo(@"c:\temp\pboximages\");
    fi1 = di1.GetFiles("*form.gif");
    List<string> newImages = new List<string>();
    for (int i = 0; i < fi1.Length; i++)
    {
        newImages.Add(fi1[i].FullName);
    }
    animatedgif.MakeGIF(newImages, @"c:\temp\pboximages\animated1.gif", 6, true);
}

When I'm doing *.form.gif and I see in the List newImages only the form gifs files the animatedgif.MakeGIF throw error since it need to get List of gifs files but I guess that when I save the form it's saving it as bitmap and not real gif.
How can I take a screenshot of form1 and save it as real gif ?
When I save the pictureBox1 to the hard disk it is GIF and there are no problems.
The problem is with saving the form.
EDIT:
I also saw now that the way I'm saving a screenshot of the form1 is not good it's not saving the whole form area only part of it. I gues using this bmp and rect is not good.
This is what I get for example when I'm saving a screenshot of the form:

In other words I need in timer4 tick event to save the form screen the whole form to the hard disk as a gif file real gif file not bmp.

A: It doesn't save as a proper GIF because you don't tell it to. The extension is not enough, you need to add the ImageFormat to the Save call!
And it doesn't save the whole area of the Form because you don't use the right Rectangle to control it.
Both issues go away very simply if you use the modified savePictueBox function:
void saveControl(Control Ctl, string fileName)
{
    Rectangle Rect = Ctl.ClientRectangle;
    // if (Ctl is Form) Rect = Ctl.Bounds; // (*)
    using (Bitmap bmp = new Bitmap(Rect.Width, Rect.Height))
    {
        Ctl.DrawToBitmap(bmp, Rect );
        bmp.Save(fileName, System.Drawing.Imaging.ImageFormat.Gif);
    }
}

Note that this uses the ClientRectangle, that is, it leaves out the Form border. If you want if to include the Border you can uncomment the line (*)
Now you can call it as
saveControl(pictureBox1, yourFileName);

and as
saveControl(this, yourOtherFileName);

Two notes on Animated Gifs:

*

*Since you are recording the Gifs in real-time don't try to create the animation at the same time!

*I found this post interesting. fireydude's answer does work, once you have included all those references from the WPF world..Not sure how to get the best quality and unfortunately there is no control over the timing, so far..


text:
Q: AWS S3 action to permit redirect edits in website enabled bucket I want to allow our web developer to change redirect rules on a specific website enabled bucket, using AWS console.
What policy permissions would I have to add? They can manage objects in the bucket already, but I am not sure what specific action to add to let them change redirect XML.
Here's the current policy:
{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Action": "s3:ListAllMyBuckets",
        "Resource": "arn:aws:s3:::*"
    },
    {
        "Effect": "Allow",
        "Action": [
            "s3:GetObject",
            "s3:PutObject",
            "s3:DeleteObject"
        ],
        "Resource": [
            "arn:aws:s3:::staging.site.com",
            "arn:aws:s3:::staging.site.com/*",
        ]
    }
]

}

A: All web site hosting-related configuration is on the /?website subresource, which (technically speaking) is completely overwritten, each time it is changed.  This includes...

[...] website configuration information such as the file name of the index document and any redirect rules.
This PUT operation requires the S3:PutBucketWebsite permission.
http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTwebsite.html


text:
Q: Wait for chain of AJAX calls to complete I have a function that calls other functions which have AJAX requests. I want all of the AJAX calls to complete before calling the last function. I initialize an array and need all of the AJAX calls to have successfully completed before going to the last step. When I run the code in the browser the console is showing the last method being called before the first AJAX call is completed. I've tried using .done however I'm still getting the same result.
function Search() {
       var userIds = [];
       var certName = $('#certificationName').val();
       var skillNumberOne = $('#skillName1').val();
       var skillNumberTwo = $('#skillName2').val();
       var skillNumberThree = $('#skillName3').val();
       var locale = $('#location').val();
       CertMatchResults(certName, userIds);
       SkillMatchResults(skillNumberOne, userIds);
       SkillMatchResults(skillNumberTwo, userIds);
       SkillMatchResults(skillNumberThree, userIds);
       LocationMatchResults(locale, userIds);
       console.log(userIds);
       DisplayMatches(userIds);
    }

    function CertMatchResults(certName, userIds) {
       if (certName == '') return;
       $.getJSON('json_data.php', { method: 'matchCerts', certName: certName }, function(data) {
          $.each(data, function(key, value) {
             console.log("Cert Match >>> " + value.user_id);
             userIds.push(value.user_id);
          });
       }).done(function() {
          console.log("Cert match completed.");
       });
    }

    function SkillMatchResults(skillName, userIds) {
       if (skillName == '') return;
       $.getJSON('json_data.php', { method: 'matchSkill', skillName: skillName }, function(data) {
          $.each(data, function(key, value) {
             console.log("Skill Match >>> " + value.user_id);
             userIds.push(value.user_id);
          });
       });
    }
... other calls below ... I can add them if needed

DisplayMatches needs all of the AJAX calls in each of the functions before it to complete.

A: You should create a chain of deferred objects.
Each ajax call returns Deferred object and then you can gather them in jQuery.when function and invoke the last function once all the ajax calls resolved their promises in jQuery.then function.
$.when( $.getJson("url1"), $.getJson("url2") ).then(function( valueFromUrl1, valueFromUrl2 ) {
  functionThatShouldBeInvokedLast();
});

A: Have all functions call the DisplayMatches when they are done and check the userIDs array if it is complete ... and when it is you know all is done so you just run it, if not, exit


text:
Q: Save associations with Cakephp 3 I have a problem with CakePHP 3 and saving new entity and its associations with one operation.
In my opinion I do it like recommended in the documentation.
Here my controller:
$articles = TableRegistry::get('Articles');
$article = $articles->newEntity($this->request->data);

if ($this->request->is('post')) {

    $valid = $articles->validate($article, [
        'associated' => ['Topics']
    ]);

    if ( $valid ) {
        $articles->save($article, [
            'validate' => false,
            'associated' => ['Topics']
        ]);
    }
}

Thats my models:
class ArticlesTable extends Table {
    public function initialize(array $config) {
        $this->primaryKey('article_id');
        $this->belongsTo ( 'Topics', [
            'targetForeignKey'  => 'topic_id'
        ]);
    }
}

class TopicsTable extends Table {
    public function initialize(array $config) {
        $this->primaryKey('topic_id');
        $this->hasMany ( 'Articles', [
            'targetForeignKey'  => 'article_id'
        ]);
}

And this is my database:
CREATE TABLE `articles` (
  `article_id` int(11) NOT NULL AUTO_INCREMENT,
  `topic_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`article_id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=latin1;

CREATE TABLE `topics` (
  `topic_id` int(11) NOT NULL AUTO_INCREMENT,
  `topic_title` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`topic_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

MY form looks like that:
<input type="text" id="articles-heading" maxlength="45" required="required" name="Articles[heading]">
<input type="text" id="articles-topics-topic-title" list="topics" name="Articles[Topics][topic_title]">

I want to create a form which contains all the associations and save it with one request.

A: Missing columns
There is no column named heading in your articles table.
Invalid foreign key configuration
Your configuration looks wrong, targetForeignKey is for BelongsToMany associations, and article_id (the primary key of the other table) is not the foreign key in an Topic hasMany Comment association, it's topic_id, and it's not necessary to specify it when you're following the naming conventions.
So when specifiying the foreign keys at all, it should look something like this:
class ArticlesTable extends Table {
    public function initialize(array $config) {
        $this->primaryKey('article_id');
        $this->belongsTo ( 'Topics', [
            'foreignKey' => 'topic_id'
        ]);
    }
}

class TopicsTable extends Table {
    public function initialize(array $config) {
        $this->primaryKey('topic_id');
        $this->hasMany ( 'Articles', [
            'foreignKey' => 'topic_id'
        ]);
    }
}

You could avoid a lot of confusion if you'd stick to the convention and name your primary keys id.
See also

*

*Cookbook > Models > Table Objects > Basic Usage

*Cookbook > Models > Table Objects > HasMany Associations
Possibly missing accessibility configuration
Since you are trying to save non-default fields (that is Topic data instead of Topic primary key), you'll have to make the field accessible for mass assignment via newEntity. This is possible for example via the Entitiy::$_accessible property, which is permanent for every single instance of that entity until overriden at runtime
class Article extends Entity {
    protected $_accessible = [
        // ...
        'topic' => true
    ];
}

or by using the accessibleFields option for Table::newEntity(), which only applies to that one single instance.
$article = $articles->newEntity($this->request->data, [
    'accessibleFields' => [
        'topic' => true
    ]
]);

See also

*

*Cookbook > Models > Entities > Mass Assignment

*API > Cake\ORM\Table::newEntity()
Field Naming Conventions
Finally your form data is incorrectly formatted, names should by default be lowercase and underscored in order to match the entities properties, and they should be singular (unless it's a hasMany or belongsToMany association), ie it should be article and topic instead of Articles and Topics, also it's actually not necessary to use article at all.
echo $this->Form->input('heading');
echo $this->Form->input('topic.topic_title');

<input type="text" name="heading">
<input type="text" name="topic[topic_title]">

See also Cookbook > Helpers > FormHelper > Field Naming Conventions


text:
Q: How to find if there is related data? Good evening. I'm developing a project using JPA and man kinds of relationship like OneToMany, ManyToMany, etc. There is anyway to find if Table X, for example have related data with table Y ?
I can use Reflection but I don't see it like the best solution since I read that it can impact the application performance.
Anyone had this problem?

A: I think you are looking for database metadata. You can obtain database metadata from database connection via getMetaData() method.
Example:
DatabaseMetaData metaData = dbConnection.getMetaData();

Look at the getExportedKeys() method of the obtained DatabaseMetaData implementation.
It retrieves a description of the foreign key columns that reference the given table's primary key columns (the foreign keys exported by a table).


text:
Q: Swift ViewController without prepareForSegue On my project I have a Master controller (Which is accessed by a segue that has three nibs. These nibs are not on the main storyboard They only show on the master view and I can swipe across to view them.
How do I get from any one of those nibs to the ViewController that sent them?
For Clarity

*

*ViewController1

*

*segue to ViewController2

*

*display slide nibs (ViewController3).

I want to get from ViewController3 to ViewController1 but they are not on the storyboard so I cant click and drag and make a segue.
I hope this makes sense.
Edit: IBAction
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let secondVC = storyboard.instantiateViewControllerWithIdentifier("ViewController1StoryBoardID") as! ViewController1
presentViewController(secondVC, animated: true, completion: nil)

ViewController2 has this:
let vc3 = ViewController3(nibName: "ViewController3", bundle: nil)
var frame3 = self.vc3.view.frame
frame3.origin.x = self.view.frame.size.width * 2
self.vc3.view.frame = frame3
self.addChildViewController(self.vc3)
self.scrollView.addSubview(self.vc3.view)
self.vc3.didMoveToParentViewController(self)

With a few extra lines to add other frames and slide to them

A: You can instanciate the Viewcontroller through the Storyboard,
//instanciate storyboard
let mainStoryBoard = UIStoryboard(name:"StoryboardName", bundle:nil)

let myViewcontroller = mainStoryBoard.instanciateViewControllerWithIdentifier("viewcontrolleridentifier") as? ViewController1

You can set the identifier in Interface builder

A: let viewController = YourViewController(nibName: "YourViewController", bundle: NSBundle.mainBundle())
self.navigationController?.pushViewController(viewController, animated: true)

A: There is a concept in iOS of Navigation View Controller that will help you to do it in a "professional way". You will "stack" the views, and can get back to any of them, white out a segue, just popping it.
Other way to do it, is moving by the identifier of the view, whithout an explicit segue in storyboard, check This link  for more details

A: You do it like:
let storyboard = UIStoryboard(name: "StoryboardName", bundle: nil)
let secondVC = storyboard.instantiateViewControllerWithIdentifier("anIdentifier") as! UIViewController
presentViewController(secondVC, animated: true, completion: nil)

*

*"StoryboardName" is the name of your storyboard

*"anIdentifier" is the identifier of your UIViewController set in storyboard

Please check the image where to set the storyboard ID of the ViewController:


text:
Q: Snowflake : Error while running snowsql (Error: OSError: [Errno 8] Exec format error) I'm looking for some help on the below error.
I just installed snowsql on my Mac and running the below command. But I keep getting the below error. Tried installing it multiple times. Appreciate any help on this.
snowsql is a binary, so I will not be able to any shebang line
/Applications/SnowSQL.app/Contents/MacOS/snowsql -v
[Errno 8] Exec format error: '/Users/rj/.snowsql/1.2.22/snowsql'

bash --version
GNU bash, version 5.2.0(1)-release (x86_64-apple-darwin21.6.0)
Copyright (C) 2022 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

A: set it at executable by running this in terminal :
chmode +x < snowsql>


text:
Q: new.html.erb doesn't see the background color of style sheet i make style sheet in assets, its name _loginstyle.css to adjust style of log_in page and sign_up page

and render it in new.html.erb
it show every thing except background color
any help please
i am beginner in ruby
this is new.html.erb

<%= stylesheet_link_tag "loginstyle", media: "all" %>

Log in

<%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>

    <%= f.label :email %>

    <%= f.email_field :email, autofocus: true %>

    <%= f.label :password %>

    <%= f.password_field :password, autocomplete: "off" %>

  <% if devise_mapping.rememberable? -%>

      <%= f.check_box :remember_me %>
      <%= f.label :remember_me %>

  <% end -%>

    <%= f.submit "Log in" %>

<% end %>

<%= render "devise/shared/links" %>

A: add !important to "background-color: #FFB6C1;" to be "background-color: #FFB6C1; !important"

A: Move the stylesheet link tag outside of your body.


text:
Q: Searching adventure movie, similar to Indiana Jones / Alan Quatermain / Romancing The Stone Saw that movie sometime in 199x (it could be 200x, but don't think so): people searching for the treasure (of ancient inka?).
The only scene I remember is a final one:

*

*main character gets into some dark place (lower ground or some cave)

*he lifts the hidden cover

*under the cover we see lots of bright shining diamonds (presumably the whole space below is overfilled with the diamonds)

*at the same time a powerful tremor begins, everything starts to fall apart

*"good guys" manage to escape

*it occurs that a new highway is being constructed and big machines are clearing the place out of jungles, so now the whole place is covered by a soil

Adventure is happening in our time.
Movie itself seems to be quite popular at that time.
Searched in google, no luck for now...


text:
Q: Replacing with SED, trying to append content doesn't work I'm trying to use sed to fix a file, and I'm having trouble grokking what I'm doing wrong. Any pointers on why sed isn't behaving as I expect it to would be appreciated.
My file consists of a bunch of lines, each containing a single value. The content of the values is irrelevant for the replacing, save that they're always alpha-numeric and follow a pattern. I want to prepend and append these values with other data, in order to create a CSV file.
When prepending, sed works admirably:
Prepend (works)
sed 's/\(.*\)/NULL;0;400;6;2010-07-27;\1/' selection.csv
Resulting in:
NULL;0;400;6;2010-07-27;1326GP11SCH
NULL;0;400;6;2010-07-27;2312BB30DUM

Which is exactly as I hoped it would.
Append (fails)
However, when appending, things get ugly:
sed 's/\(.*\)/\1 ;NULL;NULL;1/' selection.csv
Resulting in:
 ;NULL;NULL;1
2312BB30DUM ;NULL;NULL;1

The to-be-replaced value disappears on all but the last line, which is quite disheartening.
It must be something quite obvious I'm doing wrong here, but can't figure it out.
(note: Not sure whether this is SO or SU material... feel free to move it to SuperUser, if you can and believe it should be over there)

A: do a dos2unix on the file first, then use sed
$ dos2unix file
$ sed 's/$/;NULL;NULL;1/' file


text: Q: How does MVC decide which constructor to hit when there are multiple constructors? How does MVC decide which constructor to hit when there are multiple constructors? I have injected dependency in one constructor but another is being hit.


text:
Q: Is there a word for something that gets "acted upon"? For instance, say I have two individuals and one is active, the other passive. I know I can call the active person the "actor"—he "acts upon" the passive person. But what do I call the "acted upon"? Is there a single word to describe this?

A: The term is Patient, which is formed from the same semi-deponent Latin verb (patior, patere, passus 'suffer, endure') as Passive. Most grammatical terminology comes from Latin, so if you want to make up a linguistic term, get a Latin dictionary.
In a prototypical English active transitive sentence,

*

*the grammatical relation Subject has a semantic role Agent (< ago, agere, egi, actus 'do'),
while

*the grammatical relation Direct Object as the semantic role of Patient.

A: In Functional Grammar the person or thing acted upon is the Patient.
This may seem an odd use of the word, but it is not, in fact, a coinage of modern linguistics.  Patiens (the present participle of pati, "to undergo, endure, suffer") and agens were literal Latin translations of Aristotle's terms, and the opposition has been used in English since the 16th century:

The eye of the man is the arrow, the bewtie of the woman the white, which shooteth not but receiueth, being the patient, not the agent. —Lyly, Euphues 1580
Love or hate, applaud or condemn, the agents and the patients of [Shakespeare's] mundane scheme. —Swinburne, Essays & Studies 1875

A: In some circumstances, the term object can be used, as in

She was the object of his affections.

Cambridge defines it as

the particular person or thing to which others direct thoughts, feelings, or actions: The court has been the object of recent criticism

Somewhat ironically, the term subject may also be used.  Definition 5 in American Heritage says

One that experiences or is subjected to something: the subject of ridicule.
  A person or animal that is the object of medical or scientific study: The experiment involved 12 subjects.
  A corpse intended for anatomical study and dissection.
  One who is under surveillance: The subject was observed leaving the scene of the murder.

A: Actor is a term used in functional grammar to describe the person or thing that initiates a material Process (but not other kinds of Process), that is, some kind of action that takes place in the real world. If you want to be consistent with the use of Actor in functional grammar, then the term to use for the person or thing on the receiving end is the Goal (not, pace John Lawler and StoneyB, the Patient). In a mental Process it is the Phenomenon, in a Relational Process, the Value, and in a Verbal process, the Verbiage.

A: FWIW, in various computing process models I've constructed that have an Actor role, the role of that which is acted upon has been either a Subject or a Target.


text:
Q: Prove that if s is the supremum of $X$, then $z + s$ is the supremum of $X + z$ I am having a bit of trouble trying to solve this problem.
Question: For any $X \subseteq \mathbb{R}$ and $z\in\mathbb{R}$ define $X + z$ to be the set of all $x + z$ where $x\in X$. Prove that if $s$ is the supremum of $X$, then $z + s$ is the supremum of $X + z$
My attempt is that you're given that the supremum, $s$, is the supremum of $X$. Then that should mean that $s \geq x, \forall x \in X$, then that should mean that $z + s \geq x + z, \forall x \in X$.
Any help or tips will be useful!

A: Let be $\varepsilon>0$. Since $s$ is the supremum of $X$, then there exists $x_n\in X$ such that :
$$s-\varepsilon < x_n \le s$$
Now
$$z+s-\varepsilon < z+x_n \le z+s$$
let $z_n = z+x_n$ and $w=z+s$. We have showed that for all $\varepsilon>0$, there exists a $z_n = z+x_n \in z+X$ such that:
$$w-\varepsilon < z_n \le w$$
therefore $w = z+s$ is the supremum of $z+X$


text:
Q: jquery Mobile bug when long press link? I am using jquery mobile and I have an annoying issue... When an element has a link, for example a button, I am catching events like touchEnd event to fire then javascript calls or prevent link. However, when a long press button (1 or 2 seconds), ALWAYS executes the link! Tested on iOS5 and Android and tried several possibilities but problem remains! For example, following code should prevent link and it does if you click "fast" at button. However, if you press button and hold it (touchend is not fired), link is also executed! Also if you do not handle any event. Thank you
$(document).ready(function()
 {
  $("a").bind('touchend', function(event)
  {
          event.stopImmediatePropagation();
          event.preventDefault();
  }

EDIT: problem comes from tabhold event that always fire link although this event is used or not! Definetely seems a bug and possible solution could be set its time to infinite. How?

A: Please report a bug on the jquery-mobile site https://github.com/jquery/jquery-mobile/issues
Ideally make an example app that shows the bug from this template: http://jsbin.com/otepum/edit#html
I recently reported a similar bug, which is that cmd+click on a link doesn't open in new window (obviously not a problem on actual touch screens)
Thanks!


text:
Q: Best Practices for NavBar Branding in React-Bootstrap / React-Router-Bootstrap There is an issue regarding anchor tags in React Bootstrap and React Router. I was curious on how other people have handled the situation. It is possible to just leave an anchor tag with an href such as Site Title and avoid using IndexLinkContainer. There is also using MenuItem such as.
<Navbar.Brand>
    <IndexLinkContainer to={{pathname: '/'}}>
          <MenuItem>TitleName</MenuItem>
     </IndexLinkContainer>
 </Navbar.Brand>

However this leaves a hidious looking bullet point to the far left of the navbar. If anyone else has any ideas on how to tackle this I would appreciate it.

A: That's what I did (with LinkContainer from react-router-bootstrap):
        <LinkContainer to="/" style={{ cursor: 'pointer' }}>
            <Navbar.Brand>
                Some text

            </Navbar.Brand>
        </LinkContainer>

Contains site's name and logo.
No bullet point but I couldn't find a way to avoid using LinkContainer..


text:
Q: AngularJS $compile within ng-repeat I have an ng-repeat. The model I'm repeating over looks like this:
var customer = [
    {
        displayName: 'Name',
        childProperties: [{property: 'LastName'},{property: 'FirstName'}]
    },
    { property: 'Address1', displayName: 'Address' },
    {
        displayName: '',
        childProperties: [{ property: 'City' }, { property: 'State' }, { property: 'ZipCode' }]
    },
    { property: 'HomePhone', icon: 'fa fa-home', filter: 'tel' }]

This is the HTML

    <form class="form-horizontal" ng-if="!loading">

                {{prop.displayName || prop.property}}

                <input type="{{inputtype()}}" class="form-control input-sm" data-ui-help="{{prop.type}}" ng-disabled="!prop.enable" ng-model="prop.value">

    </form>

You will see on the ng-repeat I have an ng-click. I want to enable the form when I click the row. When I have an element that doesn't have child properties it's simple enough to enable the input.  If there are childProperties within the model, I want to append multiple inputs for each of the child property.  I can't seem to figure out what I'm missing to get the scope to compile the correct output.
function toggle(prop, e) {
    if (!prop.enable) {
        if (prop.childProperties) {
            e.currentTarget.children[1].innerHTML = '';
            $compile('
<input type="text" class="form-control" ng-model="child.value">
')(scope).appendTo(e.currentTarget.children[1]);
        } else {

            prop.enable = true;
        }
    } else {
        prop.enable = false;
    }
}

I just get the angular comment as though there is nothing within the element to repeat over

A: The problem is here:
ng-repeat="prop in obj track by $index"

where is "obj" variable in your code?
tried your code:

            {{prop}}

                {{prop.displayName || prop.property}}

                <input type="text" class="form-control input-sm" data-ui-help="{{prop.type}}" ng-disabled="!prop.enable" ng-model="prop.value">

the template rendered, didn't checked the logic behind


text:
Q: Issue with code behind ASPX I have an ASPX file with this button:
<asp:button id="cmdPartnerInfo" runat="server" Font-Bold="True"
    Text="Partner Info" TabIndex="3">
</asp:button>

And in the ASPX.VB file I have this Sub:
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    cmdPartnerInfo.Attributes.Add("onclick", "return ShowPartnerContatcInfo();")
    imgStaff.Attributes.Add("onclick", "return AddStaffSelection();")
    lblDt.Text = ""

... snip ...

End Sub

However, there is a squiggly line under cmdPartnerInfo and the message is:
Error 38 'cmdPartnerInfo' is not declared. It may be inaccessible due to its
protection level.

So it looks like the code in the vb file doesn't see the asp control in the aspx page.
Any help figuring out why this is happening is appreciated.
Thanks!
Eric
UPDATE:
These are the two directives at the top of the ASPX page.
<%@ Register TagPrefix="Card" TagName="Banner" Src="~/banner.ascx" %>
<%@ Page Language="vb" AutoEventWireup="false" CodeFile="projectpartlog.aspx.vb" Inherits="Project_and_Partners_Log" %>

A: *

*Check page's directive <%@ Page and ensure that you behind class
belongs to you aspx file.

*Next issue which you need to check is aspx.designer file(you should find your Button control declaration). Sometimes VS doesn't add declaration automatically, when you copy-paste a code.

A: does your ASPX file has declaration of page directive having "CodeFile/Inherits" attribute? e.g. <@Page CodeFile="XYZ.aspx.vb" Inherits="XYZ" >

A: <%@ Page Language="vb" AutoEventWireup="false" CodeFile="projectpartlog.aspx.vb" Inherits="Project_and_Partners_Log" %>

This directive means:

*

*The file name for your "code behind" should be projectpartlog.aspx.vb

*The Class name in the projectpartlog.aspx.vb file should be Project_and_Partners_Log
Partial Class Project_and_Partners_Log
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load

    End Sub

    Protected Sub cmdPartnerInfo_Click(sender As Object, e As System.EventArgs) Handles cmdPartnerInfo_Click.Click

      'Code.....

     End Sub

End Class

A: I think you have converted your button to private add a new Button and remove it and then try.

A: You need to check your page directive.
<%@ Page Language="VB" MasterPageFile="~/Master/Mater.master" AutoEventWireup="false"
    CodeFile="Test.aspx.vb" Inherits="Test" %>

Check to see if the CodeFile property is set to the proper code file.


text:
Q: The footnote for disputed flags is missing in the revised flagging history Since flag weight was removed there remains a dagger (†) to mark a footnote for disputed flags in the flagging history:

I understand this as a bug. Either the dagger marking a footnote should be removed or the footnote should be added. It is only confusing to mark a footnote but include a footnote. The user will wonder what the dagger means.
Here are further examples to show that it is confusing:

A: Fixed in trunk, will be deployed next round.


text:
Q: Create array of arrays from array of objects in the style of a matrix I have an array of objects. I am trying to create a matrix-like array of objects.
This is my code:

let data = [
    {device: 'iphone',   site: 'google', val1:10, val2:20, val3:30},
    {device: 'iphone',   site: 'bing',   val1:23, val2:12, val3:14},
    {device: 'iphone',   site: 'jeeves', val1:67, val2:78, val3:12},
    {device: 'ipad',     site: 'google', val1:10, val2:20, val3:30},
    {device: 'ipad',     site: 'bing',   val1:23, val2:12, val3:14},
    {device: 'ipad',     site: 'jeeves', val1:67, val2:78, val3:12}
    ];

let arr = data.map(d => Object.values(d));
console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

When I do the map like above, I am getting all the object values into the array of arrays.
How do I make my data look like this:
    arr = [
        [0,0,67], [0,1,23],[0,2,10],[0,3,67],[0,4,23],[0,5,10],
        [1,0,78], [1,1,12],[1,2,20],[1,3,78],[1,4,12],[1,5,20],
        [2,0,12], [2,1,14],[2,2,30],[2,3,12],[2,4,14],[2,5,30],
        ]

Not sure how to make my array objects look like the matrix above.

A: To get just the numeric values from each object use Array.filter(), and ignore value that are NaN (not a number):

const data = [{"device":"iphone","site":"google","val1":10,"val2":20,"val3":30},{"device":"iphone","site":"bing","val1":23,"val2":12,"val3":14},{"device":"iphone","site":"jeeves","val1":67,"val2":78,"val3":12},{"device":"ipad","site":"google","val1":10,"val2":20,"val3":30},{"device":"ipad","site":"bing","val1":23,"val2":12,"val3":14},{"device":"ipad","site":"jeeves","val1":67,"val2":78,"val3":12}];

const arr = data.map(d => Object.values(d).filter(v => !isNaN(v)));

console.log(arr);

To get your matrix - reverse the array, map the objects, and then map the values after filtering them, and use the indexes. Flatten the results one level, and sort according to the 1st value of each sub-array in the matrix.

const data = [{"device":"iphone","site":"google","val1":10,"val2":20,"val3":30},{"device":"iphone","site":"bing","val1":23,"val2":12,"val3":14},{"device":"iphone","site":"jeeves","val1":67,"val2":78,"val3":12},{"device":"ipad","site":"google","val1":10,"val2":20,"val3":30},{"device":"ipad","site":"bing","val1":23,"val2":12,"val3":14},{"device":"ipad","site":"jeeves","val1":67,"val2":78,"val3":12}];

const arr = [...data]
  .reverse()
  .map((d, y) =>
    Object.values(d)
      .filter(v => !isNaN(v))
      .map((v, x) => [x, y, v])
  )
  .flat(1)
  .sort(([a], [b]) => a - b);

console.log(arr);


text:
Q: show array data in react table I have an both an array, and the state array.
 const [formData, setFormData] = useState([]);
  let ure = [{}]

  useEffect(() => {
    axios
      .get("/api/listUre")
      .then((res) => {
        console.log(res.data)
        //setFormData(res.data);
       ure.push({
             class_id: res.data.class_id
         })
      })
      .catch((error) => {
        // Handle the errors here
        console.log(error);
      })
      .finally(() => {
      });
  }, []);

once I do that, I now want to access the class_id from within a table:
{ure.length > 0 &&
            ure.map((obj, index) => {

              {obj.class_id}

              {obj.class_id}

               My Name

         })}
      {ure.length === 0 && "No Data Found"}

I am not sure what I am doing wrong, but it is not outputting anything to the page. and i know that the ure array has data in it because it isn't outputting "No Data Found" to the screen, so it should be working. can anyone help me out?

A: I think you need ure to be a piece of state, otherwise your ure array will keep getting reevaluated each time your component re-renders.
So, the first step would be to:
const [ure, setUre] = useState([]);

Then for changing ure, just do something like:
setUre(currUre => {
  return currUre.concat([{ foo: bar }]);
})

Then, to iterate over it, you shouldn't need to check the length > 0, just the map() will do the trick.
The reason why you're seeing that outcome (no table but no empty array) is because you're initializing let ure = [{}], which is an array of size 1 with an empty object in it.


text:
Q: copy and paste the contents of many txt files to create one big file I have multiple txt files and I want to copy and paste the contents of each file to create one big file using python. Any help is greatly appreciated.

A: First, we should break down the problem.

*

*You have a bunch of text files

*Create a big file from those files
Lets now work with that. Doing a little quick googling, we should look into how to take the contents of files with python, and put them into a big one.
You can start by create a big file using file in python.

big_file = open("my_big_file.txt")

Okay now that that is done, lets think about what programming concepts we could use to look at all of the files we have in a directory, open them, and dump their contents inside of the big file...
Lets use a for loop! But first, we need to figure out how to get the names of the files we have in the directory, into our code.

*

*We could manually write all of these into the code...

*Or even better, use the OS module to use os.listdir() to get the names of everything in the directory.

for file in os.listdir():
  # We use context managers for opening files in Python using
  # the keyword "with"
  with open(file) as f:
    big_file.write(f.read())

# Then finally, close the big file we created earlier
big_file.close()

You will notice that the text is pretty hard to read if you look at it as it is filled with newline characters and all sorts of garbage...
You can make corrections to get it to print out the way you want it to by writing new lines or however you want to format your code.


text:
Q: Why do I get the "Type-declaration character does not match declared data type" in my VBA code? I wrote a program which calculates the integral of the probability density function of the lognormal distribution.
I want it to be able to calculate the nth moments of the pdf too. But if I modify my code I get this error. It works properly before I add *(x^(M))
Function riemanint(n, a, b)

Dim h, i, x
h = (b - a) / n
x = a - h / 2
    For i = 1 To n
    x = x + h
    s = s + f(x, ev, var, PI, M) * h
    Next
riemanint = s
End Function

Function f(x, ev, var, PI, M)

PI = Application.WorksheetFunction.PI()
ev = Range("D2")
var = Range("E2")
M = Range("F2")

f = (((1 / (x * ((2 * PI) ^ 0.5) * var)) * Exp((-(Log(x) - ev) ^ 2) / (2 * var * var)))) * (x^(M))
End Function


text:
Q: Restrict duplication of Alias name while creating a distribution list using Exchange commands I am trying to create a new distribution list using exchange server commands given in Creating new distribution list command.
When I enter a duplicate alias name it is allows me to create the new distribution list.
While when I try to create the distribution list from the Exchange Server UI in Office 365 then it gives me an error if I enter the duplicate Alias name.
I want to know how I can achieve the same functionality using commands also.
Update
I am using following command
New-DistributionGroup Name 'Distribution-List-Name' Alias 'Alias-Name' ErrorAction 'Stop'

Thanks in Advance.

A: Aakash Morya,
Have you tried this syntax?
New-DistributionGroup -Name <DL name> -DisplayName <DL display name> -Alias <Alias> -PrimarySmtpAddress <Email Address>

http://o365info.com/manage-distribution-groups-by-using/#SUB-1
To do this from Office 365, you go to Exchange Administration and go to Recipients, Click the Groups, Click the plus sign, Click Distribution group, Enter a Display name, Enter an Alias, Enter a Name, Select the owner, Select the members, Click Save.
http://office365support.ca/creating-a-distribution-group-exchange-online/


text:
Q: Can't boot from clean install I've recently been having trouble booting my computer.
I tried to re-install some NVIDIA drivers after an update broke CUDA and led to some poor video performance. However that led to some conflicts, so I totally lost the graphics, and couldn't get beyond the command line TTY screen.
I tried a reboot, but it just hung after selecting Ubuntu 14.04. Then I tried the Boot Repair CD to no avail. Here is the log.
As of now, trying to boot from it, I get error: no such device: 90cc5126-fb61-4bb20aafe-b9ad22f26644; then it goes into a boot rescue command line. I think something went pretty terribly wrong, because glancing at the log, it looks as though there's no OS detected at all.
After that didn't work, I unplugged all of my hard drives, hooked up a brand new one, and tried to install 16.04 on it, but again I couldn't boot. This time the error just said to insert a boot device. I again tried the Boot Repair CD, but it didn't work again. Here is the second log.
I really appreciate any ideas that you'll have. I'm really not sure what it could be, but I'm a total novice with this aspect of any Linux system, so I thought it would be good to reach out to you.

A: As you have placed a brand new hard disk in an UEFI system, you first need to restore the UEFI partition. Try them in the following order:

*

*The original System restore DVD/CD/USB from your hardware's manufacturer

*The Open Source rEFInd

*Go back to BIOS: no more worries about Unified Extensible Firmware Interface (UEFI) problems.  This one is hardware-dependent and on some systems might need a BIOS-flash.


text:
Q: Extract information from sentence I'm creating a simple chatbot. I want to obtain the information from the user response. An example scenario:
Bot : Hi, what is your name?
User: My name is Edwin.

I wish to extract the name Edwin from the sentence. However, the user can response in different ways such as
User: Edwin is my name.
User: I am Edwin.
User: Edwin.

I'm tried to rely on the dependency relations between words but the result does not do well.
Any idea on what technique I could use to tackle this problem?

A:
First off, I think a complete name detection is really heavy to set up. If you want your bot to be able to detect a name in like 99% of the cases, you've got some work. And I suppose the name detection is only the very beginning of your plans...

This said, here are the first ideas that came to my mind:

*

*Names are, grammatically speaking, nouns. So if one can perform a grammatical analysis of the sentence, some candidates to the name can be found.

*Names are supposed to begin with a cap, although on a chat this is likely not to be respected, so it might be of little use... However, if one came across a word beginning with a cap, it is likely to be someone's name (though it could be a place's name...).

*The patterns you could reasonably think of when introducing yourself are not that numerous, so you could "hard-code" them, with of course a little tolerance towards typos.

*If you are expecting an actual name, you could use a database holding a huge amount of names, but have fun with the Hawaiian or Chinese names. Still, this appears as a viable solution in the case of European names.

However, I am no AI specialist, and I'm looking forward to seeing other proposals.

A: I'd suggest using NER:

You can play with it yourself: http://nlp.cogcomp.org/

A: There are many alternatives, over only 2 'models':

*

*Based on NLP training; uses HTTP for integration/delivery:

*

*Microsoft LUIS

*API.AI

*IBM Watson

*based on pattern matching; uses an interpreter (needs an native implementation or a bridge from other implementation)

*

*Rivescript - Python interpreter available

*ChatScript - needs a C++ bridge/interop

*AIML - Python interpreter available

This is not an extensive listing of current options.

A: Detecting names can be complicated if you consider things like "My name is not important", "My name is very long", etc.
Here is public domain script in Self that attempts to parse a name, you may be able to adapt it to python, it also does some crazy stuff like lookup the words on Wiktionary to see if they are classified as names,
https://www.botlibre.com/script?id=525804


text:
Q: Read the CSV string and use the split command to create an array with each row I have been trying to reformat a CSV output string into an array with each row of data.
The string looks like this
428780970341,19903254,9/7/2022 6:46:59 AM,9/7/2022 9:21:02 AM,9242,428780973398,20277971,9/7/2022 7:01:41 AM,9/7/2022 8:59:52 AM,7090

I need to split the rows by the 6th value. The array should look like this
Arrresponse
[1] 428780970341,19903254,9/7/2022 6:46:59 AM,9/7/2022 9:21:02 AM,9242
[2] 428780973398,20277971,9/7/2022 7:01:41 AM,9/7/2022 8:59:52 AM,7090


text:
Q: Audio not working on WMP and VLC Players but works in the Web and using MPC-HC I did a windows update which fails with recovery tool: the issue was solved using a previous restore point and a check disk (CHKDSK) wich deleted many files on windows.
After re-booting Windows 7 / 64 bits. I was unable to play audio file (.mp3) using either VLC player (2.2.4) or windows media player. However, it plays correctly in Media Player classic MPC and also on any browser player (Opera, Chrome, Firefox etc).
MPC-HC (Nightly, 64-bit)
------------------------

Build information:
    Version:            1.7.10.252 (e91b41e)
    Compiler:           MSVC 2015 Update 3
    Build date:         Jul  8 2016

LAV Filters:
    LAV Splitter:       0.68.1.31
    LAV Video:          0.68.1.31
    LAV Audio:          0.68.1.31
    FFmpeg compiler:    MinGW-w64 GCC 5.4.0

Operating system:
    Name:               Windows NT 6.1 (build 7601, Service Pack 1)
    Version:            6.1 (64-bit)

Hardware:
    CPU:                Intel(R) Core(TM) i5-4200U CPU @ 1.60GHz
    GPU:                Intel(R) HD Graphics Family (driver version: 10.18.10.4358)

I have tried different Audio Drivers but none of them solved the issue, but I think it's related to non proper use of codecs.
My audio driver is connexant and I tried official updates (Rollback Driver, update from device manager, update from connexant and from toshiba for my model Satellite L50-B 11G). Below audio driver tried and tested after reboot.
1.
Driver provider: connexant
Driver date    : 11/04/2014
Driver version : 8.65.38.50    // Audio plays only using MPC

Driver date    : 11/03/2014
Driver version : 8.65.35.50    // Audio plays only using MPC

Driver date    : 20/08/2015
Driver version : 8.66.19.52    // Audio plays only using MPC

The first two ones are Microsoft signed and the last one is not digitally
signed.
WMP shows this message:

Windows Media Player cannot play the file because there is a problem
  with your sound device. There might not be a sound device installed on
  your computer, it might be in use by another program, or it might not
  be functioning properly.

Note: All those Players was installed before having this issue and they were working correctly. The browser is playing sound correctly !
Thanks in advance. I am still struggling with this issue, even BB Flash Recorder and similar applications doesn't record sound !

A: I suggest that you run a System File Check (SFC) scan to repair any missing or damaged system files, see http://support.microsoft.com/kb/929833 for instructions.
Does the scan find any problems and is it able to fix them?


text:
Q: Confused about / with? I've encountered this question today, what I actually said was

I'm confused with these two questions.

Then I thought, "Should I say confused with?"
Dictionary says about should follow confused.
Can anyone tell me whether both of them are right?

A: Sam Karem's examples are practical and concise:

"I always confuse Tanya with her sister."
"I am confused about what to do with this degree that I've got".

But in addition to that, it would be better if we note that:

*

*The word "confused" is an adjective, as in "be confused about".

*The word "confuse" is a verb, as in "people confuse A with B".
references:

*

*http://www.freecollocation.com/search?word=confuse

*http://www.freecollocation.com/search?word=confused

A: In many cases, preposition choice is a matter of opinion and personal preference.
With is perfectly acceptable in this case. In fact, according to Dictionary.com, one of the official definitions of with is

In regard(s) to

You could easily rewrite your example as

I am confused in regards to these two questions.

However, about is also acceptable, as it can potentially have exactly the same definition as with.
In conclusion, in this case, it's simply a matter of preference. Either is correct.
Which one sounds better to you?

A: "Confused with" is generally used when you fail to distinguish/mistake one for another. For example, "I always confuse Tanya with her sister".
On the other hand, "confused about" is used when "confuse" is given its literal meaning. For example, "I am confused about what to do with this degree that I've got".
Depending on the context, either could be correct, as they give a different meaning.


text:
Q: vscode's theme is not colorizing the letters Yesterday my vscode was working perfectly, but I dawned today and for some reason it seems that the theme is not working anymore. The editor identifies the language of the file but doesn't colorize the letters the right way, leaving almost everything white.
NOTE: html, .env and json files are working fine, but .ts files are not. Can someone help me with this?


text:
Q: "no rules expected the token" when writing a `let` statement in a macro When I try to compile this code using rustc main.rs:
macro_rules! getPI {
    let pi = 3.141592;
    println!("Pi is roughly 3.142 \n {0}", pi);
}

fn main() {
    print!(getPI);
}

it gives me an error:
error: no rules expected the token `pi`
 --> src/main.rs:2:9
  |
2 |     let pi = 3.141592;
  |         ^^

I'm very new to programing, I hope someone has a solution.

A: If you are "very new to programing", then you should start at the beginning; macros are not the beginning. Go back and re-read The Rust Programming Language, second edition, even though it's targeted at people who already understand another programming language.
You can then read the chapter from the first edition about macros. This will show you the proper syntax for macros. Macros have a number of arms, like a match statement:
macro_rules! getPI {
    () => {
        let pi = 3.141592;
        println!("Pi is roughly 3.142 \n {0}", pi);
    }
}

fn main() {
    getPI!();
}

I also don't know why you'd try to print! the return value of your macro, so I removed that. You must also call the macro using an exclamation mark (!).


text:
Q: dynamic google chart, Can't add new data I call updateChart(d) functions via ajax and pass new data.
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
    var chart;
    var dataTable;
    var options;
    var i = 1;

    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(drawChart);
    function drawChart() {
        dataTable = google.visualization.arrayToDataTable([
            ['Amplitude', 'time'],
            ['0', 0]
        ]);
        options = {
            title: '',
            curveType: 'function',
            legend: { position: 'bottom' }
        };

        chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
        chart.draw(dataTable, options);
    }

    function updateChart(d) {
        i++;
        dataTable.setValue(i, d); // Вот тут
        chart.draw(dataTable, options);

    }
</script>

When I try to add the next value for the chart, it throws an error:
Uncaught Error: Invalid row index 2. Should be in the range [0-0]

I did not find any solutions on the Internet (This is for a robot, it swears that there is not enough text).

A: function updateChart(d) {
        i++;
        console.log(i+"======"+d);
        //data.setValue(i,1,d);
        data.addRow([String(i), Number(d)]);
        chart.draw(data, options);
    }