text:
Q: Spring State Machine task execution not firing I am having issues with getting a runnable to run in the manner described in the following reference:
http://docs.spring.io/autorepo/docs/spring-statemachine/1.0.0.M3/reference/htmlsingle/#statemachine-examples-tasks
TasksHandler handler = TasksHandler.builder()
    .task("1", sleepRunnable())
    .task("2", sleepRunnable())
    .task("3", sleepRunnable())
    .build();
handler.runTasks();

My implementation looks like this:
private Action<States, Events> getUnlockedAction() {
    return new Action() {
        @Override
        public void execute(StateContext sc) {
            System.out.println("in action..");
            handler = new TasksHandler.Builder().taskExecutor(taskExecutor()).task("1", dp.runProcess(1)).build();
            handler.addTasksListener(new MyTasksListener());

            handler.runTasks();

            System.out.println("after action..");
        }

    };
}

The initialization for the TaskExecutor looks like this:
    @Bean
public TaskExecutor taskExecutor() {
    ThreadPoolTaskExecutor te = new ThreadPoolTaskExecutor();
    te.setMaxPoolSize(50);
    te.setThreadNamePrefix("LULExecutor-");
    te.setCorePoolSize(25);
    te.initialize();
    return te;
}

My code for dp (DataProcessor) looks like this:
@Component
@Qualifier("dataProcessor")
public class ADataProcessor {

