text:
Q: Docker / Net 5 / Linux container exception: Unable to load shared library 'kernel32' or one of its dependencies I have a C# .Net5 console application which works fine on Windows 10 Pro.
I put the app in a Docker container to run in Linux on my Windows machine (WSL 2).
The app allocates a chunk (1 GB) of global memory (my app runs in 'unsafe' mode).
ptrChunk = (MemoryChunk*)Marshal.AllocHGlobal(new IntPtr(ChunkSize)).ToPointer();

It then tries to open and read directly from the file into this unmanaged memory.
The code that fails (tries to open a verified as existing file):
_handle = CreateFile
(
  fileName,   //-- file name to create
  access,     //-- desired access
  sharedMode, //-- share mode
  0,          //-- security attributes
  mode,       //-- FileMode.OpenOrCreate
  0,          //-- flags and attributes: FileAttributes.Normal
  0           //-- template file
);

The CreateFile is defined as as an extern:
[System.Runtime.InteropServices.DllImport("kernel32", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
static extern unsafe System.IntPtr CreateFile
(
    string FileName,          // file name
    uint DesiredAccess,       // access mode
    uint ShareMode,           // share mode
    uint SecurityAttributes,  // Security Attributes
    uint CreationDisposition, // how to create
    uint FlagsAndAttributes,  // file attributes
    int hTemplateFile         // handle to template file
);

The exception:
Unable to load shared library 'kernel32' or one of its dependencies. In order to help diagnose loading problems, consider setting the LD_DEBUG environment variable: libkernel32: cannot open shared object file: No such file or directory
TraceBack      at DataAccess.OsFileIO.CreateFile(String FileName, UInt32
DesiredAccess, UInt32 ShareMode, UInt32 SecurityAttributes, UInt32
CreationDisposition, UInt32 FlagsAndAttributes, Int32 hTemplateFile)
  at DataAccess.OsFileIO.Open(String fileName, OpenFlags openFlags, OpenMode
                              modeFlags) in /src/DataAccess/OsFileIO.cs:line 192

My Docker file is:
FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base
WORKDIR /app

FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
WORKDIR /src
COPY ["TseShard/TseShard.csproj", "TseShard/"]
COPY ["Utils/Utils.csproj", "Utils/"]
COPY ["BinarySerialization/BinarySerialization.csproj", "BinarySerialization/"]
COPY ["Interfaces/Interfaces.csproj", "Interfaces/"]
COPY ["JsonCompare/JsonCompare.csproj", "JsonCompare/"]
COPY ["Networking/Networking.csproj", "Networking/"]
COPY ["FilterScoring/FilterScoring.csproj", "FilterScoring/"]
COPY ["DataAccess/DataAccess.csproj", "DataAccess/"]
COPY ["TseClient/TseClient.csproj", "TseClient/"]
RUN dotnet restore "TseShard/TseShard.csproj"
COPY . .
WORKDIR "/src/TseShard"
RUN dotnet build "TseShard.csproj" -c Debug -o /app/build

FROM build AS publish
RUN dotnet publish "TseShard.csproj" -c Debug -o /app/publish

FROM base AS final
#ENV LD_DEBUG=all
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "TseShard.dll"]

The problem is 100% reproducible.
Adding the:
ENV LD_DEBUG=all
to the Docker did not help.
I need to use unmanaged memory so I can't use regular C# managed I/O.
How should I build the container image to get around this problem?


text:
Q: Finding the exact cause for the exception - System.Net.Sockets.SocketException I tried to send a mail to an SMTP mail server using the code given below. But, I am getting an error -
Error: System.Reflection.TargetInvocationException: Exception has
been thrown by the target of an invocation. ---> System.Net.Mail.SmtpException:
Failure sending mail. ---> System.Net.WebException: Unable to connect to
the remote server ---> System.Net.Sockets.SocketException: A connection
attempt failed because the connected party did not properly respond after
a period of time, or established connection failed because connected host
has failed to respond 123.456.789:587
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot,
SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure,
Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState
state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)

This exception tells me the possible list of causes - A connection
attempt failed because the connected party did not properly respond after
a period of time, or established connection failed because connected host
has failed to respond 123.456.789:587
But it does not tell me exactly what is the cause - port number, wrong username, password or something else. How do I find out what is the exact cause.
Here is the code I used  -
Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird
using System.Net;
using System.Net.Mail;

public void email_send()
{
    MailMessage mail = new MailMessage();
    SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
    mail.From = new MailAddress("your mail@gmail.com");
    mail.To.Add("to_mail@gmail.com");
    mail.Subject = "Test Mail - 1";
    mail.Body = "mail with attachment";

    System.Net.Mail.Attachment attachment;
    attachment = new System.Net.Mail.Attachment("c:/textfile.txt");
    mail.Attachments.Add(attachment);

    SmtpServer.Port = 587;
    SmtpServer.Credentials = new System.Net.NetworkCredential("your
    mail@gmail.com", "your password");
    SmtpServer.EnableSsl = true;

    SmtpServer.Send(mail);

}

A: That IP address is obviously not correct 123.456.789:587.
Try ping smtp.gmail.com in a command prompt to see if it is resolving to that address. If so, you have that overriden somewhere, perhaps in your hosts file (C:\Windows\System32\drivers\etc\hosts).
After running your snippet ran but then I immediately got a "Sign-in attempt prevented" from Google since this method of authentication apparently does not meet their current standards.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How Many Moments Uniquely Define a Distribution with Finite Support? Simple question, but one to which I could not find the exact answer elsewhere.  How many moments of a discrete probability distribution with finite support are required to uniquely identify the exact probability mass function?  Suppose we know that the distribution has support on at most $N$ points within a bounded interval (for my purposes the interval is $[0, 1]$), but we do not know the points.
Is it the case that the distribution is uniquely identified by some number of moments? My hypothesis is that it may be the first $2N-1$ moments. Since we have to identify $N$ mass points and their $N$ individual probabilities, one might think we need $2N$ equations and each moment gives us one equation, plus the restriction that the probabilities sum to $1$.  But these equations are not linear in the mass points, so it's not immediately obvious to me that we're identified.
I am aware of the Hausdorff Moment Problem, so I know that an infinite sequence of moments uniquely identifies any bounded distribution, but I am particularly interested in further restricting the domain to distributions with finite support. Any references would also be appreciated!
Thanks!

A: Let $F$ be the distribution supported on the numbers $x_1 \lt x_2 \lt \ldots \lt x_n$ that assigns probabilities $p_i \gt 0$ to each $x_i.$  By definition, its (raw) moment of degree $k$ is
$$\mu_k = \sum_{i=1}^n p_i x_i^k.$$
I will begin with a series of observations about this situation, each of interest in its own right.  A basic tool is the sequence of vectors $\mathbf{x}_k = (x_1^k, x_2^k, \ldots, x_n^k)$ for $k=0, 1, \ldots,n-1.$  Writing $\mathbf{p} = (p_1,p_2,\ldots, p_n),$ each moment can be expressed as a vector product
$$\mu_k = \sum_{i=1}^n p_i x_i^k = \mathbf{p}\, \mathbf{x}_k^\prime.$$

*

*The collection $\{\mathbf{x}_0,\mathbf{x}_1, \ldots, \mathbf{x}_{n-1}\}$ is linearly independent.  To show this, assume the contrary: that is, let coefficients $c_k$ not all zero be such that $$\sum_{k=0}^{n-1} c_k \mathbf{x}_k = \mathbf{0}.\tag{1}$$  Written out component-by-component,  $(1)$ asserts that for each $i=1,2,\ldots, n,$ $$\sum_{k=0}^{n-1} c_k x_i^k = 0.$$  That exhibits each $x_i$ as a root of the polynomial $c(T)=c_{n-1}T^{n-1}+c_{n-2}T^{n-2}+\cdots + c_0.$ Such a polynomial has at most $\operatorname{deg}(c)\le n-1$ distinct roots, contradicting the distinctness of the $n$ $x_i.$

*All moments are determined by the first $n$ moments $\mu_0,\mu_1,\ldots,\mu_{n-1}.$  The preceding result shows the vectors $\mathcal{X} = \{\mathbf{x}_k,k=0,1,\ldots, n-1\},$ are a basis for $\mathbb{R}^n.$  Therefore for any $m,$ $\mathbf{x}_m$ is a linear combination of the $\mathbf{x}^k,$ $k=0,1,\ldots,n-1;$ that is, there exist coefficients $\,_ma_k$ (determined solely by the $x_i$) for which $$\mathbf{x}_m = \,_ma_0\mathbf{x}_0 + \,_ma_1\mathbf{x}_1 + \cdots + \,_ma_{n-1}\mathbf{x}_{n-1}.$$  Consequently $$\mu_m = \mathbf{p}\,\mathbf{x}_m^\prime = \mathbf{p}\,\sum_{i=0}^{n-1}\,_ma_k \mathbf{x}_k^\prime  = \sum_{i=0}^{n-1}\,_ma_k \mathbf{p}\,\mathbf{x}_k^\prime= \sum_{i=0}^{n-1}\,_ma_k \mu_k.$$

*The numbers $x_i$ and the first $n$ moments determine $\mathbf{p}.$  Indeed, the first $n$ moments are the coefficients of $\mathbf{p}$ in the basis dual to $\mathcal X.$

*The first $n$ moments of $F$ determine, and are determined by, the distribution shifted by a constant $\lambda.$  This is the distribution supported on $x_1-\lambda, x_2-\lambda, \ldots, x_n-\lambda$ with probabilities $p_i.$  The demonstration is straightforward: use the Binomial theorem to expand $(x_i-\lambda)^k$ in terms of $x_i^0, x_i^1, \ldots, x_i^k.$
Part of the question is whether there exist $n^\prime,$ a positive probability vector $\mathbf{q},$ and support points $y_1\lt y_2\lt \ldots \lt y_{n^\prime},$ determining a distribution $G$ having the same moments as $F.$  Suppose there is.  Shift both distributions by $\lambda=-\min(x_1,y_1),$ simplifying the situation to distributions with nonnegative support.  By taking $m$ arbitrarily large, the largest support points eventually dominate the moments: $$q_{n^\prime} y_{n^\prime}^m \approx \mu_m \approx p_n x_n^m$$ This is possible only when $q_{n^\prime}=p_n$ and $y_{n^\prime} = x_n.$  Continuing inductively, we conclude $n=n^\prime,$ $\mathbf{q}=\mathbf{p},$ and $\mathbf{x}_1=\mathbf{y}_1:$ that is, $G=F.$
Finally, how many moments need to be known to determine $\mathbf{p}$ and $\mathbf{x}$?  Consider the map $f:\mathbb{R}^n\times \mathbb{R}^n\approx \mathbb{R}^{2n}\to\mathbb{R}^{2n}$ defined by $$f(\mathbf{p}^\prime, \mathbf{x}^\prime) = (\mathbf{p}\mathbf{x}_0^\prime, \mathbf{p}\mathbf{x}_1^\prime, \ldots, \mathbf{p}\mathbf{x}_{2n-1}^\prime)^\prime.$$ Its derivative is the $2n\times 2n$ matrix
$$Df(\mathbf{p}^\prime, \mathbf{x}^\prime) = \pmatrix{1 & \cdots & 1 & 0 & \cdots & 0 \\
x_1 & \cdots & x_n & p_1 & \cdots & p_n \\
x_1^2 & \cdots & x_n^2 & 2p_1x_1 & \cdots & 2p_n x_n \\
\vdots & \cdots & \vdots & \vdots & \cdots & \vdots \\
x_1^{2n-1} & \cdots & x_n^{2n-1} & (2n-1)p_1x_1^{2n-2} & \cdots & (2n-1)p_nx_n^{2n-2}}$$
with a Vandermonde-like structure, enabling us to obtain a simple formula for its determinant,
$$\operatorname{Det}\left(Df(\mathbf{p}^\prime, \mathbf{x}^\prime)\right) = -(p_1p_2\cdots p_n)^{2n} \left(\prod_{1\le i\lt j \le n}(x_i-x_j)\right)^4.$$
Because none of the $p_i$ is zero and all the $x_i$ are distinct, this is nonzero.  The Inverse Function Theorem implies $f$ is locally invertible: that is, provided $\mathbf{\mu}=(\mu_0,\mu_1,\ldots,\mu_{2n-1})$ is in the range of $f$, there exists an inverse $f^{-1}\subset\mathbb{R}^n\times \mathbb{R}^n$ in a neighborhood of $\mathbf{\mu}.$  That is,

The first $2n$ moments $\mu_0,\mu_1,\ldots,\mu_{2n-1}$ determine a discrete set of solutions $(\mathbf{p},\mathbf{x})$ corresponding to those moments.

As we have already shown, all such solutions correspond to the same distribution: they differ only by permuting the indexes $1,2,\ldots, n$ of the variables.


text:
Q: How to do this approximation? Question: Of the following, which is the best approximation of
$$\sqrt{1.5}(266)^{3/2}$$
$$(A)~1,000~~~~(B)~2,700~~~~(C)~3,200~~~~(D)~4,100~~~~(E)~5,300$$
I used $1.5\approx1.44=1.2^2$ and $266\approx256=16^2$. Therefore the approximation by me is $4096$, so I chose $(D)$ which is wrong. The correct answer is $(E)$.
How should I find it out?

A: $$\sqrt{\frac{3}{2}} \cdot ( \sqrt{266})^3 =\sqrt{\frac{3\cdot 266}{2}}\cdot (\sqrt{266})^2 =  \sqrt{399} \cdot 266 \approx 266 \cdot 20 = 5320$$
This is closest to option (E)
Edit: Note that the only approximation I used here is $\sqrt{399}\approx \sqrt{400}$ so the  result will differ by a factor of $\frac{\sqrt{399}}{20}$. This can be quickly approximated too, $\frac{\sqrt{399}}{20} = \sqrt{1-1/400} \approx 1 - 1/800 =0.9987 $.

A: $$\sqrt{1.5}\cdot266^{3/2}\approx1.2 \times 16^3 = 4915.2$$
The closest answer is (E) 5300. Great intuition on how to find simple approximations, but you forgot to multiply by $1.2$! Also note that $1.44<1.5$ and $256<266$, so you know the true answer must be above the discovered approximation, leaving only the last answer.

A: $$\sqrt{1.5}(266)^{3/2} \approx \sqrt{\frac{16}{9}}(256)^{3/2} \approx \frac{4}{3} \times 4096 \approx 5460 $$
Hence, $(E)$
N.B. kuch nahi's answer is probably the "right" one ; this seemed more intuitive to me since I didn't need to compute $16^3$.


text:
Q: How to differentiate between a keypress of more than one usb-keyboard connected to the same host (in C#) I need to differentiate between a keypress of (at least) two usb-keyboards connected to a single PC.
Is there a method/precedure available to decide if key 's' (for example) is pressed either by keyboard A or Keyboard B?
(preferable language is C#)
Pseudo-Code:
if (keyPressed == 's')
{
   if(keyboardID == 'A')
   {
       print("Key 's' was pressed by Keyboard A");
   }
   else if (keyboardID == 'B')
   {
       print("Key 's' was pressed by Keyboard B");
   }
}

A: keystrokes are processed by the OS as events
in linux for every input device there is separate event queue in /dev/input/event* (* means the specific device number)
in linux you can list all input devices with the command sudo lsinput (input-utils)
you can capture the specific events for each of your keyboards, see Linux keyboard event capturing /dev/inputX
in windows this is similar. you can use rawInput and get a handle for each device. deeper information and example codes is in
https://blogs.msdn.microsoft.com/oldnewthing/20160627-00/?p=93755 ("The device handle tells us which keyboard generated the input... ")
https://www.codeproject.com/Articles/17123/Using-Raw-Input-from-C-to-handle-multiple-keyboard
raw input handling (distinguishing secondary mouse)
https://msdn.microsoft.com/en-us/library/windows/desktop/ms645543%28v=vs.85%29.aspx

A: Short of getting to the driver level and intercepting the keystroke there, you really can't (I think).  I utilize a bluetooth keyboard and a bluetooth keypad and could not find a way to do what you are asking so the number 3 on the keypad would register different than the number 3 on the keyboard keypad.


text:
Q: How to use AppWeb To upload files Anyone knows how to use AppWeb to upload file to server without using ESP?
I used the UploadFilter to do this with C but it didn't work.
I have already tried lots of methods to handle this but still cannot find the upload files in the UploadDir dictionary.
Very Appreciate for your answers!


text:
Q: Pass Int[] in HTTP Get to CoreWebAPI I have a Blazor WebAssembly Hosted project and am in need of posting up an Array of Ids to get.
[AllowAnonymous]
[HttpGet("GetByTypePaged/{ingredientTypeIds}/{startIndex}/{count}/{search?}")]
public async Task<IActionResult> GetByTypePaged([FromQuery]int[] ingredientTypeIds, int startIndex, int count, string? search)

However the ingredientTypeIds comes back as int[0] so no Ids are being retrieved.   Ive tried FromRoute and i get a 415 as well as without FromQuery
FromUri does not exist within the name spaces
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

Id have to install the Microsoft.AspNet.WebApi.Core nuget package to get the System.Web.Http namespace.  However, then the
[Authorize]
[Route]
[HttpGet]

etc all have ambiguity between the System.Web.Http and AspNetCore.   If I remove the references to the Microsoft.AspNetCore then I loose the [FromBody] for my HttpPut operation.
public async Task<IActionResult> Update(int id, [FromBody] Ingredient ingredient)

Whats my best approach here

A:
[HttpGet("GetByTypePaged/{ingredientTypeIds}/{startIndex}/{count}/{search?}")]

In your code we can find you defined a route with route parameters ingredientTypeIds, startIndex, count and optional one search.
Please note that route data and query string values are used only for simple types, if you'd like to pass an array of Ids in URL and bind to action parameter int[] ingredientTypeIds, you can modify your route and pass it through query string in this format:
ingredientTypeIds[0]=1&ingredientTypeIds[1]=2

Besides, if you'd like to pass complex-type data to your backend API, you can make your endpoint support the HTTP POST method, and you can pass the expected data through request body.


text:
Q: A macro that behaves differently at start of sentence I am using a macro to represent a certain term, e.g:
\newcommand{\agt}{the agent}

(I use this macro so that it is easier to change the term in the future, if needed).
Is it possible to change the macro so that, in the beginning of a sentence, it will print "The agent" with capital T?


text:
Q: Como buscar pelo registro quando a tabela tem chave primária composta? Tenho no meu banco de dados a tabela t_command_control.
Esta tabela tem uma chave primária composta formadas pelos campos CD_STATION e CD_COMMAND.
Se a chave primária fosse simples (apenas como campo CD_STATION) eu usaria a expressão abaixo para selecionar o registro que eu preciso.
Entities db = new Entities();
t_command_control objCommandControl = db.t_command_control.FirstOrDefault(e => e.CD_STATION == itCdStation);

Porém sendo a chave primária composta não sei como selecionar.

A: As expressões lambda podem possuir mais de uma expressão booleana. No seu caso, é só utilizar o operador condicional E (&&), deixando a expressão da seguinte forma:
Entities db = new Entities();

t_command_control objCommandControl = db.t_command_control.FirstOrDefault(e => e.CD_STATION == itCdStation && e.CD_COMMAND == itCdCommand);


text:
Q: Old young adult sci fi book about wars fought with robots remotely, allusions to chess This is a science fiction book I read about the year 2000.  The main premise that I vaguely remember was that humans were now fighting wars with robots by proxy BUT there were still normal humans in the war zones trying to survive.
I don't have much more to go on I'm sorry - but the main scene/piece that sticks out to me, was there were these "burrowing" robots that were the "hunter-killers" for the non-robot humans - I think the characters referred to these robots as Ferrets, Stoats or Weasels. I think at the end they made it to the control room or something, and realised it was all some big game of real life chess so to speak that they were caught in the middle of.
English book, unsure if series. Possible female main character but unsure.

A: Possibly Shade's Children (1997) by Garth Nix?
From Goodreads:

In a futuristic urban wasteland, evil Overlords have decreed that no child shall live a day past his fourteenth birthday. On that Sad Birthday, the child is the object of an obscene harvest resulting in the construction of a machine like creature whose sole purpose is to kill.
The mysterious Shade — once a man, but now more like the machines he fights — recruits the few children fortunate enough to escape. With luck, cunning, and skill, four of Shade's children come closer than any to discovering the source of the Overlords' power — and the key to their downfall. But the closer the children get, the more ruthless Shade seems to become ...

This Amazon review mentions a game of chess and Ferrets:

Puberty is rough, but in Garth Nix's science fiction thriller, it's deadly. You see, the "Change" has taken place in this once-familiar world and children who reach the "Sad Birthday" (that's 14 to you) are harvested for their brains, which in turn are placed in creatures used for war games by Overlords. These unlucky children go off to the Meat Factory before having their brains implanted in either a Screamer, a Tracker, a Ferret, a Myrmidon, or a Winger, the beasts used by Overlords in their sprawling and violent battles. For these seven Overlords (four men, three women), it's like a giant chess game, and the pawns are the children their creatures hunt down.

Found by searching this site for [story-identification] ferrets which returned, among others, Story Identification: Human Resistance to Conquering Aliens, the description of which had battles fought by proxy and robots:

This is a story I read back in the late 1990's or early 2000's. It was a sci-fi story and the plot was centered in a city. I believe it was on Earth. There were different tribes of Aliens that fought each other through proxy. Each tribe had augmented humans in different ways and used the humans to fight each other.
I believe there were also robots or cyborgs of some sort.


text:
Q: MySQL subqueries multiple result Is it possible to make the code below work. At the moment it only show employees from "New York" but not employees from "Chicago".?
SELECT employees.ename, zipcodes.city
FROM employees
LEFT JOIN zipcodes
ON employees.zip=zipcodes.zip
WHERE employees.zip =
(
SELECT zipcodes.zip
FROM zipcodes
WHERE zipcodes.city = 'New York' OR 'Chicago'
)
ORDER BY employees.eno;

Thanks in advance!
//René

A: Use the IN condition, like this:
SELECT employees.ename, zipcodes.city
FROM employees
LEFT JOIN zipcodes
ON employees.zip=zipcodes.zip
WHERE employees.zip IN
(
    SELECT zipcodes.zip
    FROM zipcodes
    WHERE zipcodes.city IN ('New York', 'Chicago')
)
ORDER BY employees.eno

Another approach (possibly better one) is to use the JOIN condition itself instead of a sub query, like this:
SELECT employees.ename, zipcodes.city
FROM employees
LEFT JOIN zipcodes
ON employees.zip=zipcodes.zip
AND zipcodes.city IN ('New York', 'Chicago')
ORDER BY employees.eno


text:
Q: HMS Awareness Kit-Error code 10011 is returned after the SDK is integrated I integrated the HMS Core Awareness SDK and then called the getWeatherByDevice API to query weather data, but an error occurred: com.huawei.hms.kit.awareness.b.HHG: Error Code: 10005 Desc: barrier or capture frequency limit. Why?

A: This error is caused by too frequent API calls. Currently, there are two restrictions on calling the APIs of HUAWEI Awareness Kit:

*

*The number of API calls within 1 hour cannot exceed 1000.

*The number of API calls within 5 seconds cannot exceed 20.

The reasons for such restrictions are as follows:

*

*Frequent API calls in a short period of time are not normal service requirements.

*Frequent API calls increase the workload of HMS Core and even cause a failure to provide services for other developers.

The restrictions are only a temporary workaround, and will be eliminated after service optimization.


text:
Q: How can I change the language for all default files, folders, titles, etc.? Or how can I recreate them? I bought Office 365 Business with SharePoint in Thailand because I live in Thailand and they have a special price here. On my first login the user interface and all files, folder, titles, etc. were in Thai.
But I want to use English and not Thai.
I was able to change the language from the user interface. But there are still lots of files and folders in Thai.
Is there somewhere a "button" to change all default data to English?
I guess if I would have subscribed i.e. in the USA then I would have the same file structure but in English. This is what I want.
Until now I did not add any data. So if everything is deleted and created from scratch again that is fine with me.
How can I make my SharePoint as if I would have signed up in English?
This is a sample of what I see:

A: No, there is not any button for changing default language.
If you want to have SharePoint default in English, you should create the whole Office 365 tenant in english, cause you can create Sites in English but you cannot edit the Root Site https://company.sharepoint.com otherwise you can create Microsoft Ticket and ask them if they can change the default localization to English for whole tenant...

*

*You can change preferable language for users, link here

*Or user can change it for its own. link here

*Here is some script for editing default language for all users, not tested

If its new tenant, maybe try delete them and create new one.
Hope it helps!


text: Q: Oracle SQL - Referencing another column within a wildcard statement I am trying to select only the rows the DIAGCODE column and PRESUMPTIVE column are similar. That is the first three characters of both the columns match each other. How do I self reference a cell within a like statement?


text:
Q: GoogleTV Primetime view I have to create application that uses GoogleTV primetime navigation concept.
If you ever see the primetime app on GoogleTV you know what I'm talking about.
There is something that looks like a GridView, but clearly it is not that simple.
There are always visible 3 or 4 rows, and selector is always on center row...
Content scrolls up and down, and selection is always on the same row.
Also in the row there are always up to 5,6 items, and when you try to navigate left or right...content of the selected row scroll horizontally.
So it look that this is nested grid view and scroll view...or even nested vertical and horizontal scroll view...
Do you have any idea what is this view? Or is there some library that provides this kind of view widget?
Tnx in advance!

A: This is a full blown custom set of views;
This is not a compound view, to my knowledge there are no libraries emulating this.
You will have to implement this yourself.


text:
Q: What is a good 3D library with boolean operations for iOS A good friend asked me for help regarding some 3D library for iOS but I was not able to find a proper solution:
Following is the text of the email I got from him:
We are trying to build an iOS app with 3D functionality. To do this, we need to port a 3D library with boolean operations into iOS. Our project is not open source so we need to use 3D libraries that protect the release of our code, namely ones with LGPL, Apache 2, BSD or MIT licenses. So far, we have only found one suitable 3D library with boolean operations - the GTS Library, a library in C for manipulating 3D triangular surface meshes. GTS - The GNU Triangulated Surface Library   The GTS Library, in turn, relies on the GLib library, core application building blocks for libraries and applications written in C. https://developer.gnome.org/glib/
The issue is that we have been trying to port the GLib library into iOS for weeks, but have not been successful.
Here are our questions:

*

*Do you have any suggestions on how we can port the GLib library into
iOS without errors?

*If we can't port GLib into iOS, then do you have any suggestions for
alternative 3D libraries with boolean operations (and an LGPL or
equivalent license) that we can port to iOS instead of the GTS
library?

A: A good library would be Ninevehgl. Have a look at that.


text:
Q: Database read/write collision through SQL I have a program written in VB due to the simplicity and GUI when using Visual Studio 2010 as my IDE and compiler. In this program I built a "ticketing" system where approximately 40 users in my center have the authority to submit tickets to my coworkers and I for IT or Facilities assistance.
This system uses an access database on the local server using SQL as the language. The problem is that we have rare occurrences where two users are trying to write a "ticket" at the same time to the database or pull a report of the data at the same time from the database and it crashes on one of users. I use a "try, catch, finally" block to avoid the "unhandled exception error" and have the program setup that should an "unhandled exception error" occur that it closes automatically. The other concern is that once this collision has occurred, the user can no longer read/write to the database through the program until they restart their computer.
With all that in mind, my question is as follows, is there a 100% way to prevent these collisions from occurring (like checking if the database is in use before reading/writing) and if not is there a way to avoid them being locked out of the database until restarting their computer?

A: Since this post I have swapped to a virtual MySQL database server to run these at much better speeds.  The issue I was having however, was resolved by clearing the pool.  Since at the time I was using OLEDB I used the command:
OLEDBConnection.ReleaseObjectPool()

and it prevented any more of these computers being locked to where they had to restart the computer as well as help prevent collisions.

A: Assuming you are using OLEDB, you can try using Transactions, which are simple to implement as explained in the Developer Network article entitled OleDbConnection.BeginTransaction Method.
I must admit I do not understand the IsolationLevel settings, but try omitting it or using the default shown in the example before trying the other available cryptic ones.
As Tony suggests, converting to SQL-Server is a much  more robust (long-term) solution that will ensure data integrity, especially if you plan to add more users. MS has a free migration tool that does an excellent job, even on queries. As for data integrity, see the last paragraph in the Microsoft Support article: Using Microsoft Jet with IIS


text:
Q: "No module named wordcloud" after successful installation After searching everywhere on here I found some solutions to my problem. At first, the error was that I needed Visual C++ 14.0 and that I could get it from a link that didn't work. So, I downloaded Visual C++ Build Tools and got Visual C++ 14.0.23026. That did not solve the problem.
I did some more searching and found that I could install it using wheel. So, I got wheel and got the .whl file from here as shown in the comments of this
post, making sure to get the correct version for my python version (3.6). Running python -m pip install wordcloud-1.5.0-cp36-cp36m-win32.whl worked, it seemed.
However, after restarting Pycharm, the IDE I use to run python files, it still didn't import it correctly. ModuleNotFoundError: No module named 'wordcloud'.
What am I missing here? Thanks!
EDIT: It works outside of Pycharm (just double clicking my python file), but I'd still like it to work in Pycharm.

A: I have the same problem and I've solved it.
When you create a project, you should choose 'inherit global site-packages

Or
You can use the terminal in the Pycharm to install the wordcloud.

You can also install wordcloud by File->Settings->Project:your project name->Project interpreter.


text:
Q: How to count the maximal number of letters in a string? How to count the number of (A I E O) letters in a string? I have tried to make it work but it doesn't for whatever reason. First i tried to add some more libraries and still it didn't work then i tried to add some more variables and work with cycle for,still no effect. I have this code which should do it but it just closes after execution.
#include <stdio.h>
#include <limits.h>
#include <string.h>
#include <conio.h>

int main()
{
    char str[100];
    char pick[4]={'A','E','I','O'};
    int i,j=0,kol,sor;

    printf("Write: ");
    scanf("%s",str);

   kol = INT_MIN;
   for(i=0;i<strlen(str);i++){
        if(str[i]==' '){
            j++;
           }
   }
   printf ("%d",j);
   int  words[j],max[j],min[j];
   words[0] = 0;
   for(i=0;i<strlen(str);i++){
    if(str[i]!=' '){
            for(int g=0;g<4;g++){
                if(str[i]==pick[g]){
                    words[j]+=1;
                }
            }
        }else{
                max[j]=i;
                j++;
                min[j]=i+2;
                words[j]=0;
            }
   }
   for(i=0;i<j;i++){
        if(kol<words[i]){
            kol=words[i];
            sor = i;
           }
   }
   for(i=min[sor];i<=max[sor];i++){
        printf("%c",str[i]);
   }

    return 0;
}

Maybe the code is wrong,maybe something more should be added?

A: Try the below code:
#include <stdio.h>

int main()
{
    char str[100];
    int a = 0, e = 0, i = 0, o = 0;
    printf("Write: ");
    fgets(str, sizeof(str), stdin);

    for(int c = 0; str[c]!= '\0'; c++)
    {
        switch(str[c])
        {
            case 'A':
            case 'a':
                a+=1;
                break;
            case 'E':
            case 'e':
                e+=1;
                break;
            case 'I':
            case 'i':
                i+=1;
                break;
            case 'O':
            case 'o':
                o+=1;
                break;
        }
    }

    printf("A = %d E = %d I = %d O = %d",a,e,i,o);
    return 0;
}

Given input is stored in "str". For loop is used to get individual characters from the string. Then it was checked with switch cases and the number of items is counted.
Note: You could remove switch cases with smaller case "a,e,i,o" if you need to count only Upper case characters.


text:
Q: binomial coefficient where k > n For solving binomial coefficients we have use from formula
$\frac{n!}{k!(n-k)!}$
This formula only works if n > k.
What happens if n < k? Is there another formula we need to use?

A: Your definition of "binomial coefficient" is too narrow. If $k$ is a nonnegative integer and $n$ is any real or complex number, the binomial coefficient $\binom nk$ is defined as follows:
$$\binom nk=\frac{n(n-1)(n-2)\cdots(n-k+1)}{k!}.$$
This is how the coefficient is understood in the general binomial theorem:
$$(1+x)^n=\sum_{k=0}^\infty\binom nkx^k.$$
The formula $\binom nk=\frac{n!}{k!(n-k)!}$ only applies in the special case where $n$ is an integer and $n\ge k.$
To answer your question, note that $\binom nk$ is a polynomial of degree $k$ in the variable $n,$ and its zeros are $0,1,2,\dots,k-1.$ Thus $\binom nk=0$ if $n$ is a nonnegative integer $\lt k.$ On the other hand, $\binom nk\ne0$ if $n$ is negative or fractional or non-real.


text:
Q: Can modules in Morea be marked as optional? I'd like to add to my course materials, some additional modules which will be marked as optional.
By optional, I mean that they have content (mostly static, e.g., readings) and are probably not going to be covered directly during the course lectures.
However, I'd like them still to appear below the main modules, but somehow separated and marked differently as, well, optional.
I guess I could index them last and also add "(Optiona)" text, but just wondering if there is a better solution for presenting them, e.g. a separating line, a tag like the "coming soon" option, etc.
Thanks

A: The simple approach is to list these modules last (by using a high value for morea_sort_order) and then add an Optional label (by using morea_labels). Here's an example:

If you want to get fancier, then you could edit the master/src/modules/index.md file to customize the way the modules page is rendered.  If you go this way, you could put a dividing line between the required and optional modules, add some CSS to change the border color or background of the optional modules, or anything else you want to do.


text:
Q: ggplot geom_line plot issue I have a big time series data set with thousands of values, and I am trying to plot a simple geom_line line plot, something like this:

But with my data I get this:

How can I fix this in R?
My data (df) structure is such that let's say I have 3 pixels in an area, and each pixel has a daily value.
Sample (dummy) data:
Pixel day      value
1     01/01/01  0
2     01/01/01  0.2
3     01/01/01  0.5
1     01/02/01  0.5
2     01/02/01  0.4
3     01/02/01  1
1     01/03/01  1
2     01/03/01  0.6
3     01/03/01  1.5

Code:
library(tidyverse)

ggplot(data = df, aes(x= day, y=value)) +
  geom_line() +
  xlab("")

A: That happened because you have multiple observations by day, so either you can summarise or plot one line per Pixel
Sample data
df <-
  structure(list(Pixel = c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L),
                 day = structure(c(11323, 11323, 11323, 11354, 11354, 11354,
                                   11382, 11382, 11382), class = "Date"), value = c(0, 0.2,
                                                                                0.5, 0.5, 0.4, 1, 1, 0.6, 1.5)), class = "data.frame", row.names = c(NA,
                                                                                -9L))

Original code
ggplot(data = df, aes(x= day, y=value)) +
  geom_line() +
  xlab("")

Adding group aesthetic
ggplot(data = df, aes(x= day, y=value, group = Pixel)) +
  geom_line() +
  xlab("")

Summarising code
df %>%
  #Calculating mean by day
  group_by(day) %>%
  summarise(value = mean(value,na.rm = TRUE)) %>%
  ggplot(aes(x= day, y=value)) +
  geom_line() +
  xlab("")


text:
Q: localhost returns different date format then online VPS When debugging an ASP.NET Core MVC website on Kestrel localhost the datetime output of an IHtmlHelper is displayed in the "swedish"
dateformat.
I want 2017-08-03. But when running the same website on a Digitalocean Ubuntu server located in "Amsterdam" the datetime output from the same IHtmlHelper is displayed as 8/3/17.
I have tried the following in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.Configure<RequestLocalizationOptions>(options =>
        {
            options.DefaultRequestCulture = new RequestCulture("sv-SE");
        });
}

But that doesn't make it. What can be the problem here?

A: You need set SupportedCultures and SupportedUICultures too, like this:
var mainCulture = new CultureInfo("sv-SE");
app.UseRequestLocalization(new RequestLocalizationOptions
{
    DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture(mainCulture, mainCulture),
    SupportedCultures = new[] { mainCulture },
    SupportedUICultures = new[] { mainCulture }
});

This code is for Startup.Configure(), for ConfigureServices use services.Configure as in your sample.


text:
Q: Radio button background goes white in Windows Chrome when using -webkit-backface-visibility. Any workarounds? There's a bug in Windows Chrome that makes a radio button's background turn white when its parent is both out of the document flow and has -webkit-backface-visibility applied.
Here it is in action:
http://jsfiddle.net/misterkeg/uMajC/
I'm using -webkit-backface-visiblity: hidden to get around the WebKit transition flicker bug.
This problem also occurs if I use the -webkit-transform: translateZ(0) fix instead, so it seems to kick in whenever hardware acceleration is active.
Overriding the input's -webkit-backface-visibility to visible doesn't help either.
Are there any known workarounds to this? I've filed a Chromium bug but would like to know if there are any ways around it in the meantime.

A: Better solution w/out having to use images:
Wrap the radio element in a div, and set that div's overflow to hidden, and border-radius to 100px. Then set the radio input to display block, and no margin. This worked for me:
Markup:

    <input type="radio" id="r1" name="r1">

CSS:
.radio_contain {
  display: inline-block;
  border-radius: 100px;
  overflow: hidden;
  padding: 0;
}
.radio_contain input[type="radio"] {
  display: block;
  margin: 0;
}

A: I have found the same problem but in different context, so might be it's not a problem with -webkit-backface-visiblity but with several combinations of things. In my case the problem arises when the page with the radio buttons contains a google maps like map (a propietary one, I haven't found what exactly in the map causes the problem) and is displayed inside an iframe.
If I hide the map with the inspector the radio buttons look ok, or if I view the page directly, not inside the iframe.
The only workaround I've found is in this page from CSS ninja: http://www.thecssninja.com/css/custom-inputs-using-css.
In summary, this is the solution (there is a live demo linked from the page I've mentioned, http://www.thecssninja.com/demo/css_custom-forms/):
HTML

 <input type="radio" name="input" id="input1" />
 Option 1

CSS
/*we hide the real radio button*/
.radio_image input[type=radio] {
  position:absolute;opacity:0;
}
/*we assign the span a background image
  which is a capture of the actual radio button*/
.radio_image input[type=radio] + span {
  background-image: url("radio-button.gif");
  background-position: left top;
  background-repeat: no-repeat;
  padding-left: 1.6em;
}
/*if radio is checked we change the background
  image to one with a checked radio button (it can be
  done with a sprite type background too): */
.radio_image input[type=radio]:checked + span {
  background-image: url("radio-button-checked.gif");
}

As the span is inside the label, clicking on it will have the same effect as clicking on the radio button itself, so the radio button still works ok.
I am working in a developement enviroment so I can´t post you the url, but with the code and the links above I think it's easy to see.
If you want to target just Chrome, you can try the solution provided in this post:
Can you target Google Chrome?
I hope it helps, I don't like such a complicated way to render just a simple radio button, in my case I've used it in the only page having that problem in my site and it has worked fine.

A: Here is an alternate solution that doesn't use images ( nor radio css edits ).
The solution results in a round white circle around the radio button ( if your design can tolerate that ) try this:
html:
<input type='radio'...>

css:
.radioWrap{
  background-color: white;
  padding: 4px 3px 1px 4px;
  border-radius: 10px;
}

That is it.


text:
Q: Use epsilon - N definition of Limit to verify the following limits I have this problem on my Real Analysis homework and I am stuck. The requirement is to use the $\epsilon - N$ definition of limit to verify.
$$
lim \frac{3n}{\sqrt{n^2+6n+2}} = 3
$$
This is my logical definition of limit that I am working with:
$$
\forall \space \epsilon >0 \space \exists \space N_{\epsilon}; \space N_{\epsilon} \space \epsilon \space \mathbb{N} \space \forall \space n \space \epsilon \space \mathbb{N} \space n > N_{\epsilon} \space |\{x\}_{n} - a| < \epsilon
$$
My work so far is:
$$
\{x\}_{n} = \frac{3n}{\sqrt{n^2+6n+2}}, \space a = 3 \\
\rightarrow | \frac{3n}{\sqrt{n^2+6n+2}} - 3| < \epsilon
$$
My strategy is to attempt to get a simplified fraction and transitivity to prove that there is a value between my series and epsilon such that for some index $N_{\epsilon}$ the definition is upheld. I'm currently stuck trying to simplify this fraction. Maybe there is no further simplification and I then just need to think of some value. Anyways,
$$
1. \space Let \space a = \frac{3n}{\sqrt{n^2+6n+2}} \space and \space b = 3 \\
2. \space Then \space we \space have \space (a-b) = \frac{a^2-b^2}{a+b} \\
a-b = \frac{(\frac{3n}{\sqrt{n^2+6n+2}})^2 - 3^2}{\frac{3n}{\sqrt{n^2+6n+2}} + 3} \\
= \space \frac{\frac{9n^2}{n^2+6n+2}-9}{\frac{3n}{\sqrt{n^2+6n+2}} + 3} \\
\frac{-54n-18}{n^2+6n+2} \times \frac{\sqrt{n^2+6n+2}}{3n+3\sqrt{n^2+6n+2}}
$$
This is where I get stuck. I don't think I am able to simplify this further, so at this point should I just be focusing on attempting to find a value larger than it that is simpler? What would a reasonable value look like? This fraction is messing with me a little bit. Appreciate any advice. Should I look at the triangle inequality to try to find a fraction?

A: There is a much simpler solution! Usually, such questions do not require you to do very complicated simplifications.
Possible solution:
Let $\varepsilon>0$ and $N_\varepsilon>\frac{9-3\varepsilon}{\varepsilon}$.
Then, for all $n>N_\varepsilon$ we get:
$\left|\frac{3n}{\sqrt{n^2+6n+2}}-3\right|=\left|\frac{3n}{\sqrt{(n+3)^2-7}}-3\right|<\left|\frac{3n}{n+3}-3\right|=\left|\frac{3n-3n-9}{n+3}\right|=\frac{9}{n+3}<\frac{9}{N_\varepsilon+3}<\frac{9}{\frac{9-3\varepsilon}{\varepsilon}+3}=\varepsilon$

A: You are correct. Given any $\epsilon>0$, your job is to find an $N$ so that if $n>N$, we have  $|x_n-3|<\epsilon$. This will typically be done by choosing $N$ large enough so that $$\frac{1}{N}<\epsilon$$ or something similar. Such choice of $N$ is dependent on the problem provided. You are under no obligation to preserve the form of the $x_n$ sequence in your verification, on the contrary, you are trying to actively force a simplification. For example, since $x_n$ is an increasing sequence, hence we can make the denominator larger and increase our distance to 3, so $$|x_n-3|<\left|\frac{3n}{\sqrt{n^2+6n+36}}-3 \right| = \left|\frac{3n}{n+6}-3 \right|= \frac{18}{n+6} $$ So we can now see what N to choose. Pick $N$ so large that $$\frac{18}{N+6}<\epsilon$$

A: Alternative approach:
This answer is somewhat off-topic, given the requirement that you are supposed to use an $\epsilon-N$ approach.  However, this answer does show how much easier the problem is to solve, with a different approach.
As suggested by the comment of CyclotomicField:
For all $n \in \Bbb{Z^+},$
$$n^2 < n^2 + 6n + 2 < n^2 + 6n + 9 = (n+3)^2.$$
Therefore, for all $n \in \Bbb{Z^+}$:
$$\frac{3n}{n} = \frac{3n}{\sqrt{n^2}} < \frac{3n}{\sqrt{n^2 + 6n + 2}} < \frac{3n}{\sqrt{(n+3)^2}} = \frac{3n}{n+3}. \tag1 $$
Using (1) above, per the Squeeze Theorem, it is sufficient to show that
$$\lim_{n\to\infty} \frac{3n}{n} = 3 ~~~\text{and}
 ~~~\lim_{n\to\infty} \frac{3n}{n+3} = 3. \tag2 $$
In (2) above, the first assertion is immediate, and the second assertion can be attacked via
$$\frac{3n}{n+3} = \frac{3n+9}{n+3} - \frac{9}{3n + 3}. $$
Therefore,
$$\lim_{n\to\infty} \frac{3n}{n+3} = \lim_{n\to\infty}\left[\frac{3n+9}{n+3} - \frac{9}{3n + 3}\right].\tag3 $$
In (3) above, you can use the fact that if
$$\lim_{n\to\infty} f(n) = A, ~\lim_{n\to\infty} g(n) = B ~: ~A, ~B ~~\text{finite} $$
Then
$$\lim_{n\to\infty} \left[f(n) - g(n)\right] = A - B.$$
Since $~3 \times (n+3) = (3n + 9),~$ clearly
$$\lim_{n\to\infty} \frac{3n+9}{n+3} = 3.$$
Further,
As $n \to \infty$, when examining the fraction $\dfrac{9}{n+3}$, the numerator is a constant and the denominator grows unbounded.  So (if desired) you can easily craft an $\epsilon - N$ demonstration that
$$\lim_{n\to\infty} \frac{9}{n+3} = 0.$$


text:
Q: C++ compiler error: ISO C++ forbids declaration of 'set' with no type I have some code in c++ in which my main.cpp includes a file SimpleGraph.h. When I try to compile I get:
In file included from main.cpp:9:
SimpleGraph.h:201: error: ISO C++ forbids declaration of 'set' with no type
SimpleGraph.h:201: error: invalid use of '::'
SimpleGraph.h:201: error: expected ';' before '<' token

It then goes on to similar errors in other lines. The line 201 specified here is:
std::set<int> getConvexHullPoints() const {return convexHullPoints;}

Similar errors I have found on stackoverflow usually seem to stem from a missing 'std::', but here it is present. Other people I know have used SimpleGraph.h with the same compiler and had no problems. So could it be the way I am calling it in main.cpp? Here I use:
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <vector>
#include "SimpleGraph.h"

using namespace std;

...then the main body of the program

Any help would be greatly appreciated.
Edit: I just needed
#include <set>

in main.cpp, as pointed out by hmjd and KennyTM. What a numpty, sorry for wasting your time. Thanks for helping me not to waste mine.

A: You need to #include <set>..

A: You need to #include <set> to use std::set.


text:
Q: Find ListBoxes in ASP .NET i have created dynamic listboxes (4 to 10) in ASP.NET.
and my question is , How do i find the dynamically created listboxes using c#?
thanks
Sure... and i appreciate your help . below code i am using for creating dynamic LB
protected void btndyfilter_Click(object sender, EventArgs e)
        {

            int numberOfListBox = lbFilter.GetSelectedIndices().Length;
            string lbname = lbFilter.SelectedValue;
            for (int i = 0; i < numberOfListBox; i++)
            {
                ListBox listb = new ListBox();
                ListItem lItem = new ListItem();
                listb.SelectionMode = System.Web.UI.WebControls.ListSelectionMode.Multiple;

                listb.Height = 150;
                listb.Width = 200;
                lItem.Value = i.ToString();

                lItem.Text = lbname;
                listb.Items.Add(lItem);
                panFilter.Controls.Add(listb);
                //once we created the LB dynamically i need to populate each LB with the corresponding values
                connstr2 = System.Configuration.ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
                conn2.ConnectionString = connstr2;
                conn2.Open();
                CubeCollection CubeList = conn2.Cubes;
                string cb = ddlCubeList.SelectedItem.Text;
                //need to remove the Hardcoded Code
                foreach (Member dimem in CubeList[cb].Dimensions["Date"].Hierarchies["Calendar Date"].Levels["Date"].GetMembers())
                {
                    ListItem Memlist = new ListItem();
                    Memlist.Text = dimem.UniqueName;
                    lbFilter.Items.Add(Memlist);

                }

            }
            panFilter.Visible = true;
            panCubeDef.Visible = true;
        }

so this will create the LB i believe :)... and Inside the commented code i need to use to populate for each LB item ..perhaps it bit hardcoded which i need to remove. so i all dynamic LBs are populated then the selected items from all LBs will come into the where clause in my MDX query..hope  i did not confuse you

A: There is 2 way either you can store dynamic control detail with dictionary or just find when you want to use it using some code like this
Control GetControlByName(string Name)
{
foreach(Control c in this.Controls)
    if(c.Name == Name)
        return c;

return null;
}

A: while generating ListBox dynamically, give ListBox ID as:
lstBoxNo1, lstBoxNo2. lstBoxNo3 etc. where 1,2,3(no) will be from count.
like
int count=1;
generate listbox control
listboxid=lastBoxNo+count;
count++
`by doing this, u have control over id's.
else use
http://stackoverflow.com/questions/3731007/using-findcontrol-to-find-control
using this link to understand findcontrol.

A: The points that you wont to find that dynamic controls are.

*

*The moment you first render the page.

*On every other post back.

In the case of 1, then you better keep a variable on your page that keep that creations.
In the case of 2, when you have post back, you need to store somehow the creations of your control in the page when you render it. One good place is to keep that information on the viewstate.
You can also on the post back, just to check if you have any post back valued from controls that you have named with a serial numbering starting from 1, eg You start looking if you have post back from ControlName_1, then ControlName_2, and when you not found any other value you end.


text:
Q: Cross Browser Test With Coded UI Locate Browser I am currently using Coded UI to test on IE and am using the Selenium cross browser components to extend this testing onto Chrome.
Before the most recent update to the dot net bindings from selenium these lines worked fine
BrowserWindow.CurrentBrowser = "chrome";
CurrentBrowser = BrowserWindow.Launch(onDemandURL);

Now I receive the following error stating a null value on the windowHandle
    at Microsoft.VisualStudio.TestTools.UITesting.UITestControl..ctor(IntPtr windowHandle)
   at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.FromWindowHandle(IntPtr windowHandle)
   at Microsoft.VisualStudio.TestTools.UITesting.UITestControlFactory.FromWindowHandle(IntPtr windowHandle)
   at Microsoft.VisualStudio.TestTools.UITest.Extension.CrossBrowser.CrossBrowserService.InitializeTopLevelWindow()
   at Microsoft.VisualStudio.TestTools.UITest.Extension.CrossBrowser.CrossBrowserService.InitializeCrossBrowserService(String[] args)
   at Microsoft.VisualStudio.TestTools.UITest.Extension.CrossBrowser.CrossBrowserService..ctor(String[] args)
   at Microsoft.VisualStudio.TestTools.UITest.Extension.CrossBrowser.BrowserServices.ChromeBrowserService..ctor(String[] args)
   at Microsoft.VisualStudio.TestTools.UITest.Extension.CrossBrowser.CrossBrowserService.<.cctor>b__0(String[] args)
   at Microsoft.VisualStudio.TestTools.UITest.Extension.CrossBrowser.CrossBrowserService.Launch(Uri uri)
   at Microsoft.VisualStudio.TestTools.UITest.Extension.CrossBrowser.CrossBrowserFactory.Launch(Uri uri)
   at Microsoft.VisualStudio.TestTools.UITesting.BrowserWindow.LaunchPrivate(Uri uri)
   at Microsoft.VisualStudio.TestTools.UITesting.BrowserWindow.<>c__DisplayClass15.<Launch>b__14()
   at Microsoft.VisualStudio.TestTools.UITesting.CodedUITestMethodInvoker.InvokeMethod[T](Func`1 function, UITestControl control, Boolean firePlaybackErrorEvent, Boolean logAsAction)
   at Microsoft.VisualStudio.TestTools.UITesting.BrowserWindow.Launch(Uri uri)