    public Runnable runProcess(final int i) {
    return new Runnable() {
        @Async
        @Override
        public void run() {
            long delay = (long) ((Math.random() * 10) + 1) * 1000;
            System.out.println("In thread " + i + "... sleep for " + delay);
            try {
                Thread.sleep(delay);
            } catch (InterruptedException ex) {
                Logger.getLogger(FSMFactoryConfig.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println("After thread " + i + "...");
        }

    };
    }
}

When i execute my code, I see the messages for 'in action..' and 'after action..' with no delay..
When I use the following:
                taskExecutor().execute(dp.runProcess(1));
            taskExecutor().execute(dp.runProcess(2));
            taskExecutor().execute(dp.runProcess(3));
            taskExecutor().execute(dp.runProcess(4));
            taskExecutor().execute(dp.runProcess(5));
            taskExecutor().execute(dp.runProcess(6));

I get what I would expect from using the TasksHandler..

*

*state changed to UNLOCKED

*In thread 2... sleep for 10000

*In thread 3... sleep for 5000

*In thread 4... sleep for 8000

*In thread 5... sleep for 4000

*In thread 6... sleep for 4000

*In thread 1... sleep for 9000

*Jan 13, 2016 12:32:13 PM - org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor initialize

*INFO: Initializing ExecutorService

*state changed to LOCKED

*After thread 5...

*After thread 6...

*After thread 3...

*After thread 4...

*After thread 1...

*After thread 2...

None of the messages before or after the delay in the sleep are displayed when using the TasksHandler.  So my question, how do I actually execute my runnable??  If I'm doing it correctly, what should I check?

A: I think you've slightly misunderstood few things. First you're linking to tasks sample having the original idea which were turned into a tasks recipe. It's also worth to look unit tests for tasks.
You register runnables with taskhandler get a state machine from it to start it and then tell handler to run tasks.
I now realize that in docs I probably should be bit more clear of its usage.

A: After adding all tasks to the handler, I had to start the state machine before invoking runTasks().
handler.getStateMachine().startReactively().block();
handler.runTasks();


text:
Q: If $a, b$ are positive integers, does $\;b\mid(a^2 + 1)\implies b\mid (a^4 + 1)\quad?$ If $a, b$ are positive integers, does $\;b\mid(a^2 + 1)\implies b\mid (a^4 + 1)\;$?
Explain if this is true or not. If no, give a counterexample.

A: Suppose $b = 5, a = 3$:
$$5\mid (3^2 + 1)\;\;\text{but}\;\;5 \not\mid (3^4 + 1)$$
Or, simply choose $a = 2, b= 5$ and again, $$5\mid (2^2 + 1)\;\;\text{but}\;\;5 \not\mid (2^4 + 1)$$

What is true is that  $b\mid (a^2 + 1) \implies b\mid(a^2 + 1)^2$,
but note that $$\begin{align}\;(a^2 + 1)^2 &= (a^4 + 2a^2 + 1) \\ \\ &= \left[(a^4 + 1) + 2a^2\right]\\ \\ &\neq (a^4 + 1)\end{align}$$

A: Hint: $\,\gcd(a^2\!+\!1,a^4\!+\!1) = \gcd(a^2\!+\!1,(a^2\!+\!1)(a^2\!-\!1) + 2) = \gcd(a^2\!+\!1,2)$

A: If positive integer $b$ divides $a^2+1$ and $a^4+1$ for some integer $a$
$b$ must divide $(a^4+1)-(a^2-1)(a^2+1)=2$
So, $b=1$ or $2$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Passing arguments to Maven release build I'm trying to release a library using Maven and perform a site-deploy to sourceforge (I have create an interactive shell first). The release is done by a Jenkins job (using the Maven Release Plugin for Jenkins).
I tried:
-X -e -Dresume=false -Dusername=puce release:prepare release:perform -Darguments="-Dusername=puce"

and
-X -e -Dresume=false -Dusername=puce -Darguments=-Dusername=puce release:prepare release:perform

but both times the job hangs at site:deploy of the first module:
 [INFO] --- maven-site-plugin:3.2:deploy (default-deploy) @ myproject-parent ---
 [INFO] Parent project loaded from repository: myGroupId:myOtherproject-parent:pom:1.0
 [INFO] Parent project loaded from repository: myGroupId:myOtherproject-parent:pom:1.0
 Using private key: /opt/jenkins/.ssh/id_dsa

When I stop the job, the following gets printed at end:
Password for ${username}@shell.sourceforge.net: channel stopped

which probably means that ${username} wasn't resolved.
How can I resolve the ${username}?
Edit:
Note that the following runs fine:
site-deploy -Psonatype-oss-release -Dusername=puce

Edit 2:
As part of release:perform maven executes the following command:
/usr/share/maven/bin/mvn -s /tmp/release-settings7797889802430474959.xml deploy site-deploy --no-plugin-updates --batch-mode -Psonatype-oss-release -P nexus -f pom.xml

-Dusername=puce doesn't seem to get passed to this maven command...
Also note that help:effective-pom shows the following maven-release-plugin configuration:
<plugin>
  <artifactId>maven-release-plugin</artifactId>
  <version>2.2.2</version>
  <configuration>
    <mavenExecutorId>forked-path</mavenExecutorId>
    <useReleaseProfile>false</useReleaseProfile>
    <arguments>-Psonatype-oss-release</arguments>
  </configuration>
</plugin>

So 'arguments' gets defined and its value seems to reach the embedded maven command instead of the value passed on the command line...

A: Overriding
<plugin>
  <artifactId>maven-release-plugin</artifactId>
  <version>2.2.2</version>
  <configuration>
    <mavenExecutorId>forked-path</mavenExecutorId>
    <useReleaseProfile>false</useReleaseProfile>
    <arguments>-Psonatype-oss-release</arguments>
  </configuration>
</plugin>

with
    <plugin>
        <artifactId>maven-release-plugin</artifactId>
        <configuration>
            <mavenExecutorId>forked-path</mavenExecutorId>
            <useReleaseProfile>false</useReleaseProfile>
            <arguments>-Psonatype-oss-release -Dusername=${username}</arguments>
        </configuration>
    </plugin>

in one of the parents did the trick.
It seems to be a bug that the value on the command line doesn't override the value in the POM.

A: What I've successfully done in the past is as follows:

*

*Define a property in the POM file, e.g.:
<properties>
    <release.arguments></release.arguments>
</properties>

*Add the POM property to the plugin configuration in the POM file, e.g.;
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-release-plugin</artifactId>
    <configuration>
        <arguments>${release.arguments}</arguments>
       ...

*Pass the argument through the property on the command-line, e.g.:
mvn release:prepare -Drelease.arguments="-N -Prelease"

Hope this helps.

A: My solution was similar to Sander Verhagen's. I added only line only though.
How I run:
mvn --batch-mode release:prepare -Denvironment=production

My config:
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-release-plugin</artifactId>
            <version>2.5.3</version>
            <configuration>
                <tag>${artifactId}-${version}-${environment}</tag>
                <arguments>-Denvironment=${environment}</arguments>
              <releaseProfiles>release</releaseProfiles>
            </configuration>
        </plugin>
    </plugins>
</build>

The difference is that now my submodules use the variable environment and I don't need to define it twice (I.e. -Darguments=-Denvironment=production -Denvironment=production). I also gives me the flexibility of not adding the properties tag.


text:
Q: Running makeCluster within withTimeout does not work The makeCluster function sometimes hangs in my code and just needs to be rerun to fix the issue.
In order to do that in my code I'm trying to use a while loop plus the withTimeout function to have the makeCluster function timeout if it is hanging and rerun itself.
The issue is that when I create my cluster with withTimeout I can't access it later for my parallel lapply.
library(parallel)
library(R.utils)
library(pbapply)

 cl = NULL

while( is.null(cl) ){

cl =  withTimeout({makeCluster(4,type = 'FORK')},timeout=3,
                         onTimeout="silent",envir = environment())
}

pblapply(1:3, function(x){x+1},cl = cl)

The error message I'm getting is:
Error in serialize(data, node$con, xdr = FALSE) :
  error writing to connection

A: When the envir argument of withTimeout() is not set, the clusters are created in .GlobalEnv and everything works as expected.
library(parallel)
library(R.utils)
library(pbapply)
cl <- NULL
while(is.null(cl)){
    cl <- withTimeout(makeCluster(4, type='FORK'), timeout=3, onTimeout="silent")
}
pblapply(1:3, function(x){x+1}, cl = cl)
  |++++++++++++++++++++++++++++++++++++++++++++++++++| 100% elapsed=00s
[[1]]
[1] 2

[[2]]
[1] 3

[[3]]
[1] 4

In the question you set envir = environment(), which will resolve to the calling environment of the function. The latter is different from .GlobalEnv and seems unsuitable for creating clusters. See also R eval(): changed behavior when argument 'envir' is explicitly set to default value for more information on environments.


text:
Q: Delphi creating a paint event canvas issues When I look at TWinControl, the Canvas is blanked out with clBtnFace and then the WM_PAINT is called. This causes an unavoidable flicker that I do not need. Also the canvas given allows drawing over the scroll bars making the scroll bars to be redrawn after a WM_PAINT event and creating more flicker.
GetMetrics and internal scrollbar Info gives the true canvas size. Correct me if I'm wrong, but I understand an HDC is a handle on the form that has a rectangular canvas to print on. So I'm thinking:

*

*how do I create a new HDC with a smaller width and height and not move the Top Left corner. I want to remove flicker by not using a WM_ERASEBKGND message if possible and not printing over scrollbars by allocating a newly sized HDC and then to set the Delphi canvas handle with the correct HDC.

*using a windows bitmap that I do not know if I should use and set the Bitmap canvas size for a BitBlt() copy as, TWinControl (Below).
DC := GetDC(0);
MemBitmap := CreateCompatibleBitmap(DC, ClientRect.Right, ClientRect.Bottom);
ReleaseDC(0, DC);
MemDC := CreateCompatibleDC(0);
OldBitmap := SelectObject(MemDC, MemBitmap);
try
  DC := BeginPaint(Handle, PS);
  Perform(WM_ERASEBKGND, MemDC, MemDC);
  Message.DC := MemDC;
  WMPaint(Message);
  Message.DC := 0;
  BitBlt(DC, 0, 0, ClientRect.Right, ClientRect.Bottom, MemDC, 0, 0, SRCCOPY);
  EndPaint(Handle, PS);
finally
  SelectObject(MemDC, OldBitmap);
  DeleteDC(MemDC);
  DeleteObject(MemBitmap);
end;

I do not know what option is better in a flicker free result and how to implement it in Delphi.

A:
...the Canvas is blanked out with clBtnFace...

The background color is adjustable with setting Brush.Color.

and then the WM_PAINT is called. This causes an unavoidable flicker...

This can be prevented by by-passing the WM_ERASEBKGND message.

How do I create a new HDC with a smaller width and height?

That is not possible. A device context has no size. It is only limitted by the window which hosts it.

The canvas given allows drawing over the scroll bars making the scroll bars to be redrawn after a WM_PAINT event.

Native scroll bars are drawn by the system in WM_NCPAINT. If you can draw over them, then you have gotten a device context of the whole window, not its client space.
But overall speaking, the solution is really simple: do not draw beyond the client region of a window.
And as a tip: I suggest that you derive your control from TCustomControl instead of TWinControl because that class has already a canvas you can draw on which eliminates all your WinAPI code.


text:
Q: for loop misses the first iteration #!/usr/bin/env python

new_trace=[1,2,2,3,2,1,4,3,2,1,3,4,3,5,6,4,7,6,5,4,5,4,6,6,5,6,4,4,5,6,7,7,6,5,5,7,6,5]

def extractIntervals(new_trace):
    listofAppearances=[[new_trace[0]],[0],[-1]]
    for i in range(0,len(new_trace)-1,1):
        if new_trace[i] in listofAppearances[0]:
            continue
        else:
            listofAppearances[0].append(new_trace[i])
            listofAppearances[1].append(i)
            listofAppearances[2].append(-1)
    print(listofAppearances)

    for j in range(len(new_trace)-1,0,-1):
        for k in range(0,len(listofAppearances[0])-1,1):
            if (new_trace[j]==listofAppearances[0][k]) and (listofAppearances[2][k]==-1):
                listofAppearances[2][k]=j
            else:
                continue

    print(listofAppearances)

def main():
    extractLivenessIntervals(new_trace)

if __name__ == "__main__":
        main()

In my code above I am trying to extract Intervals of appearance (delimited by 1st and last appearance indexes of every number in the list) The way I do it is I parse once the list and if the number still doesn't exist in listOfAppearances, then I append it to first column, the index to the second column and I set the 3rd column to -1.
I parse again the list in reverse every element is look for in the listofAppearances and the corresponding 3rd column is changed to the current index if still set to -1.
This works, but the first iteration when parsing the list backward has some issue that I can't figure out. the result I have with this example of a list is:
[[1, 2, 3, 4, 5, 6, 7], [0, 1, 3, 6, 13, 14, 16], [-1, -1, -1, -1, -1, -1, -1]]
[[1, 2, 3, 4, 5, 6, 7], [0, 1, 3, 6, 13, 14, 16], [9, 8, 12, 27, 37, 36, -1]]

As you can see the last element of the second list is still set to -1 which I don't understand why! I inspected every inch of the code and I can't see why is it this way!

A: Just change
for k in range(0, len(listofAppearances[0])-1, 1):

to
for k in range(0, len(listofAppearances[0]), 1):

in line 17.

Edit: you can get the same result by:
def extractIntervals(new_trace):
    listofAppearances = [0, 0, 0]
    listofAppearances[0] = list(set(new_trace))
    # returns new_trace without repeated elements

    listofAppearances[1] = [new_trace.index(i) for i in list(set(new_trace))]
    # returns a list with the index of the first occurrence
    # in new_trace of each element in list(set(new_trace))

    listofAppearances[2] = [len(new_trace) - 1 - new_trace[::-1].index(i) for i in list(set(new_trace))]
    # returns a list with the index of the last occurrence
    # in new_trace of each element in list(set(new_trace))

    print(listofAppearances)

A: Might I suggest processing a stream of values? First define a few helper functions, then use them to group each element with the positions at which it occurs.
from itertools import groupby
from operator import itemgetter

second = itemgetter(1)
first_and_last = itemgetter(0, -1)

def sort_and_group(seq, k):
    return groupby(sorted(seq, key=k), k)

def extract_intervals(new_trace):
    tmp1 = sort_and_group(enumerate(new_trace), second)
    tmp2 = [(val, *first_and_last([x for x,_ in positions])) for val, positions in tmp1]
    return zip(*tmp2)

new_trace=[1,2,2,3,2,1,4,3,2,1,3,4,3,5,6,4,7,6,5,4,5,4,6,6,5,6,4,4,5,6,7,7,6,5,5,7,6,5]

print(list(extract_intervals(new_trace)))

tmp1 is a pairing of each element with the list of positions at which it occurs.
tmp2 is a list of triples, consisting of a list element and the first and last position at which it occurs.
The call to zip "unzips" the list of triples into three tuples: the elements, the first positions, and the last positions.


text:
Q: Checking proof that space is not path connected I was going through Munkres and ran into a problem asking to show that
\begin{align*}
X & = \operatorname{cl} \left( \left\{ \left( x, \sin \frac{1}{x} \right) : 0 < x \leq 1 \right\} \right) \\
& = \left\{ \left( x, \sin \frac{1}{x} \right) : 0 < x \leq 1 \right\} \cup \left( \{0\} \times [-1, 1] \right)
\end{align*}
is not path connected. Having taken analysis, my first instinct was to say, "Oh! Weird stuff happens with $\sin \frac{1}{x}$ when you approach $0$!" So I came up with this. Does it work?
So let $p \in \{0\} \times [-1, 1] $, and $q = (1, \sin 1)$. I claim there does not exist a continuous function $f: [0, 1] \to X$ such that $f(0) = p, f(1) = q$. To do so, assume for contradiction that $f: [0, 1] \to X$ is continuous, and $f(0) = p, f(1) = q$. Then since $\{ 0 \} \times [-1, 1]$ is closed, we know that $f^{-1} (\{ 0 \} \times [-1, 1])$ is compact, so we set
\begin{align*}
c & = \max \left( f^{-1} (\{ 0 \} \times [-1, 1]) \right) \\
& = \max \{ t \in [0, 1] : f(t) = 0 \},
\end{align*}
where the maximum must exist by the extreme value theorem, and $c < 1$ because $f(1) = (1, \sin 1)$.
Now, we aim to show that $f$ is not continuous at $c$. Assume without loss of generality that $\pi_{2} (f(c)) \leq 0$. Let $0 < \epsilon < 1$, and let $\delta > 0$ be arbitrary. Then since $f$ is continuous, and thus so is $\pi_{1} \circ f$, we know by the intermediate value theorem that $\pi_{1}(f([c, c + \delta)))$ must contain an interval $[0, r)$ for some $r > 0$. Choose $N \in \mathbb{N}$ sufficiently large that $0 < \frac{1}{2 \pi N + \pi / 2} < r$. Then there exists $t \in [c, c + \delta)$ s.t. $f(t) = \left( \frac{1}{2 \pi N + \pi / 2}, 1 \right) $. Then
\begin{align*}
\| f(t) - f(c) \| & = \sqrt{ ( \pi_{2}(f(t)) - \pi_{2}(f(c)) )^{2} + ( \pi_{1}(f(t)) - \pi_{1}(f(c)) )^{2} } \\
& \geq \pi_{2}(f(t)) - \pi_{2}(f(c)) \\
& = 1 - \pi_{2}(f(c)) \\
& \geq 1 \\
& > \epsilon ,
\end{align*}
so $f$ is not right-continuous at $c$. This completes the proof.
Is the proof above correct? Is there another more typical one? Thanks.


text:
Q: Akka.net restart actor system termination on node quarentined We are developing a cluster with Akka.net v1.4.38 on we have seed nodes that communicate with a external system using Akka.IO.TCP, and multiple client nodes that receive and send messages to seed nodes. If a client node lost communication with the cluster we need to restart the Akka actor system on this node because is quarentined. We created a Actor that listen AssociationErrorEvent and ThisActorSystemQuarantinedEvent and restart the system when receive this messages.
public class ErrorManagerActor: ReceiveActor {
    public ErrorManagerActor(Action action) {
        Receive<ThisActorSystemQuarantinedEvent>(m => {
            action();
        });
        Receive<AssociationErrorEvent>(m => {
            action();
        });
    }
}

The problem is that the actor system never stop and show a warning in console:

[CoordinatedShutdown (akka://xxxxx)] Coordinated shutdown phase
[actor-system-terminate] timed out after 00:00:10

We created a UnitTest to reproduce the problem.
    [Test]
    public void TerminateSystemTest() {
        var actor = Sys.ActorOf(Props.Create<ErrorManagerActor>(() => {
            if (!Sys.Terminate().Wait(10000))
                Assert.Fail("Unable to terminate actor system");
            terminatedEvent.Set();
        }));
        Sys.EventStream.Subscribe(actor, typeof(AssociationErrorEvent));
        Sys.EventStream.Subscribe(actor, typeof(ThisActorSystemQuarantinedEvent));
        var cluster = Cluster.Get(Sys);
        Sys.EventStream.Publish(new ThisActorSystemQuarantinedEvent(cluster.SelfAddress, cluster.SelfAddress));
        terminatedEvent.WaitOne();
    }

A: The reason why your test fails is that in order for the ActorSystem to terminate it has to kill all actors first, including the one running your test assertion. So having an actor execute a blocking Task.Wait on System.Terminate will result in a deadlock.
To fix this in a production system, just don't wait on the Task.


text:
Q: Annoying JSON parsing Error index 2 out of range Been trying to wrap my head around it for hours now and I always end up with this annoying Error index 2 out of range error
I know there's plenty of questions about the error in stackoverflow but everyone seems to have a different problem with their code
JSONArray platforms = currentMovie.getJSONArray("platforms");
for (int y = 0; y < arrayPlatforms.length(); y++) {
    JSONObject currentPlatform = platforms.getJSONObject(i);
    String platform = currentPlatform.getString("name");
    String platformAbv = currentPlatform.getString("abbreviation");

    platforms.add(platform);
    Toast.makeText(getActivity(), ""+ platforms, Toast.LENGTH_SHORT).show();

    platformsAbbreviation.add(platformAbv);
    Toast.makeText(getActivity(), ""+ platformsAbbreviation, Toast.LENGTH_SHORT).show();
}

Both platforms and platformsAbbreviation are String ArrayList
Thanks!!!

A: It looks like you might have a typo in:
JSONObject currentPlatform = platforms.getJSONObject(i);
That i should probably be a y.


text:
Q: JScrollPane and jPlayer with playlist I'm trying to implement jScrollPane on a playlist generated by jPlayer (with playlist) but it's not working. I think what is happening is that jPlayer builds the playlist dynamically after jScrollPane has been initialized on the playlist ul element.
The jPlayer and jPlayerPlaylist work fine; and I can see the element css added by jScrollPane, which shows it's working, but the scrollbars are not visible. Possibly I'd need to call jScrollPane after the playlist has finished building? Does anybody have experience with these plugins?
Thanks!
The site is here: http://elricoshow.com

A: I finally figured it out, after a few tries… I think it was something with the css, maybe because I was trying to have a non-javascript version too, I'm not sure.
Anyways, I've managed to make some very nice scroll bars that blend well with the page, and that work better on a touchscreen (or with the mousewheel) than say a Carousel (because with the carousel you need to click for every advance).


text:
Q: How to define the calling program when using Iseries ODBC? Is there a way to define the calling 'program name' when using the Iseries ODBC driver? When I run a command against our AS400 using the Iseries Access ODBC driver, the calling program in the call stack of the as400 shows the program name as blank. I'd like to define one because we have a trigger that needs to know who is the caller.

A: The ODBC connection is proxied through a QZDASOINIT job.  I don't believe there is a way to identify the specific connection (or program) that fired the trigger.

A: As JamesA points out, all ODBC requests go through the QZDASOINIT job, so you can't change the call stack to determine the caller.
To get around this problem, DB2 for i includes client special registers that are automatically set by the ODBC driver (which you can override if you wish) and your trigger can then use. For more information see: http://ibmsystemsmag.blogs.com/i_can/2009/10/i-can-use-client-special-registers.html

A: It's been possible for some time, exposed only since i 6.1. For an example usage, run this statement in i Nav 'Run SQL Scripts...':
select CURRENT CLIENT_APPLNAME, CURRENT CLIENT_PROGRAMID, CURRENT CLIENT_WRKSTNNAME from sysibm.sysdummy1

Support is available to application developers using a JDBC, OLE DB, CLI, or .NET data provider. They can also be set by calling a special stored procedure.
Using IBMDASQL for example, a connection string might include:
conn.Open "Provider=IBMDASQL; Data Source=MyAS400;" & _
"Client User ID=MYWINUSRID; Client WorkStation Name=MYWINPC; " & _
"Client Program ID=somepc.exe; Application Name=Sample for Audit"

The SQL Reference discusses new "special registers".


text:
Q: Установка драйвера MySQL для Qt 5.12.2 Windows Имеется Qt 5.12.2 на Win10(1903)x64. нужно поставить драйвер для MySQL.
при этом в директории нужного мне компилятора творится вот такая вот ситуация.

Я предполагаю, что драйвер нужно собрать и поставил mysql 8.0 как этого требует оф. инструкция, но при попытке qmake мне в ответ вываливается сообщение
D:\Qt\5.12.2\Src\qtbase\src\plugins\sqldrivers\mysql>qmake "INCLUDEPATH += C:\Program Files\MySQL\MySQL Connector C 6.1\include" "LIBS+= C:\Program Files\MySQL\MySQL Connector C 6.1\lib\libmysql.lib" mysql.pro
Cannot read D:/Qt/5.12.2/Src/qtbase/src/plugins/sqldrivers/qtsqldrivers-config.pri: No such file or directory
Project ERROR: Library 'mysql' is not defined.

D:\Qt\5.12.2\Src\qtbase\src\plugins\sqldrivers\mysql>qmake -- MYSQL_INCDIR=C:/MySQL/include "MYSQL_LIBDIR=C:/MYSQL/MySQL Server 8.0/lib/opt"
Cannot read D:/Qt/5.12.2/Src/qtbase/src/plugins/sqldrivers/qtsqldrivers-config.pri: No such file or directory
Project ERROR: Library 'mysql' is not defined.

Как с этим бороться и как заставить MySQL работать в проектах?

A: Допустим, у меня база данных MySQL установлена в директорию D:/mysql, а Qt в директории D:\Qt

*

*Запустите консоль с настроенным окружением для Qt

*Смените директорию на D:\Qt\Qt5.11.2\5.11.2\Src\qtbase\src\plugins\sqldrivers

*Выполните команду qmake -- MYSQL_INCDIR=D:/mysql/include "MYSQL_LIBDIR=D:/mysql/lib"

*Выполните команду mingw32-make

*Результат компиляции (новые драйвера) можно найти в директории D:\Qt\Qt5.11.2\5.11.2\Src\qtbase\src\plugins\sqldrivers\plugins\sqldrivers

*Скопируйте новые драйвера в папку D:\Qt\Qt5.11.2\5.11.2\mingw53_32\plugins\sqldrivers

*Скопируйте файлы libmysql.dll и libmysqld.dll из директории D:\mysql\lib в директорию D:\Qt\Qt5.11.2\5.11.2\mingw53_32\bin
После проделанной работы, можете запускать свои проекты, которые используют соединение с базой данных MySQL.

A: Спасибо.
Заработало.
Фраза "с настроенным окружением для Qt" должна быть понята так: в QT Creator посмотреть, где реально расположен компилятор g++.exe (Инструменты - Параметры - Комплекты - Компиляторы - поле внизу - Путь к компилятору) - именно этот путь нужно прописать в path (я разместил его в системных).
mysql взял здесь https://downloads.mysql.com/archives/community/?version=5.6.23 - вторая кнопка - мне нужна было старенькая версия.


text:
Q: How to print day of the date without using inbuilt calendar date day packages, libraries in java In this program i want to print day of the date without using inbuilt calendar packages.. And i'm not able to get exact answer for certain dates (input date). in this i get day of the date correctly for only upto 31.12.0004. Note that it is the assessment given by my guide 5 days before still i'm not getting correct answer and I'm not supposed to use calendar packages and api's because syllabus for my course completed lists : basic array, if & else, for loops, class and objects.
import java.util.Scanner;
class calendarr
{
public static void main(String arg[])
    {
int z=0;
do{
    int id,im,iy;
    Scanner ip = new Scanner(System.in);
    System.out.print("Enter DD MM YYYY : ");
    id = ip.nextInt();
    im = ip.nextInt();
    iy = ip.nextInt();
    System.out.print("\n");

    int totalDays = 0, leapYearDays = 366, ordinaryYearDays = 365, y = iy-1,day=0;
    int totalDaysOfGivenYear,totalDaysUptoGivenMonth=0, totalDaysEntire;
    int leapYearCount = y%4, ordinaryYearCount = y - leapYearCount;
    int totalDaysUptoPreviousYear=0;
    int totalDaysUptoPreviousYearCount = (leapYearCount * leapYearDays)+(ordinaryYearCount * ordinaryYearDays);
    System.out.print("Odd Days Leap Year and Ordinary Year : "+leapYearCount+" "+ordinaryYearCount+"\n");

    String[] months = new String[] {"January","February","March","April","May","June","July","August","September","October","November","December"};
    int[] monthDates = new int[] {0,31,28,31,30,31,30,31,31,30,31,30,31};
    String[] weekDays = new String[] {"Saturday","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday"};

        if((iy%4==0)&&(iy%100!=0)||(iy%400==0))
            {
            monthDates[2] = 29;
            System.out.println("It is Leap Year");
            }
        else System.out.println("It is Ordinary Year");

    for(int i=1;i<=monthDates.length;i++)
        {

        totalDays = totalDays + monthDates[i-1];
        }
    for(int j=1;j<=im;j++)
        {
        totalDaysUptoGivenMonth = totalDaysUptoGivenMonth+monthDates[j];

        }
        totalDaysOfGivenYear = totalDaysUptoGivenMonth+id-monthDates[im];

        System.out.println("Total Days Upto Given Months : "+totalDaysOfGivenYear+"\nTotal Days of given year :  "+iy+" : "+totalDays);

        System.out.println("Total Count : "+totalDaysUptoPreviousYearCount);

        //totalDaysEntire = totalDaysUptoPreviousYearCount - totalDays+ totalDaysOfGivenYear;
        totalDaysEntire = totalDaysUptoPreviousYearCount+ totalDaysOfGivenYear-y;
        System.out.println("Overall Total Days : "+totalDaysEntire);

    /*//day = (365+366-totalDays+totalDaysUptoPreviousYearCount)%7;

        for(int k=0;k<=y;k++)
        {

        day = (totalDaysEntire%7);

        System.out.println(day+"\n"+weekDays[day]+"\n\n");
        }*/

    day = ((totalDaysUptoPreviousYearCount+ totalDaysOfGivenYear-iy)%7);

    System.out.println(day+"\n"+weekDays[day]+"\n\n");
}
while(z<5);

    }
}

output: Enter DD MM YYYY : 1 1 1
Odd Days Leap Year and Ordinary Year : 0 0
It is Ordinary Year
Total Days Upto given month : 1
Total days of given year : 1 : 365
Total Count : 0
Overall Total Days : 1
0
Saturday

A: Hey there were some fixes required in your code check this code it works now.
import java.util.Scanner;
public class calendarr
{
public static void main(String arg[])
    {
int z=0;
do{
    int id,im,iy;
    Scanner ip = new Scanner(System.in);
    System.out.print("Enter DD MM YYYY : ");
    id = ip.nextInt();
    im = ip.nextInt();
    iy = ip.nextInt();
    System.out.print("\n");

    int totalDays = 0, leapYearDays = 366, ordinaryYearDays = 365, y = iy-1,day=0;
    int totalDaysOfGivenYear,totalDaysUptoGivenMonth=0, totalDaysEntire;
    int leapYearCount = 0;
    //calculate the number of leap and non leap years
    for(int i=0;i<=y;i++){
        if((i%4==0)&&(i%100!=0)||(i%400==0))
            {
                leapYearCount++;
            }
    }
    int ordinaryYearCount = y - leapYearCount;
    int totalDaysUptoPreviousYear=0;
    int totalDaysUptoPreviousYearCount = (leapYearCount * leapYearDays)+(ordinaryYearCount * ordinaryYearDays);
    System.out.print("Odd Days Leap Year and Ordinary Year : "+leapYearCount+" "+ordinaryYearCount+"\n");

    String[] months = new String[] {"January","February","March","April","May","June","July","August","September","October","November","December"};
    int[] monthDates = new int[] {0,31,28,31,30,31,30,31,31,30,31,30,31};
    String[] weekDays = new String[] {"Saturday","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday"};

 if((iy%4==0)&&(iy%100!=0)||(iy%400==0))
            {
            monthDates[2] = 29;
            System.out.println("It is Leap Year");
            }
        else System.out.println("It is Ordinary Year");

    for(int i=1;i<=monthDates.length;i++)
        {
        totalDays = totalDays + monthDates[i-1];
        }
    for(int j=1;j<im;j++)
        {
        totalDaysUptoGivenMonth = totalDaysUptoGivenMonth+monthDates[j];

        }
        totalDaysOfGivenYear = totalDaysUptoGivenMonth+id;

        System.out.println("Total Days Upto Given Months : "+totalDaysOfGivenYear+"\nTotal Days of given year :  "+iy+" : "+totalDays);

        System.out.println("Total Count : "+totalDaysUptoPreviousYearCount);

        //totalDaysEntire = totalDaysUptoPreviousYearCount - totalDays+ totalDaysOfGivenYear;
        totalDaysEntire = totalDaysUptoPreviousYearCount+ totalDaysOfGivenYear;
        System.out.println("Overall Total Days : "+totalDaysEntire);

    /*//day = (365+366-totalDays+totalDaysUptoPreviousYearCount)%7;

        for(int k=0;k<=y;k++)
        {

        day = (totalDaysEntire%7);

        System.out.println(day+"\n"+weekDays[day]+"\n\n");
        }*/

    day = (totalDaysEntire%7);

    System.out.println(day+"\n"+weekDays[day]+"\n\n");
}
while(z<5);

    }
}

I had changed some things moved the setting the days of feb out of loop. Check the calculation for the number of years and non leap years . And also did the changes on finding totalDaysOfGivenYear, totalDaysEntire and the day variables.
Input : 1 1 1998
output:
Odd Days Leap Year and Ordinary Year : 485 1512
It is Ordinary Year
Total Days Upto Given Months : 1
Total Days of given year :  1998 : 365
Total Count : 729390
Overall Total Days : 729391
5
Thursday


text:
Q: Managing data on a subset of dataset using tidyverse Tidyverse makes data management a lot easier, and I am grateful to the developers who made it. I am familiar with the basic dplyr functions like group_by, filter, select, and mutate. However, there are times that I want to manage the data when there is a subset of the data.
Using the dplyr starwars dataset as an example, below are two tasks that I know how to manage using base R. I wonder what are the tidyverse equivalents.
library(dplyr, warn.conflicts = FALSE)
data(starwars)
dim(starwars)
#> [1] 87 14

In the starwars dataset, suppose that the data entry personnel made a mistake on two homeworlds.
Task 1: On the Tatooine homeworld, the hair color for all characters with a height at least 160 cm should be "blond". It is easy to do this in base R, but what is the tidyverse equivalent?
starwars[starwars$homeworld == "Tatooine" & starwars$height >160,
         "hair_color",
         drop = TRUE
] <- "blond"

Task 2: A bit more complicated. Suppose that there was a mistake made on Naboo (homeworld) where the missing mass was 80 kg, and want to exclude Gungan species on homeworld from the dataset. I also want to count the number of rows used for the Naboo homeworld only. In base R, this is straightforward, but due to the substantial data management, I need to assign an intermediate object.
# Make a subset for those from Naboo homeworld and delete from main dataset
starwars.Naboo <- starwars %>% filter(homeworld == "Naboo")
starwars <- starwars %>% filter(homeworld != "Naboo")

# Manage the subset of starwars.Naboo
starwars.Naboo <- starwars.Naboo %>%
    filter(species != "Gungan") %>%
    mutate(mass = coalesce(mass, 80)) %>%
    mutate(num = n())

# Re-add starwars.Naboo. num should be missing for all other homeworlds.
starwars2 <- bind_rows(starwars, starwars.Naboo)

# Check to ensure transformation works
starwars2 %>%
  tail(n = 15) %>%
  print(width = Inf)
#> # A tibble: 15 x 15
#>    name            height  mass hair_color skin_color       eye_color
#>    <chr>            <int> <dbl> <chr>      <chr>            <chr>
#>  1 Ratts Tyerell       79    15 none       grey, blue       unknown
#>  2 Wat Tambor         193    48 none       green, grey      unknown
#>  3 San Hill           191    NA none       grey             gold
#>  4 Shaak Ti           178    57 none       red, blue, white black
#>  5 Grievous           216   159 none       brown, white     green, yellow
#>  6 Tarfful            234   136 brown      brown            blue
#>  7 Raymus Antilles    188    79 brown      light            brown
#>  8 Sly Moore          178    48 none       pale             white
#>  9 Tion Medon         206    80 none       grey             black
#> 10 R2-D2               96    32 <NA>       white, blue      red
#> 11 Palpatine          170    75 grey       pale             yellow
#> 12 Gregar Typho       185    85 black      dark             brown
#> 13 Cordé              157    80 brown      light            brown
#> 14 Dormé              165    80 brown      light            brown
#> 15 Padmé Amidala      165    45 brown      light            brown
#>    birth_year sex    gender    homeworld   species films     vehicles  starships
#>         <dbl> <chr>  <chr>     <chr>       <chr>   <list>    <list>    <list>
#>  1         NA male   masculine Aleen Minor Aleena  <chr [1]> <chr [0]> <chr [0]>
#>  2         NA male   masculine Skako       Skakoan <chr [1]> <chr [0]> <chr [0]>
#>  3         NA male   masculine Muunilinst  Muun    <chr [1]> <chr [0]> <chr [0]>
#>  4         NA female feminine  Shili       Togruta <chr [2]> <chr [0]> <chr [0]>
#>  5         NA male   masculine Kalee       Kaleesh <chr [1]> <chr [1]> <chr [1]>
#>  6         NA male   masculine Kashyyyk    Wookiee <chr [1]> <chr [0]> <chr [0]>
#>  7         NA male   masculine Alderaan    Human   <chr [2]> <chr [0]> <chr [0]>
#>  8         NA <NA>   <NA>      Umbara      <NA>    <chr [2]> <chr [0]> <chr [0]>
#>  9         NA male   masculine Utapau      Pau'an  <chr [1]> <chr [0]> <chr [0]>
#> 10         33 none   masculine Naboo       Droid   <chr [7]> <chr [0]> <chr [0]>
#> 11         82 male   masculine Naboo       Human   <chr [5]> <chr [0]> <chr [0]>
#> 12         NA male   masculine Naboo       Human   <chr [1]> <chr [0]> <chr [1]>
#> 13         NA female feminine  Naboo       Human   <chr [1]> <chr [0]> <chr [0]>
#> 14         NA female feminine  Naboo       Human   <chr [1]> <chr [0]> <chr [0]>
#> 15         46 female feminine  Naboo       Human   <chr [3]> <chr [0]> <chr [3]>
#>      num
#>    <int>
#>  1    NA
#>  2    NA
#>  3    NA
#>  4    NA
#>  5    NA
#>  6    NA
#>  7    NA
#>  8    NA
#>  9    NA
#> 10     6
#> 11     6
#> 12     6
#> 13     6
#> 14     6
#> 15     6

Session_info
xfun::session_info("dplyr")
#> R version 4.0.4 (2021-02-15)
#> Platform: x86_64-w64-mingw32/x64 (64-bit)
#> Running under: Windows 10 x64 (build 19041)
#>
#> Locale:
#>   LC_COLLATE=English_United States.1252
#>   LC_CTYPE=English_United States.1252
#>   LC_MONETARY=English_United States.1252
#>   LC_NUMERIC=C
#>   LC_TIME=English_United States.1252
#>
#> Package version:
#>   cli_2.5.0        crayon_1.4.1     **dplyr_1.0.5**      ellipsis_0.3.2
#>   fansi_0.5.0      generics_0.1.0   glue_1.4.2       graphics_4.0.4
#>   grDevices_4.0.4  lifecycle_1.0.0  magrittr_2.0.1   methods_4.0.4
#>   pillar_1.6.1     pkgconfig_2.0.3  purrr_0.3.4      R6_2.5.0
#>   rlang_0.4.11     stats_4.0.4      tibble_3.1.2     tidyselect_1.1.0
#>   utf8_1.2.1       utils_4.0.4      vctrs_0.3.8

EDIT 1: For Task 2, can I avoid assigning an intermediate object in tidyverse? Is there a more elegant way to use this in the code above?

A: Looks like you've done 2 already?
starwars %>%
  mutate(
    hair_color = if_else(homeworld == "Tatooine" & height >160, "blond", hair_color)
  )

A: Your second task can be done in one pipe by
starwars %>%
  filter(homeworld == "Naboo",
         species != "Gungan") %>%
  mutate(mass = coalesce(mass, 80),
         num = n()) %>%
  bind_rows(starwars %>% filter(homeworld != "Naboo"))


text:
Q: async await @MainActor crash "Modifications to the layout engine must not be performed from a background thread" I have a crash when trying to reload collectionView inside the method update() which marked as @MainActor. "Modifications to the layout engine must not be performed from a background thread after it has been accessed from the main thread"
I know, that you should update the UI from main thread only. Using GCD it works
private func update() {
      DispatchQueue.main.async {
          collectionView.reloadData()
      }
}

I thought that if you mark you method with @MainActor in async/await world, then this function will be executed in the main thread automatically. But it crashes.
extension PhotosCollectionViewController: PHPhotoLibraryChangeObserver {
    func photoLibraryDidChange(_ changeInstance: PHChange) {
        update()
    }

    @MainActor private func update() {
        collectionView.reloadData()
    }
}

What am I missing?

A: @MainActor only works when using Swift concurrency and ensures that when you are in an async context calling a @MainActor annotated function is executed on the main thread (actually the actor's executor which in this case is always the main queue).
In your example you call the function in a synchronous context which uses the same thread it was called from (as always).


text:
Q: Wordpress theme with multiple color schemes I am building a WP theme and want to implement multiple color schemes. I looked through different free and premium themes and found out that this feature is developed different ways there and here. What is the best practice to make multiple color schemes support in a theme?

A: The short answer? Theme options page + secondary, conditionally-loaded CSS files = Joy in Mudville.


text:
Q: Vue how to redirect user after login to main components I'm just started learning Vue and I don't understand how to make "structure" of components, I mean: my login page should be as a main component which is loaded as first page in application, then after success login user should be redirected to main components (core application).
Can someone simply explain how to do that? What should be in App.vue? Where to place router-view responsible for login-view and where to place routers-views which are responsible for views which can be showed just after loggin?
Here's couple of pieces of my code:
App.vue
<template>

      <left-menu></left-menu>

      <router-view></router-view>

</template>

That's my routes.js, every component has same structure:
(basically that particular component should be loaded after loggin)
{
        path: '/orders',
        component: Orders,
        beforeEnter(to, from, next) {
            if (store.state.jwt) {
                next();
            } else {
                next('/login')
            }
        }
    }

and here's my Login component:
<template>

        <form @submit.prevent="submit">
            Podaj login
            <input type="text" v-model="login">

            Podaj hasło
            <input type="password" v-model="password">

            <button type="submit">Zaloguj</button>

        </form>

</template>


text:
Q: MNIST with TensorFlow-Inputs to a layer should be tensors I'm trying to exercise the TensorFlow Deep Convolutional Generative Adversarial Network based on the MNIST database. In order to test my coding abilities I downloaded the MNIST database directly from there website(instead of tf.keras.datasets.mnist.load_data()) and I have the following problem during executing the following line:
real_output = discriminator(images, training=True)
The error:
        raise TypeError('Inputs to a layer should be tensors. Got: %s' % (x,))
    TypeError: Inputs to a layer should be tensors. Got: pixel0```
What should I do to solve this?

A: Ok I solved it.
The solution is to normalize the images to values in the range -1 to 1:
train_images = (train_images - 127.5) / 127.5 # Normalize the images to [-1, 1]


text:
Q: Why can't I/ How can I move a project's source control location before it's checked-in? In TFS, I add a VS project (which adds the project into source control whether I want it to or not).  I realise I've made a mistake with its location, so I want to move the source control folder to the correct location.
However, the TFS option to 'move' is greyed-out until the project is checked-in.  Is TFS forcing me to check it in, and if so, why?

A: Because Move command is used for existing files/folders already checked into the TFS.
you have 2 options:

*

*Backup your project, undo add, move your project into the correct
location and add it again

*Check in your project into the wrong location and move it to the correct location after check-in


text:
Q: How to increment a numeric string in Python I've spent the last two days trying to figure out how to increment a numeric string in Python.  I am trying to increment a sequence number when a record is created.  I spent all day yesterday trying to do this as an Integer, and it works fine, but I could never get database to store leading zeros.  I did extensive research on this topic in StackOverflow, and while there are several examples of how to do this as an Integer and store leading zeros, none of the examples worked for me.  Many of the examples were from 2014, so perhaps the methodology has changed.  I then switched over to a String and changed my attribute to a CharField, and can get the function to work with leading zeros, but now I can't seem to get it to increment.  Again, the examples that I found on SO were from 2014, so maybe things have changed a bit.  Here is the function that works, but every time I call it, it doesn't increment.  It just returns 00000001.  I'm sure it's something simple I'm not doing, but I'm out of ideas.  Thanks in advance for your help.  Here is the function that works but doesn't increment.
def getNextSeqNo(self):
    x = str(int(self.request_number) + 1)
    self.request_number = str(x).zfill(8)
    return self.request_number

Here is the field as it's defined:
request_number = models.CharField(editable=True,null=True,max_length=254,default="00000")

I added a default of "00000" as the system is giving me the following error if it is not present:
int() argument must be a string, a bytes-like object or a number, not 'NoneType'

I realize the code I have is basically incrementing my default by 1, which is why I'm always getting 00000001 as my sequence number.  Can't seem to figure out how to get the current number and then increment by 1.  Any help is appreciated.

A: A times ago I made something similar
You have to convert your string to int and then you must to get its length and then you have to calculate the number of zeros that you need
code = "00000"
code = str(int(code) + 1 )
code_length = len(code)

if code_length < 5: # number five is the max length of your code
  code = "0" * (5 - code_length) + code

print(code)

A: Can this be done? Yes. But don't do it.
Make it an integer.
Incrementing is then trivial - automatic if you make this the primary key. For searching, you convert the string to an integer and search the integer - that way you don't have to worry how many leading zeros were actually included as they will all be ignored. Otherwise you will have a problem if you use 6 digits and the user can't remember and puts in 6 0's + the number and then doesn't get a match.

A: number = int('00000150')
('0'*7 + str(number+1))[-8:]

This takes any number, adds 1, concatenates/joins it to a string of several (at least 7 in your case) zeros, and then slices to return the last 8 characters.
IMHO simpler and more elegant than measuring length and working out how many zeros to add.

A: For those who want to just increase the last number in a string.

Import re

a1 = 'name 1'
num0_m = re.search(r'\d+', str(a1))
if num0_m:
    rx = r'(?<!\d){}(?!\d)'.format(num0_m.group())
    print(re.sub(rx, lambda x: str(int(x.group()) + 1), a1))


text:
Q: Angular 4 + Webpack - How can I support a relative PublicPath I'm unable to know the PublicPath at compile time, so it needs to be set dynamically at runtime for all associated resources.
Compile time example:
output: {
  publicPath: './test'
}

index.html...
<script type="text/javascript" src="./test/polyfills.js"></script>
<script type="text/javascript" src="./test/vendor.js">

SO THE PUBLICPATH IS PREFIXED TO THE SCRIPT SRC LOCATIONS, AND EVERYTHING WORKS OK...
Now, to do this at runtime seems to require webpack_public_path to be set within the Angular entry point (main.ts). So, for example I've set...
(https://github.com/webpack/docs/wiki/configuration)
declare var  __webpack_public_path__: string;
__webpack_public_path__ = './test';

But this doesn't seem to work?


text:
Q: Closed and exact forms, and functions $f : \mathbb{R}^2 \setminus \{ 0 \} \to S^1$ I have a simple question on the classic example of a closed form not being exact. It is well-known that the one-form
$$
\omega = \frac{x \mathrm{d}y - y \mathrm{d}x}{x^2 + y^2}
$$
is closed on $\mathbb{R}^2 \setminus \{ 0 \}$ (as can be verified by direct calculation), but is not exact. As a result, integrals of $\omega$ along non-homotopic paths can yield different results.
Of course, in the back of our heads, we know that $\omega$ is at least locally exact: it is the differential of $\arctan (y / x)$. Of course, I accept that this function is not well-defined on all of $\mathbb{R}^2 \setminus \{ 0 \}$; for example, it is clearly not well-defined at $x = 0$. This is closely related to the fact that $\arctan(y/x)$ has a branch cut, and cannot be continuously defined on all of $\mathbb{R}^2 \setminus \{ 0 \}$.
However, consider the following approach: instead of considering functions $f : \mathbb{R}^2 \setminus \{ 0 \} \to \mathbb{R}$, consider instead a function $\varphi : \mathbb{R}^2 \setminus \{ 0 \} \to S^1$, defined by
$$
e^{i \varphi(x,y)} = \frac{x+iy}{\sqrt{x^2 + y^2}}
$$
Here I'm considering $S^1$ as the unit circle in $\mathbb{C}$, for convenience. Clearly $\varphi(x,y)$ is a smooth $S^1$-valued function on all of $\mathbb{R}^2 \setminus \{ 0 \}$. On the other hand, whereas the original target space $\mathbb{R}$ was simply-connected, the new target space $S^1$ is not! As a result, $\varphi$ can "wind" by $2\pi n$ around the origin.
On the other hand, it's not at all clear that $d\varphi = \omega$ in the way I want it to. Indeed, it's not clear to me if one can even define the exterior derivative on a function $\varphi : M \to S^1$ the same way as for a function $f : M \to \mathbb{R}$. I suspect the reason that it 'seems' like it might work with $\varphi$ is because, whereas $\varphi$ is $S^1$-valued, its derivative is $\mathbb{R}$-valued. If I instead had an $S^2$-valued function (i.e., a function $\psi : M \to S^2$), I'm not sure how I'd generalize at all.
So, here is the final question: what is the mathematically precise way to describe the fact that $\omega$ has a well-defined antiderivative $\varphi(x,y)$ on all of $\mathbb{R}^2 / \{ 0 \}$, despite not being exact, by allowing the target space of $\varphi$ to be $S^1$ instead of $\mathbb{R}$?
EDIT: Just to be completely clear, in order to address some of the comments: I am considering here $S^1$ to be the set $\mathbb{R} / \sim$, where $x \sim x + 2\pi n$ for all $n \in \mathbb{Z}$. Then $\varphi : \mathbb{R}^2 \setminus \{ 0 \} \to S^1$, and $e^{i \varphi(x,y)}$ lies on the unit circle in $\mathbb{C}$. As a map between manifolds, $\varphi(x,y)$ is a smooth map; I'm certain that this could be verified by putting down coordinate charts, but it should be plainly obvious by noting that $\varphi$ is just the angular coordinate of the complex variable $z = x+iy$.

A: I think you are correctly describing. Maybe we don't say that $\varphi$ is an antiderivative, since it is not defined as a $\it{function}$ over the whole space $\mathbb{R}^2 \setminus \{ 0 \}$ (a function is a map to $\mathbb{R}$). Mathematically, to regard your $\varphi$ as a function (at least locally), we need to compose it with local coordinates $\theta$ of $S^1$ in the sense of manifolds, $S^1\supset U\overset{\theta}{\rightarrow} V\subset\mathbb{R}$. These local coordinates are not defined over the whole circle, hence $\theta\circ\varphi$ cannot be seen as a function over $\mathbb{R}^2\setminus \{0\}$ again. For example, the standard angle coordinate $\theta$ on $S^1$ has an ambiguity of 2$\pi\mathbb{Z}$ under monodromy, and so the "function" $\theta\circ\varphi$ is only multi-valued (not a mathematical function). But, this ambiguity vanishes after taking derivative, so $d(\theta\circ \varphi)$ is a well-defined 1-form over the circle, as you observed.
EDIT: The fact that the integral $\int_{S^1} \omega=2\pi\neq 0$ shows that there are no (single-valued, mathematical) function $f$ with $df=\omega$, i.e., $\omega$ is not exact. Please try searching de Rham cohomology for the context. Anyway, in these discussions we exclusively consider functions to $\mathbb{R}$ which is single-valued. Those to $S^1$ or to some covering spaces (multi-valued functions) are, although sometimes called functions in fact, of importance in completely different aspects.


text:
Q: Generic call for StartNew and ContinueWhenAll I'm not an expert in c# and quite new in TPL...
I have a lot of different task that I want to start and some depends on others. Also I want to decide from a xml config file if some of the task must be executed or not and then the ones depending on a task that is not going to be performed shall not wait until this task is executed.
Using if statements for all of this overcomplicates my code so I would like to do something like this:
static Task<bool> StartTask( List<Task<bool>> dependencies,
                             Func<bool> action)
{
    List<Task<bool>> filtered = new List<Task<bool>>();
    foreach (Task<bool> t in dependencies)
    {
        if (t != null)
        {
            filtered.Add(t);
        }
    }

    Task<bool> task;
    if (filtered.Count == 0)
    {
        task = (Task<bool>)tf.StartNew(action);
    }
    else
    {
        task = (Task<bool>)tf.ContinueWhenAll(filtered.ToArray(), ts => action);
    }

    return task;
}

So the idea is I generate the list of dependencies of every task at the beginning and then if any task is not performed filtering the list of null tasks...and if none of the ancestors of the task has been performed I call StartNew instead of ContinueWhenAll.....this way I set lists with the dependencies and call all the tasks in a generic way.
But I don't know whether this is doable and how to do it in c#. Any idea??
All the tasks returns bool but have different parameters.
Javier

A: I'd write it like this:
await Task.WhenAll(dependencies.Where(t => t != null));
await Task.Run(() => action());

I'd make the Where(t => t != null) part an argument validation and make it illegal to pass null tasks.


text:
Q: Inline css issues i want to ask if its possible to fix. I have inserted pay with paypal button, but its floating to the left. I want to make it in the middle, is it possible, i could use inline css but i cant.
i have tried like that:

<input type="image" src="https://mywebsite.com/img/cms/pay-try.png" style="margin-left:15px;" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">

but no result at all, its not moving
Best regards
Dilshod

A: Try putting it an a form and use text-align: center like

<form style="text-align:center" action="#" mehod="post">
    <input type="image" src="https://mywebsite.com/img/cms/pay-try.png" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
</form>

A:

<div style="text-align:center;">
    <input type="image" src="https://mywebsite.com/img/cms/pay-try.png" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
</div>


text:
Q: Swagger Documentation when the java class is deserialised from String input In my request body, I have a field which takes a string as input but is converted into a java object while deserializing.
public class UserCredentials {
  @NotBlank String username;
  @NotNull ReferenceString passwordRef;
}

the passwordRef value is taken as string and I used @JsonCreator to convert the string to ReferenceString object.
public class ReferenceString {
  private String identifier;
  private String type;

  @JsonCreator
  public ReferenceString(String secretRefConfigString) {
    // logic to break the string into two and set the
    // identifier and type value
    return;
  }

The serialization and deserialization work fine. I am having an issue with the swagger documentation, the documentation looks like
    "UserCredentials" : {
        "type" : "object",
        "required" : [ "passwordRef" ],
        "properties" : {
          "username" : {
            "type" : "string"
          },
          "passwordRef" : {
            "$ref" : "#/definitions/ReferenceString"
          }
        }
    }

    "ReferenceString" : {
      "type" : "object",
      "properties" : {
        "identifier" : {
          "type" : "string"
        },
        "type" : {
          "type" : "string"
        }
      }
    }

Since the API will take a string as input, I want that in the docs the type of passwordRef should be shown as String and not ReferenceString, also I don't want the user to see the internal class ReferenceString.
I read about @ApiModel and @ApiModelProperty. I can use the @ApiModelProperty on my fields and the documentation will show that field as a string, but in my code, a lot of fields will be of type ReferenceString and I don't want to use @ApiModelProperty on every field.
Can it be done easily some different way? Can I add some annotation/code only on the ReferenceString to solve this issue?


text:
Q: Using a python script to install a software with a custom interactive installer I have a program that I would like to automatically install by using a python script.
This program provides their installation file as an .exe file. It can be executed in a linux environment and initially prompts the user whether he would like to install this program and expects a key input [Y/n]. Then it are prompts the user to enter Acknowledged while showing the terms of service, and afterwards you are asked to specify a few more installation specifications, all through prompting keystrokes.
Is it possible to perform this installation process automatically? I thought about using subprocess.Popen to launch the exe, but don't know how to proceed from there and how to provide the correct inputs upon being prompted.


text:
Q: How can I check specific macro is there or not with identifier stored inside NSString I have macros named
CONSTANT_1
CONSTANT_2
CONSTANT_3
CONSTANT_4 etc..

I have an NSString variable sending from another class consist of macro name only, how can I access the contents of macro variable matching with this NSString.
My NSString variable is defined as:
NSString *str=@"CONSTANT_3"

A: 1 Here is one solution to do it, but it needs you to know all macros:
#define CONSTANT_1 1
#define CONSTANT_2 2
#define CONSTANT_3 3

#define STRINGIZE(x) #x

+ (int)getValueForContant:(NSString *)constantStr {
    const char *charStr = STRINGIZE(CONSTANT_1);
    NSString *str = [NSString stringWithUTF8String:charStr];
    if ([constantStr isEqualToString:str]) {
        return CONSTANT_1;
    }

    charStr = STRINGIZE(CONSTANT_2);
    str = [NSString stringWithUTF8String:charStr];
    if ([constantStr isEqualToString:str]) {
        return CONSTANT_2;
    }

    return -1;
}

And use it as:
int constVal = [ClassName getValueForContant:@"CONSTANT_1"];

It'll give you int value in return.
2 Use .plist to define constants and loop through to get appropriate value as provided string parameter to this method;
+ (int)getValueForContant:(NSString *)constantStr

A: I would recommend to better use constants
NSString *const CONSTANT_1 = @"1";
NSString *const CONSTANT_2 = @"2";
NSString *const CONSTANT_3 = @"3";

The you could use CFBundleGetDataPointerForName
-(NSString *)valueOfConstantWithName:(NSString *)constantName {
    void ** pointer = CFBundleGetDataPointerForName(CFBundleGetMainBundle(),   (__bridge CFStringRef)constantName);
    return (__bridge NSString *)(pointer ? *pointer : nil);
}

and use that method like
NSString *costant1 = [self valueOfConstantWithName:@"CONSTANT_1"];


text:
Q: Android Relativelayout Programmatically Basically I'm attempting to add rows to a table, I need to do this programmatically.
I can make it add the content I want, but not exactly how I want it.
For example I want a textview on the left with a button edittext button on the right.
Basically I want it like the image below:

.
Also I don't want to just and width to the textview.
Anyway here's what I've made so far:
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:padding="5dp" xmlns:android="http://schemas.android.com/apk/res/android">

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:id="@+id/linearLayout1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <Button
                android:id="@+id/btnOutstandingJob"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Outstanding Job" />

            <Button
                android:id="@+id/btnVanStock"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Van Stock" />

            <Button
                android:id="@+id/btnRegister"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:text="Register User" />
        </LinearLayout>

    </ScrollView>

    <RelativeLayout
        android:id="@+id/relativeLayout1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <Button
            android:id="@+id/btnLogout"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_marginTop="5dp"
            android:text="Log Out" />
    </RelativeLayout>

</LinearLayout>

Java:
TableLayout table = (TableLayout) findViewById(R.id.tableLayout1);

TableRow row = new TableRow(vanstock.this);

RelativeLayout RowLayout = new RelativeLayout(vanstock.this);
RowLayout.setId(99);

TextView lblItem = new TextView(vanstock.this);
lblItem.setId(1);
lblItem.setText("ddfsgsdfgs");

RelativeLayout.LayoutParams lblitemParam = new RelativeLayout.LayoutParams(
        RelativeLayout.LayoutParams.WRAP_CONTENT,
        RelativeLayout.LayoutParams.WRAP_CONTENT);
lblitemParam.addRule(RelativeLayout.CENTER_VERTICAL,
        RelativeLayout.TRUE);
lblitemParam.addRule(RelativeLayout.ALIGN_PARENT_LEFT,
        RelativeLayout.TRUE);

lblItem.setLayoutParams(lblitemParam);
RowLayout.addView(lblItem);

Button btnPlus = new Button(vanstock.this);
btnPlus.setId(4);
btnPlus.setText("+");
btnPlus.setWidth(40);

RelativeLayout.LayoutParams btnPlusParams = new RelativeLayout.LayoutParams(
        RelativeLayout.LayoutParams.WRAP_CONTENT,
        RelativeLayout.LayoutParams.WRAP_CONTENT);
btnPlusParams.addRule(RelativeLayout.ALIGN_PARENT_TOP,
        RelativeLayout.TRUE);
btnPlusParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,
        RelativeLayout.TRUE);
btnPlus.setLayoutParams(btnPlusParams);

RowLayout.addView(btnPlus);

EditText txtItem = new EditText(vanstock.this);
txtItem.setId(3);
txtItem.setWidth(40);

RelativeLayout.LayoutParams txtItemParams = new RelativeLayout.LayoutParams(
        RelativeLayout.LayoutParams.WRAP_CONTENT,
        RelativeLayout.LayoutParams.WRAP_CONTENT);
txtItemParams.addRule(RelativeLayout.ALIGN_PARENT_TOP,
        RelativeLayout.TRUE);
txtItemParams.addRule(RelativeLayout.LEFT_OF, btnPlus.getId());
txtItem.setLayoutParams(txtItemParams);

RowLayout.addView(txtItem);

Button btnMinus = new Button(vanstock.this);
btnMinus.setId(2);
btnMinus.setText("-");
btnMinus.setWidth(40);

RelativeLayout.LayoutParams btnMinusParams = new RelativeLayout.LayoutParams(
        RelativeLayout.LayoutParams.WRAP_CONTENT,
        RelativeLayout.LayoutParams.WRAP_CONTENT);
btnMinusParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
btnMinusParams.addRule(RelativeLayout.LEFT_OF, txtItem.getId());
btnPlus.setLayoutParams(btnMinusParams);

RowLayout.addView(btnPlus);
row.addView(RowLayout);

table.addView(row, new LayoutParams(LayoutParams.WRAP_CONTENT,
        LayoutParams.WRAP_CONTENT));

I've tried searching etc., but I still can't get it to work correctly.. Any help would be appreciated!

A:  LayoutInflater inflater = getLayoutInflater();
 TableRow row = (TableRow) inflater.inflate(R.layout.table,
                _tablelayout, false);
 TextView textview = (TextView) row.findViewById(R.id.rowdata);

Like this way you can fullfill your requirement.Is this sufficient??
Best
V.k


text:
Q: Jenkins groovy error java.lang.IllegalArgumentException: Expected named arguments but got [{returnStatus=true} ...] I am trying to run below code in Jenkins DSL pipeline but getting an error, what could be the issue
Closure test = { dockerImageName ->
    sh('''cd ''' + dir + ''' \
        && if make image ''' + dockerImageName + ''' 2>&1 | grep -m 1 "No rule to make target"; then exit 1; fi''',
        returnStatus: true
    )
}

Error
java.lang.IllegalArgumentException: Expected named arguments but got [{returnStatus=true}, cd dir && if make image docker-xxx.com/dir 2>&1 | grep -m 1 "No rule to make target"; then exit 1; fi]

A: You missed to give the argument name for the first argument, try as following:
Closure test = { dockerImageName ->
    sh(script: '''cd ''' + dir + ''' \
        && if make image ''' + dockerImageName + ''' 2>&1 | grep -m 1 "No rule to make target"; then exit 1; fi''',
        returnStatus: true
    )
}


text:
Q: NSUserDefaults returns null Can UILocalNotification be stored in NSUserDefaults?
I tried to get the value but it always returns null.
Here's the method that tries to get the value
-(IBAction)doneClicked:(id)sender
{
    NSUserDefaults *prefx = [NSUserDefaults standardUserDefaults];
    UILocalNotification *oldNotifObj = [prefx objectForKey:@"NotificationObject"];
    NSLog(@"oldNotifObj = %@",oldNotifObj);

    NSLog(@"enable notification");
    if (oldNotifObj == nil)
    {
        [self addNotification];
        NSLog(@"add a new one");
    }
    else
    {
        //if notification exist, remove old one, and add new one.
        [self removeNotification:oldNotifObj];
        [prefx setObject:nil forKey:@"NotificationObject"];
        [self addNotification];
        NSLog(@"remove old notification and add a new one");
    }
}

and here's the addNotification method
-(void)addNotification
{
    //set the notification
    UILocalNotification *localNotif = [[UILocalNotification alloc]init];
    localNotif.fireDate = self.timePicker.date;
    localNotif.repeatInterval = NSDayCalendarUnit;
    localNotif.alertBody = @"Hello world!";
    localNotif.soundName = UILocalNotificationDefaultSoundName;
    [[UIApplication sharedApplication]scheduleLocalNotification:localNotif];

    NSLog(@"localNotif = %@",localNotif);

    //saving notification to prefs
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    [prefs setObject:localNotif forKey:@"NotificationObject"];
    [prefs synchronize];
}

the oldNotifObj always return null.

A: Yes, it will return null. NSUserDefaults reads and writes the defaults using a property list file, so it only can manage property list types: NSString,NSNumber,NSData, NSDate, NSArray, NSDictionary.
All in all, you can't store an UILocalNotification in NSUserDefaults.

A: Try to convert the values manually in to an NSDictionary and try adding that to userdefaults. That solves this.
I mean you can  convert the items like localNotif.fireDate
localNotif.repeatInterval
localNotif.alertBody
localNotif.soundName etc into string objects and set them in to an NSDictionary. So you can save them into the userdefaults.
`


text:
Q: Echo JS variable in Joomla JText Ajax.php, Script tag in php file
<script>
 success: function(data) {
    var message = data.message; //Json data
    if ( data.status == 1 ) {
      jQuery("#msgError").html(<?php echo JText::_(' + message + ');?>);
    }
 }

Is it possible to Echo JS variable in php like above?

A: Here is a best example,
<?php
// In php write following code
JText::script('COM_HELLOWORLD_MESSAGE');

<script>
// Using in Javascript like this
Joomla.JText._('COM_HELLOWORLD_MESSAGE')

// For your example look like
 success: function(data) {
    if ( data.status == 1 ) {
      jQuery("#msgError").html(Joomla.JText._('COM_HELLOWORLD_MESSAGE'));
    }
 }
;
</script>

I already sent code to merge in joomla to make it more advanced. Please check it here https://github.com/joomla/joomla-cms/pull/6006
Also there are many ways to do it which you will find in above link.


text:
Q: Classloader issues - How to determine which library versions (jar-files) are loaded I've just solved another *I-though-I-was-using-this-version-of-a-library-but-apparently-my-app-server-has-already-loaded-an-older-version-of-this-library-*issue (sigh).
Does anybody know a good way to verify (or monitor) whether your application has access to all the appropriate jar-files, or loaded class-versions?
Thanks in advance!
[P.S. A very good reason to start using the OSGi module architecture in my view!]
Update: This article helped as well! It gave me insight which classes JBoss' classloader loaded by writing it to a log file.

A: If you've got appropriate versions info in a jar manifest, there are methods to retrieve and test the version.  No need to manually read the manifest.
java.lang.Package.getImplementationVersion() and getSpecificationVersion() and isCompatibleWith() sound like they'd do what you're looking for.
You can get the Package with this.getClass().getPackage() among other ways.
The javadoc for java.lang.Package doesn't give the specific manifest attribute names for these attributes.  A quick google search turned it up at http://java.sun.com/docs/books/tutorial/deployment/jar/packageman.html

A: In the current version of Java, library versioning is a rather wooly term that relies on the JAR being packaged correctly with a useful manifest.  Even then, it's a lot of work for the running application to gather this information together in a useful way. The JVm runtime gives you no help whatsoever.
I think your best bet is to enforce this at build time, using dependency management tools like Ivy or Maven to fetch the correct versions of everything.
Interestingly, Java 7 will likely include a proper module versioning framework for precisely this sort of thing. Not that that helps you right at this moment,

A: I don't think there is a good way to check that. And I'm not sure you want to do that. What you need to do  is get familiar with your app-server's class loading architecture, and understand how that works.
A simplified explanation of how it works is: an EJB or a web-app will first look for a class or a resource in  libraries declared in its own module (ejb-jar or war). if the class is not found there, the class loader forwards the request to the its parent class loader which is either a declared dependency (usualy an ejb) or the the application class loader which is responsible to load libraries and resources declared in the ear package. If the class or the resource is still not found the request is forwarded to the app server which will look in its own classpath.
This being said, you should remember that a Java EE module (web-app, ejb) will always load classes from a jar that is in the nearest scope. For example if you package log4j v1 in the war file, log4j v2 at ear level and you put log4j v3 in your app-server's class path, the module will use the jar in its own module. take that away and it'll use the one at ear level. take that out and it will use the one in the app-server's classpath. Things get more tricky when you have complex dependencies between modules.
Best is to put application global libraries at ear level.

A: If you happen to be using JBoss, there is an MBean (the class loader repository iirc) where you can ask for all classloaders that have loaded a certain class.
If all else fails, there's always java -verbose:class which will print the location of the jar for every class file that is being loaded.

A: There must be a better way than the way I do it, but I tend to do this in a very manual way.

*

*Every Jar must have it's version number in the file name (if it doesn't change it's name).

*each application has it's own classpath.

*There must be a reason to start using an updated Jar (new version). Don't just change because it is available, change because it gives you functionality that you need.

*Each release must include all Jars that are needed.

*I keep a Version class that knows the list of Jars it needs (this is coded into the source file) and can be checked at runtime against the list of Jars in the classpath.

As I said, it is manual, but it works.


text:
Q: Filter MultiIndex with Query Strings I have a fairly large DataFrame, say 600 indexes, and want to use filter criteria to produce a reduced version of the DataFrame where the criteria is true. From the research I've done, filtering works well when you're applying expressions to the data, and already know the index you're operating on. What I want to do, however, is apply the filtering criteria to the index. See example below.
MultiIndex is bold, names of MultiIndex names are italic.

I'd like to apply the criteria like follows (or something) along these lines:
df = df[MultiIndex.query('base == 115 & Al.isin(stn)')]
Then maybe do something like this:
df = df.transpose()[MultiIndex.query('Fault.isin(cont)')].transpose
To result in:

I think fundamentally I'm trying to produce a boolean list to mask the MultiIndex. If there is a quick way to apply the pandas query to a 2d list? that would be acceptable. As of now it seems like an option would be to take the MultiIndex, convert it to a DataFrame, then I can apply filtering as I want to get the TF array. I'm concerned that this will be slow though.

A: As you noticed, indexes aren't great for querying using filter expressions. There's df.filter() but it doesn't really seem to work well on a MultiIndex.
You can still filter the MultiIndex values as an iterable of Python tuples, and then use .loc to access the filtered results.
This works:
rows = [(season, cont)
        for (season, cont) in df.index
        if 'Fault' in cont]
cols = [(stn, base)
        for (stn, base) in df.columns
        if base == 115 and 'Al' in stn]
df.loc[rows, cols]

A: If what you're after is using the df.query() nifty syntax to slice your data, then you're better off "unpivoting" your DataFrame, turning all indices and column labels into regular fields.
You can create an "unpivot" DataFrame with:
df_unpivot = df.stack(level=[0, 1]).rename('value').reset_index()

Which will produce a DataFrame that looks like this:
  season cont  stn   base value
0 Summer Fault Alpha  115   1.0
1 Summer Fault Beta   115   0.8
2 Summer Fault Gamma  230   0.7
3 Summer Trip  Alpha  115   1.2
4 Summer Trip  Beta   115   0.9
...

Which you can then query with:
df_unpivot.query(
    'cont.str.contains("Fault") and '
    'stn.str.contains("Al") and '
    'base == 115'
)

Which produces:
  season cont  stn   base value
0 Summer Fault Alpha  115   1.0
6 Winter Fault Alpha  115   0.7

Which is the two values you were expecting.


text:
Q: curl or file_get_contents ignore output I need to run a php code in a different server (let's call it server 2) from server 1.
In server 1, I have something like this
<?php
file_get_contents('http://domain_in_server_2.com/php-script.php');
?>

The problem is, this request may take long time, and I don't need to get the output. I just want to trigger the script without having to wait or getting the output.
Is there anyway to accomplish what I want?
Thank you very much.

A: You can use a socket. See this example.
Edit:
Here is the code from the above link:
// Example:
// post_async("http://www.server.com/somewhere",array("foo" => 123, "bar" => "ABC"));

function post_async($url, $params)
{
    // Build POST string
    foreach ($params as $key => &$val) {
      if (is_array($val)) $val = implode(',', $val);
      $post_params[] = $key.'='.urlencode($val);
    }
    $post_string = implode('&', $post_params);

    // Connect to server
    $parts=parse_url($url);
    $fp = fsockopen($parts['host'],isset($parts['port'])?$parts['port']:80,$errno, $errstr, 30);

    // Build HTTP query
    $out = "$type ".$parts['path']." HTTP/1.1\r\n";
    $out.= "Host: ".$parts['host']."\r\n";
    $out.= "Content-Type: application/x-www-form-urlencoded\r\n";
    $out.= "Content-Length: ".strlen($post_string)."\r\n";
    $out.= "Connection: Close\r\n\r\n";
    $out.= $post_string;

    // Send data and close the connection
    fwrite($fp, $out);
    fclose($fp);
}


text:
Q: Using Require with React in a web page without node I know this might be a silly question to some of you, but I am beginner in React, and I wish to create a really simple application.
I found a sample in which every component is saved in a separate js file, which looks very good for modularity and re-usage.
The only thing I need to take care of now is using export/require. However, I don't need to be dependent on nodejs. I just need a simple html/js application that can run on any cheap web server.
I read somewhere that I can use "Browserify", but after looking at it, it seems like a node library.
Is there any library that I can use from a web page (via cdn for example) that allow me to use require? If not, does that mean I can not separate react components in different files?

A:
However, I don't need to be dependent on nodejs.

Use NodeJS. It is how React applications are designed to be built.

I just need a simple html/js application that can run on any cheap web server

NodeJS is only required at build time. You run it on your development workstation. The output is static files that you can upload to any webserver.
(NB: React applications are often designed to make HTTP requests to get dynamic data. Some tutorials cover using Node to build a server to listen for and make responses to those requests. Make sure you don't conflate the program to transpile the React application to ES5 (which runs at build time) with the program to run a webserver (at runtime) even if both are written using Node).

A: If you don't want to use Node, you can use webpack: https://webpack.github.io/
you will generate a static/bundle.js . If you want to learn more about it, I sugest http://survivejs.com/

A: What you need is a build step that packs the separate files into one or more packages that can be loaded in the browser.
Browserify can be used to do that, but WebPack is also popular.
These tools require some configuration, so I think that the best way to start is with a tool like create-react-app which is easy to install and has commands for developing as well as packing your app for deployment.
It uses webpack internally (along with some other tools) but saves you the hassle of configuring it yourself. If at any time you need advanced configurations beyond what create-react-app provides, it has an 'eject' command that exposes the raw configuration files.
Getting started is simple (taken from their readme):
npm install -g create-react-app

create-react-app my-app
cd my-app/
npm start


text:
Q: How to enable "persistent mode" in Windows failover cluster manager 2012? In Windows Server 2008 R2 there was a checkbox named "Enable persistent mode" on a General tab in the Properties of a cluster resource.
In Windows Server 2012 that seems to have disappeared.
My cluster resource is a "generic script" resource (not that it makes any difference).
How do I enable "persistent mode" for a cluster resource in Windows Server 2012?

A: Here has some PowerShell commands to do this, have you seen/tried these at all?

http://blog.crayon.no/blogs/janegil/archive/2011/06/03/enable_2D00_persistent_2D00_mode_2D00_for_2D00_cluster_2D00_resource_2D00_groups_2D00_using_2D00_the_2D00_powershell_2D00_failover_2D00_clustering_2D00_module.aspx

A: After further investigation it seems to me that 2012 either defaults to or is hard-coded to "persistent mode" and they've disabled changing the value with the GUI.


text:
Q: Original Series Trek episode where the crew go to a planet where whatever they think comes true Does anyone know the name of the episode from the original Star Trek series where they are on a planet and whatever they think becomes true?
I remember Bones McCoy was thinking about a beautiful "damsel" and she appears from behind a rock, and then a knight in armor lances him through the chest and he

dies but is taken to a place under the planet surface where they make these things appear on the surface (and therefore can revive Dr. McCoy)?

A: This is almost certainly TOS: Shore Leave

Kirk:... things of fantasy, which are undeniably real, begin to appear...

You can see the knight and the damsel just before the end of the trailer.


text:
Q: How to put an if else statement in a loop This is my code. So far this works but I need it to be in a loop, so I don't keep repeating the if else statement.
static void Main(string[] args)
        {
            int i, j, k, l, m, n;
            int result;
            string [] array = { "abcw", "baz", "foo", "bar", "xtfn", "abcdef" };
            i = array[0].Length;
            j = array[1].Length;
            k = array[2].Length;
            l = array[3].Length;
            m = array[4].Length;
            n = array[5].Length;
            result = i * j;
            if (result == 16)
            {
                Console.WriteLine(result);
            }
            else
            {
                result = i * k;
            }
            if (result == 16)
            {
                Console.WriteLine(result);
            }
            else
            {
                result = i * l;
            }
            if (result == 16)
            {
                Console.WriteLine(result);
            }
            else
            {
                result = i * m;
            }
            if (result == 16)
            {
                Console.WriteLine(array[0]+" * "+array[4]+" = "+result);
            }
            else
            {
                result = i * n;
            }

A: If you create an outer loop that loops over all the entries and then an inner loop that loops over the entries after the one you're looking at in the outer loop, you can do something like this
      string[] array = {"abcw", "baz", "foo", "bar", "xtfn", "abcdef"};
      for (var i = 0; i < array.Length; i++)
      {
          for (var j = i + 1; j < array.Length; j++)
          {
              if (array[i].Length * array[j].Length == 16)
              {
                  Console.WriteLine($"{array[i]} {array[j]}");
              }
          }
      }

You then get the result which is abcw xtfn

A: One of the possible way to short your code.
You can iterate your array and compare first item with rest of the items as you mentioned in your question code-block. No need to access individual array elements.
Compare 1st element with rest
static void Main(string[] args)
{
    int result;
    string[] array = { "abcw", "baz", "foo", "bar", "xtfn", "abcdef" };

    for (int i = 0; i < array.Length - 2; i++)
    {
        result = array[0].Length * array[i + 1].Length;

        if (result == 16)
        {
            Console.WriteLine(array[0] + " * " + array[i+1] + " = " + result);
            break;
        }
    }

    Console.ReadLine();
}

Compare all element in between
for (var i = 0; i < array.Length; i++)
    for (var j = i + 1; j < array.Length; j++)
        if (array[i].Length * array[j].Length == 16)
            Console.WriteLine(array[i] + " * " + array[j] + " = " + array[i].Length * array[j].Length);

A: string[] array = { "abcw", "baz", "foo", "bar", "xtfn", "abcdef" };
        int result = 16;
        for (var i = 0; i < array.Length; i++) {
            int x = array[i].Length;
            if (result % x != 0) {
                continue;
            }
            for (var j = i + 1; j < array.Length; j++) {
                if (x * array[j].Length == result) {
                    Console.WriteLine(array[i] + "*" + array[j] + "= " + result);
                }
            }
        }


text:
Q: c# Неадекватно запускается файл Столкнулся со странной проблемой...
Ситуация в следующем: Есть папка с игрой, в ней 2 папки (Папка1 и Папка2) и приложение Updater.exe. В папке 2 лежит лаунчер (прога с графической оболочкой и кнопкой запуска игры), перемещать лаунчер нельзя, ибо если лаунчер запустить из другой папки, то игра не запустится и будет орать на конфиги.
Суть такова - лаунчер проверяет обновление , и если оно есть, то запускает Updater.exe из папки выше, который скачивает обновление  вместо того, чтобы распаковать его "в себя" (в место где он находится) , он распаковывает файлы в папку 2 (с лаунчером), ибо процесс лаунчера вызвал апдейтер (Хотя, если запускать просто сам файл апдейтера, он обновляет все правильно, НО, потом, когда запускает лаунчер - При нажатии кнопки играть игра ругается на недостающие конфиги.. )
Почему процессы себя так ведут и как это можно исправить?
Метод проверки обновления и запуска апдейтера в лаунчере
void CheckUpdate()
    {
        string updVers = GetSettingValue("update_version");
        string curVers = _xmlhelper.GetSettingValue("update_version");
        if (updVers != curVers){
          Process.Start(AppDomain.CurrentDomain.BaseDirectory + @"..\Updater.exe");
            Application.Current.Shutdown();

        }

    }

Метод обновления в апдейтере и запуска лаунчера после
void Load()
    {
        downloader.LocalDirectory = workPath;
        downloader.Files.Clear();

        string getUpd = _web.DownloadString(_xmlhelper.GetSettingValue("update_url"));
        string updVers = GetSettingValue("update_version");
        string curVers = _xmlhelper.GetSettingValue("update_version");
        if (updVers != curVers)
        {
            downloader.Files.Add(new WowSuiteUpdater.FileInfo(_xmlhelper.GetSettingValue("url") + _xmlhelper.GetSettingValue("file_zip")));
            downloader.Start();
        }
        else {
            pBarTotalProgress.Visibility = Visibility.Hidden;
            Process.Start(AppDomain.CurrentDomain.BaseDirectory + "tes3mp\\Launcher.exe");
            Application.Current.Shutdown();
        }

    }

A: ProcessStartInfo startInfo =
  new ProcessStartInfo(AppDomain.CurrentDomain.BaseDirectory + "tes3mp\\Launcher.exe");
startInfo.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory + "tes3mp";
Process.Start(startInfo);

Если для программы важно, какая папка текущая при запуске, то Вам надо взять за правило запускать Ваши программы с явным указанием рабочей директории. Или писать код так, чтобы он читал конфигурационные файлы, не полагаясь на текущую директорию, а вычисляя путь к этим файлам из полного пути к EXE-файлу.


text:
Q: How to hide WebView's "Open in new window" button? So I simply show a PDF inside a WebView, using a Google Drive link but I would like to disable the "Open in new window" button.
Is there such option at all or I have to live with it?
If yes, how?
I've only found functions like:
setBuiltInZoomControls(boolean b)

But I would like to remove the button on the upper right corner.
Maybe can I disable it with JS?
Here is a screenshot about what am talking about:

Thanks in advance.


text:
Q: How to view the trace_id of the default trace files? Sql server automatically creates the default trace into multiple files. These can be seen in the LOGS directory of sql server installation path.
The sys.fn_trace_getinfo has a trace_id parameter which I'm not sure where I can find.
How to view the trace_id of the default trace files?

A: You can find the Trace ID in the DMV sys.traces.
According to the documentation, other valid inputs are NULL, 0 or DEFAULT.

Valid inputs are the ID number of a trace, NULL, 0, or DEFAULT. NULL,
0, and DEFAULT are equivalent values in this context. Specify NULL, 0,
or DEFAULT to return information for all traces in the instance of SQL
Server.

But the documentation also has a warning that sys.fn_trace_getinfo should no longer be used, and to use Extended events instead.


text:
Q: Distribution of Active X Control .CAB file I am having difficulties trying to distribute an Active X control that I have created, the Active X control works fine if the component is registered manually (which is not good as it needs to be distributed to the user through IE). however when clicking the install button on the IE prompt, it simply doesn't install displaying no sign of any errors. My internet options are set to allow Active X controls to be installed.
The Active X control itself is a .Net dll which needs to be registered in the Component Services of the clients machine. I have followed the following walk through which seems to describe the same scenario that I face but it just doesn't seem to work.
I have even created the .exe to register the component that is describe in the example, set up the .inf file correctly but it just still refuses to install with no sign on any errors
Does anyone know is there is a log output for Active X installation that my help, or has anyone found a solution to a similar problem? I am using IE 8, 9, 10 compatibility mode
Example that I followed:-
http://www.mrrives.com/Technology/?p=767   I have also looked at MSDN website that surround this area


text:
Q: Using kknn regression on a time series I'm trying to perform a knn regression on a sales time series using the kknn package. I can't see how you can restrict the neighbours to past sales only though.
e.g.
Product, Price, Sale Date
A,       £100,  2012-01-04
A,       £100,  2012-01-05
A,       £200,  2012-01-06

If I want to predict for the second row, it should only consider the first row as a neighbour -- not the third.
Is there a way to do this or am I going to have to write something custom?
If it's going to have to be custom, what's the most efficient way of doing this in R? My dataset is 200,000 rows so I imagine it could be slow going using a loop.
Any help you can offer is appreciated. Thanks

A: Ended up implementing a custom function using sqldf to combine the train and test datasets, then ddply to get the means


text:
Q: Using capybara-webkit with HTTPS in rails Does anyone know if it is possible to use capybara-webkit using HTTPS with ruby on rails.
My app runs with HTTPS forced in production. To keep test as similar to production, I also want it to use HTTPS.
I have got rspec request specs using HTTPS with https!
However I cannot get rspec features working using capybara-webkit. I have tried a few options similar to the following:
Capybara.default_driver = :webkit
Capybara.server_port = 37_511
Capybara.default_host = 'https://localhost'
Capybara.app_host = "#{Capybara.default_host}:#{Capybara.server_port}"

Capybara::Webkit.configure do |config|
  config.raise_javascript_errors = true
  config.ignore_ssl_errors

Error:
Capybara::Webkit::InvalidResponseError:
   Unable to load URL: https://localhost:37511/home because of error loading https://localhost:37511/home: Unknown error

My versions are:
ruby 2.3.4
rails 5.0.4
capybara-webkit 1.14.0
capybara 2.13.0
rspec 3.6.0


text:
Q: Custom Binding for Foundations Tooltip in Knockout I am trying to figure out a way of adding a custom binder for foundation's tooltip in knockout like it is done for bootstrap in this example.
Custom KnockoutJS bindingHandler for dynamic Bootstrap Tooltips
Does anyone know how to do that?

A: You implement an update function, an init function, or both depending on the behaviour you require.
A complete walkthrough with a worked example is provided on (surprise, surprise) http://knockoutjs.com/documentation/custom-bindings.html
You got the downvotes (not from me) because you didn't make the slightest attempt to find this for yourself.


text:
Q: Can I apply a variable to text-based xPath searches on Selenium WebDriver? Currently I know you can search for web elements on xpath with this syntax:
driver.findElement(By.xpath("//*[text()='text to be found']"));

Is there anyway I can search for elements from a variable String? I would like to be able to make a method like this:
public boolean nameExists( String name ) {
     if (driver.findElement(By.xpath("//*[text()= name ]")) )
        return true;
     else
        return false;
}

A: You could do something like this:
public boolean nameExists(String name) {
     return driver.findElements(By.xpath("//*[text()='" + name + "']")).size() != 0;
}

Remember that findElement returns a WebElement not a boolean. Also, if the given element does not exist, Selenium will throw a NoSuchElementException.
Instead, we can utilize findElements to find all the WebElements with the given String name from your XPath. If the returned List<WebElement> contains any values (.size() != 0), this means at least one WebElement with the given name exists.