There seems to be an issue in the CrossBrowserService call to InitializeTopLevelWindow(). I'm not sure if that's a bug in the cross browser server or where it's coming from. That being said - is there any other way to launch the chrome browser and assign it to CurrentBrowser like I did above, where CurrentBrowser is of type BrowserWindow in this case. Or am I doing something wrong in the above 2 lines?


text:
Q: symfony accessing form values iteratively I want to access values of a form from a template. Poor symfony documentation and google are not helping. Assume I don't know the names of the fields. I don't want to do a $form->getObject()->getFieldName()
SOLUTION: Ok. I got this. $form->getValues() does a pretty good job for me.

A: Ok. I got this. $form->getValues() does a pretty good job for me.


text:
Q: Django Rest Framework: ModelSerializer and choosing fields per HTTP METHOD Say I have a phone book with 3 fields and a model to represent it:

*

*Name

*Age

*Phone

I'm writing an API to post new entries, get existing entries and modify existing entries. For the sake of this question, my constraints are:

*

*for POST I'd like to be able to write all three fields when creating a new record.

*for GET I'd like to return only the Age and Phone

*for PUT I'd like to allow only the phone field to be updated.

Given the rigidness of the class meta and where I can define extra_kwargs with definitions for each field such as read_only and write_only -- Will I need three separate ModelSerializer classes? or can I somehow have some kind of condition in a single ModelSerializer in order to support my constraints.
Thanks

A:
or can I somehow have some kind of condition in a single
  ModelSerializer in order to support my constraints.

Yes, you can in fact when most people start off using DRF. This is the approach taken. Certainly, I went down that path myself. But it's just not worth it.
It's much much easier and fewer lines of code to use multiple serializes. Specially if you are using Views instead of Viewsets. If you are using Viewsets, override the get_serializer_class


text:
Q: Mysql union select error I am trying to display all records from table1 even if the catid not existing in table2 (all employee in table2 should have all catid from table1 with 0 days if not exising in table2) with the following sql query but getting an error

Error Code: 1054. Unknown column 'catid' in 'group statement'

select empid,days from table2 union select catid from
table1 group by empid, catid;

table1:
catid
  1
  2
  3

table2:
empid catid days (computed column count(*))
1000    1    8
1000    3   10

expected result:
empid  catid  days
1000    1    8
1000    2    0 <---catid 2 and days 0 if catid not existing in table2 for empid 1000
1000    3   10

A: That is not the function of the union statement. Union statement does a set like capability which merging two sets. What you are looking for a is a join with the table 1 where you do a count and group by catid. Your data model to achieve this output itself is grievously wrong ;)
select employeeid, catid, sum(days) from table1, table2 group by employeeid, catid;

A: You just need a LEFT JOIN:
    Select tab2.empid, tab2.catid, ifnull(tab2.days, 0)
    from tab2
    left join tab1 on tab2.catid = tab1.catid

Please note : While doing a UNION the number and type of the columns present in the first select should be the same as the next Selects.
So you need to first make the select columns in sync first.

A: can you check this and add empid similarly.
SELECT TABLE1.CATID, IFNULL(TABLE2.DAYS,0) FROM table1 LEFT OUTER JOIN
table2 ON table1.catid = table2.catid

A: Please use LEFT JOIN with IFNULL.
Select table2.empid, table1.catid, IFNULL(table2.days, 0) from table2
LEFT JOIN table1 ON table2.catid = table1.catid;


text:
Q: Ant "Java" Task not running So I have this ant file and it works up until it gets to the "run" task. It cleans and compiles, but when it gets to "run", nothing happens. I don't even get an error message.
I know that it isn't a problem with the program it's running, since it runs fine when i do java Driver on the command line.
<project name="lab3" default="run">

  <target name="run" depends="compile">
      <java classname="Driver" fork="true"/>
  </target>

  <target name="compile" depends="clean">
     <javac srcdir="." includes="**/*.java" includeantruntime="false"/>
  </target>

  <target name="clean">
    <delete>
       <fileset dir="." includes="**/*.class, **/*.jar"/>
    </delete>
  </target>

</project>

a big thank you to anyone who will help a beginner out!

A: Try removing fork="true" from the <java> task. It is currently spawning a separate JVM.


text:
Q: Set page background without referring to  I am new to css and web design so please be gentle ;-)
I was wondering if it is possible to define the background of a page (i.e. what color the screen is) without referring to the  tag. So not doing the typical:
body { background-color: #fff; }

I need to do this since I am writing css to stylize our login page, but only have access to the template html to be inserted into the page body. So my html looks something like this (very simplified):

I couldn't find any answers online since this seems to be an unusual way of doing it.
So: Is this possible, if yes - how?

A: How about:

(put it above all your other html, and maybe use z-index: 1; if necessary)

A: You can use the :root selector if you don't mind about losing IE6-8 support.
But have you tried targeting body or html, in spite of the fact that they're not in the code? They still get inserted into the DOM.

A: In my opinion you need to discuss this with your team members and a superior. If you find a work around you may come to work tomorrow and find that someone has added
body {
  background-color: #not-white !important;
}

after your code and your next question is how to override !important in css.

A: On a side note, whoever made the restriction of not giving you access to css/main template should really not do that. If you continue working like that you'd end up with a lot of workarounds that will likely bite you.
Regardless of the restiction you could add a style tag like so:

which would take priority over the original body rule (assuming the body flow is not tampered with). This would be safer than setting background colour for * which would have unexpected side-effects. You may also want to set it through the shorthand background:#fff; which will reset any background image etc. previosly applied.
Update
I've just seen your comment

I did do that first (just target body) , but was friendly reminded by
  my team members to only style elements that are actually on the page I
  am working on... (which is not the case for body).

Assuming it's a valid argument and not some sort of petty tyranny going on, maybe it could be appropriate setting the background on the loginpage element? You could reference elements by ID like so:


text:
Q: Плюсы и минусы создания сервера на своем компьютере Не могу найти хорошего хостинга, тот дорогой, а тот не подходит. Решил рискнуть поставить на компьютер сервер, не могли бы вы написать плюсы и минусы этой затеи.
A: Плюсы:

*

*Ты сам себе хозяин.

*Много места для твоих проектов.

Минусы:

*

*Постоянный шум компьютера.

*Расходы на электричество.

*Убиваешь свое железо.

*Очень затратно.

*Нужно постоянно мониторить, обслуживать сервер.

*Постоянный онлайн, нужны средства на оплату трафика (если он не безлимитный)

Я бы не советовал заниматься данным мазохизмом, не пожалей пару баксов и возьми себе нормальный хостинг, меньше геморроя будет. Я бы посоветовал jino.ru. В любом случае это обойдется тебе дешевле, чем свой сервер. И я сомневаюсь что ты будешь использовать всю мощь своего сервера.
A: Плюсы имеются при выполнении двух условий:

*

*если есть ненужный компьютер,

*если есть бесплатный быстрый интернет.

Минусы:

*

*никакой поддержки (владелец уехал в отпуск - сервер упал),

*никакой надежности (отключили электричество в подъезде, сервер упал),

*никакой скорости (обычная домовая сеть),

*это не так уж и дешево (посчитайте, сколько стоит электричество и трафик).

Для более-менее серьезных проектов домашний сервер неприемлим из-за вышеуказанных минусов. Хороших хостингов, вообще говоря, много.
A: Во всяком случае, домашний сервер - это замечательный способ стать хорошим сисадмином.
A: Если не подходят хостинги, так можно же виртуальный сервер арендовать, если у буржуйской компании, то это не сильно дорого. Я думаю дешевле обойдётся, чем именно свой домашний  сервер.


text:
Q: Maven : Build project batch i have some problems for generate project with Maven (Windows).
First, i use the command "mvn archetype:generate" -> No problem
Second, i try to build project with batch with :
mvn -B archetype:generate -DarchetypeGroupId=org.apache.maven.archetype -DarchetypeArtifactId=maven.archetype.quickstart -DarchetypeVersion=1.1 -DgroupId=org.example.demo -DartifactId=ticket.batch -Dpackage=org.example.demo.batch

But i have the error : BUILD FAILURE :
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:3.2.0:generate (default-cli) on project ticket: The desired archetype does not exist (org.apache.maven.archetype:maven.archetype.quickstart:1.1)

Am I doing it wrong?
Thanks.

A: Seems like you'are searching for an archetype that does not exists as the exception "says".
You're propably seaching for this one :
maven-archetype-quickstart

and not the original
maven.archetype.quickstart

Here is the basic command (you have to had your customs options after theses ones):
mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4

Don't hesitate to accept as an answer if it help :)
if no i will came back


text:
Q: Attempt to read property "status" on null First time i try to log in in my website the website crash with error " status on null" , sometimes when i refresh it lets . I cant find the error.
public function authenticate()
{
        $this->ensureIsNotRateLimited();
        if (!Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) {
            RateLimiter::hit($this->throttleKey());
            throw ValidationException::withMessages([
                'email' => trans('auth.failed'),
            ]);
        }

        $user = $this->user();
        $customer = $user->customer;
        if ($customer->status !== CustomerStatus::Active->value) {

            /*the problem is here*/
            Auth::guard('web')->logout();

            $this->session()->invalidate();
            $this->session()->regenerateToken();
            throw ValidationException::withMessages([
                'email' => 'Your account has been disabled',
            ]);
        }

        RateLimiter::clear($this->throttleKey());
    }

Here is the customer status,
enum CustomerStatus: string
{
    case Active = 'active';
    case Disabled = 'disabled';
}

There ary many errors like this in my project , i tried this :
if ($customer->status ?? '' !== CustomerStatus::Active->value)
But then I cant log in , all my accounts become disabled.

A: You can check if the $customer variable is null before accessing its status property.
if (!$customer || $customer->status !== CustomerStatus::Active->value) {
    // handle disabled account
}

A: public function authenticate()
{
    $this->ensureIsNotRateLimited();
    if (!Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) {
        RateLimiter::hit($this->throttleKey());
        throw ValidationException::withMessages([
            'email' => trans('auth.failed'),
        ]);
    }

    $user = $this->user();
    $customer = $user->customer;

    if ($customer->status !== CustomerStatus::Active->value && $customer->status != null) {
        /*the problem is here*/
        Auth::guard('web')->logout();

        $this->session()->invalidate();
        $this->session()->regenerateToken();
        throw ValidationException::withMessages([
           'email' => 'Your account has been disabled',
        ]);
    }

    RateLimiter::clear($this->throttleKey());
}


text:
Q: Background-attachment: fixed and skew in chrome webkit I'm having an issue in Chrome. I have two <section> elements with background-attachment: fixed. When I apply a CSS3 skewY transform, the second <section> renders incorrectly.
I've made a jsfiddle of the problem. If you open it in chrome, scroll down. The second <section> doesn't scroll up correctly. If you open it in Safari, you can see the expected behavior.
Any ideas on how to solve this?


text:
Q: Show uitextview with keypad and toolbar when editing textfield
What is the right approach to achieve what you see in the gif? It's a tableview with textfields. When you tap a textfield, a textview shows up with it's keypad. I have a tableview with a custom tableviewcell with a textfield(valueTextField). And in cellforrow i set the inputview of the textfield to a UITextView. When i press the textfield, the textview is supposed to show the toolbar on top (with a "Done" button) but no toolbar shows. When i tap the textview, still no toolbar.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! EditProfileTableViewCell
    cell.isUserInteractionEnabled = true
    cell.valueTextField.isUserInteractionEnabled = true
    cell.valueTextField.delegate = self
    toolBar = UIToolbar()
    toolBar.sizeToFit()

    let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(editorDone))
    toolBar.setItems([doneButton], animated: false)

    editorTextView = UITextView(frame: CGRect(x:0, y:0, width:view.bounds.width, height:view.bounds.height))
    cell.valueTextField.inputAccessoryView = toolBar
        cell.valueTextField.inputView = editorTextView

    return cell
}

A: There are few things in your code you want to change.
1) This view's frame causes that strange behavior:
UITextView(frame: CGRect(x:0, y:0, width:view.bounds.width, height:view.bounds.height))

2) The reason why you make this mistake is because you are confusing
.inputAccessoryView
.inputView

3) The gif you posted is based on navigationBar buttons. Basically, it by tapping on the cell it presents a detailedViewController with two items set in navigationBar

A: The example you show is simply using a UINavigationController to navigate to a separate UIViewController when the cell is tapped. In this view controller, the UITextField will be handled something like this.
// View controller subclass conforming to UITextFieldDelegate protocol
class MyDetailViewController: UIViewController, UITextFieldDelegate {

    // Set an IB Outlet to the text field in storyboard
    @IBOutlet myTextField: UITextField!

    override viewDidLoad() {
        myTextField.delegate = self

        // ToolBar
        let toolBar = UIToolbar()
        // Optional styling
        toolBar.barStyle = .default
        toolBar.isTranslucent = true
        toolBar.tintColor = .black
        toolBar.layer.borderWidth = 0

        toolBar.sizeToFit()

        // Buttons
        let buttonOne = BarButtonItem(title: "One", style: .plain, target: self, action: #selector(yourSelectorOne(_:)))
        let buttonTwo = BarButtonItem(title: "One", style: .plain, target: self, action: #selector(yourSelectorTwo(_:)))

        let spacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)

       toolBar.setItems([buttonOne, spacer, buttonTwo], animated: false)
       toolBar.isUserInteractionEnabled = true
       textField.inputAccessoryView = toolBar
    }
}

This will create two buttons, one on the left and one on the right of the toolbar. The type of keyboard can be set in Interface Builder.
To get this by tapping on the text field in the cell directly, without navigating to a new view controller, you could set your custom UITableViewCell subclass as the text field delegate.
Note that you will need to provide method stubs to conform to the UITextFieldDelegate protocol. These are not essential for this example so I have omitted them. XCode will offer to populate them for you.


text:
Q: Object returning three value instead of one. Laravel I have used following code:
public function verify($id,$sid)
{
$sfees = sfee::where('student_id', $sid)->first(['mfee_id']);//mfee_id is the column I'm trying to recover
 foreach ($sfees as $sfee) {

    echo $sfee;

 }

The problem is that it is returning three 1. While it was supposed to return only one.
If i echo $sfees before foreach it returns only one value: {"mfee_id":1}.
What is the problem? Can anyone help me?

A: You are asking for one model, you don't need to try and iterate it, its a single model (object). (first() can return null though, so you should check)
$sfees->mfee_id;

If you just want the value of that column for that one record:
$mfee_id = sfee::where('student_id', $sid)->value('mfee_id');

Laravel 5.2 Docs - Query Builder - Retrieving Results - Retrieving A Single Row / Column From A Table

A: You should use return statement for returning from function, not echo.
public function verify($id,$sid)
{
    $sfees = sfee::where('student_id', $sid)->first(['mfee_id']);//mfee_id is the column I'm trying to recover

    return $some_variable;
}

A: Your problem is that that your trying to itterate over a single model. That's cause that you itterate over attributes and you get odd result the only think that you need is to do like this:
public function verify($id,$sid)
{
    $sfees = sfee::where('student_id', $sid)->first(['mfee_id']);//mfee_id

    echo $sfees->mfee_id;
 }

$sfees in this example is a single model not a collection of models becasuse you've used first to get it.


text:
Q: How manage state of different widgets in ListView flutter? I am building a Flutter App where a List is shown using ListView. Which returns a ListTile with User Information. The ListTile contains a leading, title and subtitle with trailing set as a ElevatedButton.
Here's how it looks like:

I want to tap on the 'Invite Button' and change its color, text, and subtitle of the ListTile
After tapping, it should look like this.

How can I do this? Here's the code that I wrote. But it's changing the state of every List Item.
class InviteFriends extends StatefulWidget {
  const InviteFriends({Key? key}) : super(key: key);

  @override
  State<InviteFriends> createState() => _InviteFriendsState();
}

class _InviteFriendsState extends State<InviteFriends> {

  bool isSelected = false;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }
}

UI Under ListView.builder:
                       ListTile(
                            title: const Text('Haris'),
                            subtitle: const Text(
                              isSelected ? 'Invitation Sent' : 'Not Invited Yet',
                            ),
                            leading: CircleAvatar(
                              backgroundImage: NetworkImage(
                                _userProfile!.profilePhoto.toString(),
                              ),
                            ),
                            trailing: ElevatedButton(
                              style: ElevatedButton.styleFrom(
                                elevation: 0.0,
                                primary: isSelected ? Colors.orange : Colors.green,
                                side: BorderSide.none,
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(10.0),
                                ),
                              ),
                              child: const Text(
                                isSelected ? 'Invited': 'Invite',
                              ),
                              onPressed: () {
                                setState(() {
                               isSelected = !isSelected;
                                });
                              },
                            ),
                          );

I also tried Keys here in ListTile by using ValueKey(index) but it didn't work either. What should I do? Thanks

A: Bring out Tile as a separate StatefulWidget so that each has its own state.
Do not modify State List.builder.
And you use one isSelected field for all Tile, and you will all refer to this condition.
Please provide more code and I can help. So that I understand the full picture

A: You need create different class for listtiles. Do as follows:
 ListView.builder(
        itemCount: 3,
        shrinkWrap: true,
        itemBuilder: (ctx, i) {
          return MyListItems();
        }))

then MyListItems.
    class MyListItems extends StatefulWidget {
  @override
  MyListState createState() => MyListState();
}

class MyListState extends State<MyListItems> {
  bool isSelected = false;

  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: const Text('Haris'),
      subtitle: Text(
        isSelected ? "Invitation Sent" : 'Not Invited Yet',
      ),
      leading: const CircleAvatar(
        backgroundImage: NetworkImage(
            'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQYtfZRhbGQtq2BapB2MXJfWIO2QriO5Wx3qQ&usqp=CAU'),
      ),
     // use your image here
      trailing: ElevatedButton(
        style: ElevatedButton.styleFrom(
          elevation: 0.0,
          primary: isSelected ? Colors.orange : Colors.green,
          side: BorderSide.none,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(10.0),
          ),
        ),
        child: Text(
          isSelected ? 'Invited' : 'Invite',
        ),
        onPressed: () {
          setState(() {
            isSelected = !isSelected;
          });
        },
      ),
    );
  }}

A:          return ListView.builder(
             itemCount: itemCount.length
              itemBuilder: (BuildContext context, int index) {
              return Friend(
              //arg if available
              );
    });

class Friend extends StatefulWidget {
  const Friend({Key? key}) : super(key: key);

  @override
  _FriendState createState() => _FriendState();
}

class _FriendState extends State<Friend> {
  bool isSelected = false;
  @override
  Widget build(BuildContext context) {
//put ListTile detail here
    return Row(
      children: [
        FlatButton(//deprecated but other buttons work
               key: PageStorageKey('random num'),//if you are interested in keeping the state of the button while navigating
            onPressed: () {
              setState(() {
                isSelected = !isSelected;
              });
            },
            child: Text(isSelected ? "INVITED" : "INVITE"))
      ],
    );
  }
}

A:
You create a list say "i" (variable) to know the state of each tile and initilze all with false. On tap change there state to true.

final List<bool> selected = List.generate(20, (i) => false);

Pass the List "i" to the listview.builder like:-

            itemBuilder: (BuildContext context, i)

See the full code
import 'package:flutter/material.dart';

class InviteFriends extends StatefulWidget {
  const InviteFriends({Key? key}) : super(key: key);

  @override
  State<InviteFriends> createState() => _InviteFriendsState();
}

class _InviteFriendsState extends State<InviteFriends> {
  bool isSelected = false;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  final List<bool> selected = List.generate(20, (i) => false);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.only(top: 60),
        child: ListView.builder(
            // itemCount: i,
            itemBuilder: (BuildContext context, i) {
          return ListTile(
            title: const Text('Haris'),
            subtitle: Text(
              selected[i] ? 'Invitation Sent' : 'Not Invited Yet',
            ),
            leading: const CircleAvatar(
              backgroundImage: AssetImage('assets/profile.gif'),
            ),
            trailing: ElevatedButton(
                style: ElevatedButton.styleFrom(
                  elevation: 0.0,
                  primary: selected[i] ? Colors.orange : Colors.green,
                  side: BorderSide.none,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                ),
                child: Text(
                  selected[i] ? 'Invited' : 'Invite',
                ),
                onPressed: () {
                  setState(() => selected[i] = !selected[i]);
                  // setState(() {
                  //   isSelected = !isSelected;
                  // });
                }),
          );
        }),
      ),
    );
  }
}

Thank you
Output


text:
Q: Selenium webdriver usage plan? Well I'm going to post some thoughts about a usage of Selenium NOT WAITING for response, but you're welcome if you want to give tips or tricks.
Need to start automation testing project to test: UI, functionality and performance (not sure but is very possible).
Want use Selenium as the base element of our testing BUT I'm a little bit confused about the Architecture that need to use, as this is my first time creating from scratch a bundle framework for automation testing need to know some stuff, for example...
What's the correct way to work with Selenium? I know about Page Object pattern but not sure on how to implement it, does it needs a real architecture like in a regular web app like MVC, or Data access layer or whatever?... I can't find any example of a complete framework testing ANY test-web-page..
What I mean?
Need to know how to implement correctly Selenium, any architecture, maybe using other tools like TestNg, Cucumber, or whatever...
other thing is to implement some kind of code repository (maybe git?) to work with members collaboration..
AND THEN...
what I need to know about WHO'S going to execute my automated test cases? is there a robot for it? need to investigate more about that and everything else :)

A: It sounds like you are new to the testing world...and so, I'll explain basic concepts concerning what you asked.
Selenium takes the browsers on your machine and runs them.  That's it, simply.
Performance testing is possible, but I believe there are better tools for doing that.  I won't go into them here.
In order to write selenium code, there are really two parts...the selector and the action.   The selector tells WebDriver which element to perform the action on.  Because webpages change (but the actions may not), and because you may use an element twice in different places in your code, we separate the selector and the actions in our code.
The result of this is Page Objects.  In Java they look like this:
@FindBy(id = "logoffBtn")
WebElement logOffButton;

This says "In the HTML, there's an element that has an id of logoffBtn.  Next time I use logOffButton, find that element, and perform that action on it".
Now for the rest of your questions:
TestNG/Cucumber are testing frameworks.  They allow you to organize your tests, and make them flexible/powerful.
I'm not going into Git/Subversion.  They make it so different people can code on the same project, and are beasts of their own.
Finally, you can get your tests to run on different machines, but somebody has to own them and keep them running.  The common (and best) way to do this is with Selenium Grid.


text:
Q: I want to change my ban command to not ban any staff members discord.py I want to be able to change this code to where staff cannot ban staff regardless of position and not go off higher roles like admins can't ban mods. I tried to tie it to the staff role but the bot does not send an output.
@commands.command()
@commands.has_permissions(ban_members=True)
@commands.bot_has_guild_permissions(ban_members=True)
async def ban(self, ctx, user, *, reason: commands.clean_content = '[No reason given]'):
    """ Ban a user from the current guild. """
    author = ctx.author
    guild = ctx.guild
    user = await self.fetch_user(ctx, user)
    if guild.get_member(user.id) and (guild.get_member(user.id).top_role.position >= guild.me.top_role.position): >This is where heirarchy comes into play
        raise GenericCustomException(
            "Sorry, but I can not ban that user. Maybe try checking my role hierarchy?"
        )
    else:  # this is where I try to pass the mod role to be ignored from banning each other
        if discord.utils.get(user.roles, id=<insert mod role id here>):
            return await ctx.send("you cannot ban a staff member")

A: I'd try searching if the user has a certain permission that one of your roles have, then if true, send the message. For example, if I wanted to see if the user had ban_members permissions:
if user.guild_permissions.ban_members:
    return await ctx.send("you cannot ban a staff member")

Make sure to replace ban_members with any other permission that suits your needs.

A: You can iterate through the roles of the user and check if he has a role in a list of mod roles. I prefer to use the role IDs since it can't be changed.
@commands.command()
@commands.has_permissions(ban_members=True)
@commands.bot_has_guild_permissions(ban_members=True)
async def ban(self, ctx, user, *, reason: commands.clean_content = '[No reason given]'):
    """ Ban a user from the current guild. """
    author = ctx.author
    guild = ctx.guild
    user = await self.fetch_user(ctx, user)
    if guild.get_member(user.id) and (guild.get_member(user.id).top_role.position >= guild.me.top_role.position): >This is where heirarchy comes into play
        raise GenericCustomException(
            "Sorry, but I can not ban that user. Maybe try checking my role hierarchy?"
        )
    else:
        whitelisted_roles = [123456, 456789, 789012] # List of Mod roles
        for role in user.roles:
            if role.id in whitelisted_roles:
                return await ctx.send("You can't ban this user! He is a moderator!")
        else:
            # ban the user
            pass


text:
Q: How to Dynamically change Youtube Player videoID I want to use the YT.Player code so that I can detect events. I have a CSV file with Youtube video ID's and a function that puts the ID's in an array and want to be able to dynamically change the ID when a user click an image. Essentially like this:
html

javascript
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// 3. This function creates an  (and YouTube player)
//    after the API code downloads.
// NOTE: videoId is taken out and instead is placed as the generated IFRAME src from the postSelection function

var player;
function onYouTubeIframeAPIReady() {
   player = new YT.Player('player', {
      height: '100%',
      width: '100%',
      videoId: '<<CALL TO FUNCTION OR VARIABLE HERE>>',
      events: {
         //'onReady': onPlayerReady,
         'onStateChange': onPlayerStateChange
      }
   });
}

If you are familiar with this code then what happens is the #player DIV is replaced by an IFRAME. I can change the IFRAME source with this function:
function postSelection() {
    $("#player").attr("src", _selected.attributes.url); //_selected.attributes.url comes from the CVS file
}

But this is very buggy and not cross browser friendly. If I use a standard IFRAME and not the YT Player API then everything works just fine. But I want to detect the end, and pause and so on so I have to use the API. My guess is that it is an issue with state and that persistence is lost some where in the creation of the IFRAME.
Regards.

A: This is very simple to do with the js api.  When you want to load a new video just call player.loadVideoById(videoId);  Details at https://developers.google.com/youtube/iframe_api_reference#loadVideoById

A: In case this is of help to anyone struggling as I did...
This player.loadVideoById(videoId)  was only working for me when videoId was hardcoded e.g.
player.loadVideoById('sdfexxdfse')
When I tried to put that value into a variable directly or when storing in an array it wasn't working even though it contained the same information.
The video was coming up with incorrect parameter each time.
Adding it to a variable in this way
var x = new String(variabledatahere)
did the job.


text:
Q: Failed to get D-Bus connection: Unknown error -1 on systemctl I unable to do operation (start, stop service etc) using systemctl on server, so that I tring to reinstall systemd-sysv packages but still facing same issue with systemctl.
root@localhost:~# systemctl daemon-reload
Failed to get D-Bus connection: Unknown error -1
root@localhost:~# systemctl start mongod
Failed to get D-Bus connection: Unknown error -1

D-bus status :
root@localhost:~# ps -ef | grep dbus
root      1524     1  0 16:39 ?        00:00:00 /usr/bin/dbus-daemon --fork --print-pid 4 --print-address 6 --session
109       2118     1  0 Jun24 ?        00:00:00 /usr/bin/dbus-daemon --system
root      2203 65058  0 17:13 pts/1    00:00:00 grep dbus
root     18311     1  0 Jul22 ?        00:00:00 /usr/bin/dbus-daemon --fork --print-pid 4 --print-address 6 --session

anyone have idea for this error ?


text:
Q: Induction proof for a function being in $C^{\infty}(\mathbb{R})$ Let $$f(t) = \begin{cases}
     0 & \text{: } x \le 0\\
     e^{-\frac{1}{t^2}}& \text{: } x > 0
\end{cases}$$
Prove that $f(t)$ is in $C^{\infty}(\mathbb{R})$.

I know that for a function to be in $C^{\infty}(\mathbb{R})$ it has to be infinitely times differentiable and each derivative must be continuous. I'm a bit stuck on how to prove this. I'm assuming the answer will need to be proved inductively. Ie:
Suppose the $f^{(n)}(t)$ is continuous. I need to then prove that $f^{n+1}(t)$ exists and is continuous. I'm not quite sure how to do this, I'm new to proofs by induction. I can also image proving continuity at $t=0$ may be a challenge.

A: Hint.
A standard example of a smooth non-analytic function is
$$
g(x)=\left\{\begin{array}{ll}e^{-\frac{1}{x}} & \text { if } x>0 \\ 0 & \text { if } x \leq 0\end{array}\right.
$$
A detailed proof for smoothness is given in this Wikipedia article:
https://en.wikipedia.org/wiki/Non-analytic_smooth_function#The_function_is_smooth
You can adapt the techniques for your example. A key step is to note that for any positive integer $m$,
$$
\lim_{x\downarrow 0}\frac{e^{-\frac1{x}}}{x^{m}}=0
$$
Alternatively, observe that
$$
f(x)=g(h(x))
$$
where $h(x)=x^2$ for $x\ge 0$ and $h(x)=0$ for $x<0$. You can show that $h$ is smooth. The result then follows from the chain rule.

A: A simple induction argument shows that for $x >0$ $f^{n}(x)$ can be written as $p_n(\frac 1 x) e^{-1/x^{2}}$ for some sequence of polynomials $(p_n)$ But $\lim_{y \to \infty} \frac {p_n(y)} {e^{y^{2}}} =0$ by L'Hopital's Rule. Put $y=\frac 1  x$ in this.

A: Find all derivatives of $f(x)$ everywhere on $\mathbb{R}$ except for $t = 0$. Then prove that all of them in fact are continuous at zero.


text:
Q: format phone number in csv using pandas Python/pandas n00b. I have code that is processing event data stored in csv files. Data from df["CONTACT PHONE NUMBER"] is outputting the phone number as `5555551212.0' Obviously, the ".0" is a problem, but added because it's an integer, I imagine?
Anyhoo, I decided that I should format the phone number for usability's sake.
The number comes from the csv file, unformatted. The number will always be ten digits: 5555551212, but I would like to display it as (555)555-1212.
import glob
import os
import pandas as pd
import sys

csvfiles = os.path.join(directory, '*.csv')
for csvfile in glob.glob(csvfiles):
    df = pd.read_csv(filename)
    #formatting the contact phone
    phone_nos = df["CONTACT PHONE NUMBER"]
    for phone_no in phone_nos:
        contactphone = "(%c%c%c)%c%c%c-%c%c%c%c" % tuple(map(ord,phone_no))

The last line gives me the following error:
not enough arguments for format string
But maybe this isn't the pandas way of doing this. Since I'm iterating through an array, I also need to save the data in its existing column or rebuild that column after the phone numbers have been processed.

A: I think phone numbers should be stored as a string.
When reading the csv you can ensure this column is read as a string:
pd.read_csv(filename, dtype={"CONTACT PHONE NUMBER": str})

You can use the string methods, naively adding:
In [11]: s = pd.Series(['5554443333', '1114445555', np.nan, '123'])  # df["CONTACT PHONE NUMBER"]

# phone_nos = '(' + s.str[:3] + ')' + s.str[3:7] + '-' + s.str[7:11]

Edit: as Noah answers in a related question, you can do this more directly/efficiently using str.replace:
In [12]: phone_nos = s.str.replace('^(\d{3})(\d{3})(\d{4})$', r'(\1)\2-\3')

In [13]: phone_nos
Out[13]:
0    (555)4443-333
1    (111)4445-555
2              NaN
3              123
dtype: object

But there is a problem here as you have a malformed number, not precisely 10 digits, so you could NaN those:
In [14]: s.str.contains('^\d{10}$')  # note: NaN is truthy
Out[14]:
0     True
1     True
2      NaN
3    False
dtype: object

In [15]: phone_nos.where(s.str.contains('^\d{10}$'))
Out[15]:
0    (555)4443-333
1    (111)4445-555
2              NaN
3              NaN
dtype: object

Now, you might like to inspect the bad formats you have (maybe you have to change your output to encompass them, e.g. if they included a country code):
In [16]: s[~s.str.contains('^\d{10}$').astype(bool)]
Out[16]:
3    123
dtype: object

A: I think the problem is that the phone numbers are stored as float64, so, adding a few things will fix your inner loop:
In [75]:

df['Phone_no']
Out[75]:
0    5554443333
1    1114445555
Name: Phone_no, dtype: float64
In [76]:

for phone_no in df['Phone_no']:
    contactphone = "(%c%c%c)%c%c%c-%c%c%c%c" % tuple(map(ord,list(str(phone_no)[:10])))
    print contactphone
(555)444-3333
(111)444-5555

However, I think it is easier just to have the phone numbers as string (@Andy_Hayden made a good point on missing values, so I made up the following dataset:)
In [121]:

print df
     Phone_no   Name
0  5554443333   John
1  1114445555   Jane
2         NaN  Betty

[3 rows x 2 columns]
In [122]:

df.dtypes
Out[122]:
Phone_no    float64
Name         object
dtype: object
#In [123]: You don't need to convert the entire DataFrame, only the 'Phone_no' needs to be converted.
#
#df=df.astype('S4')
In [124]:

df['PhoneNumber']=df['Phone_no'].astype(str).apply(lambda x: '('+x[:3]+')'+x[3:6]+'-'+x[6:10])
In [125]:

print df
       Phone_no   Name    PhoneNumber
0  5554443333.0   John  (555)444-3333
1  1114445555.0   Jane  (111)444-5555
2           NaN  Betty         (nan)-

[3 rows x 3 columns]

In [134]:
import numpy as np
df['PhoneNumber']=df['Phone_no'].astype(str).apply(lambda x: np.where((len(x)>=10)&set(list(x)).issubset(list('.0123456789')),
                                                                      '('+x[:3]+')'+x[3:6]+'-'+x[6:10],
                                                                      'Phone number not in record'))
In [135]:

print df
     Phone_no   Name                 PhoneNumber
0  5554443333   John               (555)444-3333
1  1114445555   Jane               (111)444-5555
2         NaN  Betty  Phone number not in record

[3 rows x 3 columns]

A: You can use the function clean_phone() from the library DataPrep. Install it with pip install dataprep.
>>> from dataprep.clean import clean_phone
>>> df = pd.DataFrame({'phone': [5555551212, '5555551212']})
>>> clean_phone(df, 'phone', output_format='national')
Phone Number Cleaning Report:
    2 values cleaned (100.0%)
Result contains 2 (100.0%) values in the correct format and 0 null values (0.0%)
        phone     phone_clean
0  5555551212  (555) 555-1212
1  5555551212  (555) 555-1212


text:
Q: How to get Variable Name of button on press? I have a problem with obtaining ID / Variable Name of buttons. Generally I want create lights out game. I created panel of buttons (NxN, N from combo box) but I don't know how to get single button's ID after press. Any idea?
    private void p1ActionPerformed(java.awt.event.ActionEvent evt) {
    String temp = jComboBox1.getSelectedItem().toString();
    ile=Integer.parseInt(temp);

    jPanel1.removeAll();
    jPanel1.setLayout(new GridLayout(ile,ile));
    for (int i = 0; i < ile; i++) {
        for (int j = 0; j < ile; j++) {
            JButton btn = new JButton();
            btn.setPreferredSize(new Dimension(40, 40));
            btn.setBackground(Color.green);
            btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
        /*What put here?*/
            }
            });
            jPanel1.add(btn);
            revalidate();
            pack();
        }
    }
}

A: You can get a reference to the button pushed through the ActionEvent's getSource() method.
e.g.,
public void actionPerformed(ActionEvent e)  {
   JButton selectedButton = (JButton) e.getSource();
}

Now, if you need to know where the button is in your grid, you will need to do more work, such as putting your buttons into an array or ArrayList, and then iterating through the array finding the index number of the selected button.
e.g.,
// changes to code marked with a //!! comment
private void p1ActionPerformed(java.awt.event.ActionEvent evt) {
  String temp = jComboBox1.getSelectedItem().toString();
  ile = Integer.parseInt(temp);

  jPanel1.removeAll();
  jPanel1.setLayout(new GridLayout(ile, ile));

  final JButton[][] buttons = new JButton[ile][ile]; //!!

  for (int i = 0; i < ile; i++) {
     for (int j = 0; j < ile; j++) {
        JButton btn = new JButton();
        btn.setPreferredSize(new Dimension(40, 40));
        btn.setBackground(Color.green);
        btn.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) {
              //!!
              JButton source = (JButton) e.getSource();
              for (int k = 0; k < buttons.length; k++) {
                 for (int l = 0; l < buttons[k].length; l++) {
                    if (buttons[k][l] == source) {
                       System.out.printf("row: %d, col: %d%n", l, k);
                       return;
                    }
                 }
              }
           }
        });
        jPanel1.add(btn);
        buttons[i][j] = btn; //!!
        //!! revalidate();
        //!! pack();
     }
  }
  jPanel1.revalidate(); //!!
  jPanel1.repaint(); //!!
}

As a side note, whenever I see removeAll() I think that perhaps this can be better achieved by using a CardLayout

As a second side note, I always cringe when I see "get variable name" in questions. Variable "names" aren't really all that important, don't exist for many objects, and almost don't exist in compiled code. And if an object is referred to by several variables, which one represents the "name" for this object? Much more important are object references, which is what most of the answers to your question have been dealing with.

A: The suggestion of Hovercraft Full Of Eels is good. Alternatively in your case you can use the button defined in your code, but you should make it final.
for (int i = 0; i < ile; i++) {
    for (int j = 0; j < ile; j++) {
        final JButton btn = new JButton();
        btn.setPreferredSize(new Dimension(40, 40));
        btn.setBackground(Color.green);
        btn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e)
        {
           // here we can use the variable btn - java will create an access method automatically
           System.out.println(btn.getText());
        }
        });
        jPanel1.add(btn);
        revalidate();
        pack();
    }
}

A: You have a ton of options (as you can see).
You can also use set/getName and/or set/getActionCommand, even set/getText, but I personally wouldn't rely on this...
for (int i = 0; i < ile; i++) {
    for (int j = 0; j < ile; j++) {
        JButton btn = new JButton();
        btn.setBackground(Color.green);
        String id = Integer.toString(i) + "x" + Integer.toString(j);
        btn.setName(id);
        // and/or
        btn.setActionCommand(id);
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                JButton btn = (JButton)e.getSource();
                String id = btn.getName();
                // and/or
                String id = btn.getActionCommand();
            }
        });
        jPanel1.add(btn);
    }
}
pack();