text:
Q: Cannot deploy Dynamic Web Module to Glassfish server I've been having trouble for the last few hours trying to deploy a Dynamic Web Module project to 2 different Glassfish 4 servers, one installed locally and one hosted online.
The project was working great (pom.xml & web.xml both taken from previous projects - no problems on these) even with webpages added, until I added EJB annotations for a DAO in only ONE class. Here is the class in question :
import java.util.ArrayList;
import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import be.helha.groupeA3.entities.Nouvelle;

@Stateless
@LocalBean
public class DAONouvelle {

    @PersistenceContext(unitName="groupeA3JTA")
    private EntityManager em;

    public DAONouvelle() {}

    public List<Nouvelle> getAllNouvelles() {
        Query q = em.createQuery("SELECT n FROM Nouvelle n");
        return new ArrayList<Nouvelle>(q.getResultList());
    }

    public Nouvelle getNouvelle(Nouvelle n) {
        Query q = em.createQuery("SELECT n FROM Nouvelle n WHERE id=:id");
        q.setParameter("id", n.getId());
        return (Nouvelle) q.getSingleResult();
    }

    public Nouvelle createNouvelle(Nouvelle n) {
        em.persist(n);
        return n;
    }

    public int deleteNouvelle(Nouvelle n) {
        Query q = em.createQuery("DELETE FROM Nouvelle n WHERE n.id=:id");
        q.setParameter("id", n.getId());
        return q.executeUpdate();
    }

    public int updateNouvelle(Nouvelle n1, Nouvelle n2) {
        Query q = em.createQuery("UPDATE Nouvelle n SET n.titre=:titre,n.description=:description,n.image=:image WHERE n.id=:id");
        q.setParameter("id", n1.getId());
        q.setParameter("titre", n2.getTitre());
        q.setParameter("description", n2.getDescription());
        q.setParameter("image", n2.getImage());
        return q.executeUpdate();

    }
}

I know the update and delete statements may be wrong but that's not the point.
When deploying this project to Glassfish 4, it complains about not being able to deploy the project:
2018-01-17T09:45:29.685+0100|Grave: Exception while preparing the app
2018-01-17T09:45:29.685+0100|Grave: Exception during lifecycle processing
java.lang.RuntimeException: Unable to load the EJB module. DeploymentContext does not contain any EJB. Check the archive to ensure correct packaging for C:\payara41\glassfish\domains\domain1\eclipseApps\groupeA3.
If you use EJB component annotations to define the EJB, and an ejb or web deployment descriptor is also used, please make sure that the deployment descriptor references a Java EE 5 or higher version schema, and that the metadata-complete attribute is not set to true, so the component annotations can be processed as expected
    at org.glassfish.ejb.startup.EjbDeployer.prepare(EjbDeployer.java:189)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.prepareModule(ApplicationLifecycle.java:926)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:435)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:220)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:488)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:544)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:540)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:539)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:570)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:562)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:561)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1469)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:111)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1851)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1727)
    at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
    at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
    at org.glassfish.grizzly.http.server.StaticHttpHandlerBase.service(StaticHttpHandlerBase.java:189)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:480)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:180)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:539)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:593)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:573)
    at java.lang.Thread.run(Thread.java:745)

I've googled the stacktrace with no luck, checked my web.xml versions (3.1, worked on another project). Here is the web.xml fyi :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">
    <display-name>groupeA3</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.xhtml</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>
</web-app>

The persistence.xml is present in the META-INF folder as well, worked on another project (using JTA).
Now, by running a maven clean compile package, it works just fine and I can deploy it correctly to the remote glassfish 4 server, so something must be out of sync between Eclipse and Maven.
It's really hard to debug in these conditions, could you guide me on how to resolve this issue ?
Thanks !

A: As far is I know eclipse has its own java compiler which is different to the standard java compiler which Maven uses when you execute Maven on the commandline.
So I would suggest to check your project setting and compare it to your command line java environment.
You can type mvn -v to get the java home and version information used by Maven which looks this:
Apache Maven 3.5.0
Maven home: c:\Dev\apache-maven-3.5.0\bin\..
Java version: 1.8.0_141, vendor: Oracle Corporation
Java home: c:\Program Files\Java\jdk1.8.0_141\jre
Default locale: de_CH, platform encoding: Cp1252

In Eclipse you can compare this information your project settings.


text:
Q: restsharp and Postman I am attempting to get an OAuth2 access token from ZOHO using RestSharp code. The Postman simulation works correctly so I know there is something I'm missing in my code.
I always get an "invalid client id" result status.  However in Postman, it works and returns a code when I click the "Get new access token".  I have the same items as in the Postman authorization tab (client_id, client_secret, etc).  In Postman, "Body" is set to "none", and there are no parameters or headers.  The only difference between my code and postman, is that Postman requires the Callback URL.   My code is trying to get the code using "self-client", which bypasses the callback URL.
I have tried several different alternatives to the request call including ParameterType.Body, and ParameterType.GetOrPost.   Is GetOrPost the same as a form?
client = New RestClient(ZOHO_API_URL)
request = New RestRequest(TokenUrl, Method.POST)
request.AddHeader("content-type", "application/x-www-form-urlencoded") ' also tried: "application/json")
request.AddParameter("grant_type", "authorization_code",
    ParameterType.GetOrPost)
request.AddParameter("client_id", Client_ID, ParameterType.GetOrPost)
request.AddParameter("client_secret", Client_Secret,
    ParameterType.GetOrPost)
request.AddParameter("code", Grant_Token, ParameterType.GetOrPost)
response = client.Execute(request)

This is the translated Postman code for RestSharp:
var client = new RestClient("http://");
var request = new RestRequest(Method.POST);
request.AddHeader("Postman-Token", "xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx");
request.AddHeader("cache-control", "no-cache");
IRestResponse response = client.Execute(request);

Any ideas on what I am doing wrong.  I have tried to view the raw data coming across with Fiddler, but when I do that, Postman indicates a failure.
What code do I need to use to duplicate what Postman is doing?
How do I implement a callback URL if that is also required?

A: I quickly checked ZoHo REST API docs and it seems like you should use the Limited Input Device authentication flow.
From what I can understand from their help page, you indeed need to do a POST request, but parameters must be specified as query parameters:
https://accounts.zoho.com/oauth/v3/device/code?
client_id=1000.GMB0YULZHJK411248S8I5GZ4CHUEX0&
scope=AaaServer.profile.READ&
grant_type=device_request

You will also get better off with JSON set as a default for serialisation and content type just by using client.UseJson().

A: It maybe that Postman is following a redirect from your API endpoint as the functionality is different Postman verses RestSharp (possibly missing a trailing slash or similar).
Try adding
client.FollowRedirects = false;

to your RestSharp code and analyse the result.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to dynamically resize QGraphicsView in PyQt6 Python I am working at application that shows plots in QGgraphicsView window and i need to dynamically resize the plot when user resizing the window. I show matplotlib plot in code below. So how to make resizing func?
fig, ax = plt.subplots()
ax.plot(x, y, 'o')
canvas = FigureCanvas(fig)
proxy_widget = QtWidgets.QGraphicsProxyWidget()
proxy_widget.setWidget(canvas)
scene.addItem(proxy_widget)
fig.tight_layout()
self.View.show()


text:
Q: Swift 4 - \n not working. How can I make this to another line. var welcomeText: UITextField = {
    let textField = UITextField()
    textField.layer.cornerRadius = 25
    textField.text = "Hello, are you \n Im doing good! "
    textField.textColor = .white
    return textField
}()

I can't figure this out. Any help would be appreciated!

A: UITextField can only display a single line. If you want multiple lines of editable text, you must use UITextView instead.


text:
Q: Web API 2 does not set Thread.CurrentPrincipal in certain scenarios While trying to debug why custom authentication filter does not work in our in-memory integration tests, I found that there is a difference in the way different subclasses of HttpRequestContext set Principal.
Most of them ( OwinHttpRequestContext, SelfHostHttpRequestContext, WebHostHttpRequestContext) set Thread.Principal like this
WebHostHttpRequestContext.cs:
public override IPrincipal Principal
        {
            get
            {
                return _contextBase.User;
            }
            set
            {
                _contextBase.User = value;
                Thread.CurrentPrincipal = value;
            }
        }

But some do not set it at all (BatchHttpRequestContext and RequestBackedHttpRequestContext).
Is this a design decision and I need to rewrite parts of application to not use Thread.Principal) or is it a bug that needs to be/will be fixed?


text:
Q: Momentum conservation in phonon-photon scattering event I am following a discussion from Kittel´s Introduction to Solid State Physics in the subchapter 'phonon momentum':
We have two different conservation laws of momentum in a crystal:

*

*Total momentum is conserved (if we include all processes i.e. also the center of mass motion).

*Crystal momentum (pseudo momentum) is conserved up until a reciprocal lattice vector $K_{AB}=K_A+K_B+G$, with $K$ the crystal momentum and $G$ a reciprocal lattice vector.

If a photon hits a crystal and gets reflected, the momentum change of the photon is according to bragg's law (or Laue equation):
$$k'=k +G$$
where $k$ is the initial momentum and $k'$ is the outgoing momentum of the photon. $G$ is a reciprocal lattice vector. This means that the photon gives some momentum to the crystal, whose center of mass starts to move (since a momentum $\hbar G$ is transferred).
In the case that a phonon (lattice vibration) gets produced or absorbed in this scattering process, the conservation of momentum looks the following:
$$ k'=k+G+K$$
where K is the crystal momentum of the phonon.
My question is:
We said crystal momentum $K$ is not conserved. By above equation, then also $k'$ (the real momentum of the photon) is not conserved. How can this be?
As an example:
Let's say we have two photons interacting with the crystal producing two phonons A and B.
$$ k^'_A=k_A+G+K_A$$
$$ k_B^'=k_A+G+K_B$$
Now let's say both phonons meet at a later point in time and a scattering event happens. Since crystal momentum is not a conserved quantity, the conservation of crystal momentum looks like:
$$K_{AB}=K_A+K_B+G$$
so for example, if $K_A$ and $K_B$ would be large enough, this would be an umklapp process and the total crystal momentum $K_{AB}$ would be smaller then $K_A+K_B$. So where is the real momentum of the initial photon going? It cannot (again) change the center of mass motion, because phonon-phonon interactions are not external 'forces', which are the only ones that can change the center of mass motion.
Comment: I think the problem is that some of the real momentum of the photon is converted into crystal momentum of the phonon. But why is this even possible if it does not conserve total momentum?

A: Crystal momentum is a quantum number, characterizing states in a specific crystal band (whether we speak of electrons/holes or phonons). That is $k$ and $k+G$ describe the same quantum state/excitation. While the analogy between crystal momentum and real momentum is useful and not completely unfounded, we have to keep in mind that the photon actually interacts with the whole crystal - the difference between the change in the crystal momentum and the momentum of the photon is the momentum transferred to the lattice as a whole, which is not accounted in the Block waves solutions.
Another way to think of its is that Bloch waves (and phonon modes) are excitations in the frame of reference where the crystal is at rest. Crystal speed as a whole changes when it is hit by a photon, but this does not change the energy spectrum of the internal excitations of the crystal.


text:
Q: LINQ Order By Query for XML Hi I have the following problem:
I am trying to do the following on an XML file: sort all STRUCTs according to the ID attribute of STRING. But return a list of CONTENT objects. The XML can contain  more than one  element.
<OBJECT>
  <CONTENT>
     <STRUCT>
        <STRING ID="2">string</STRING>
     </STRUCT>
     <STRUCT>
        <STRING ID="1">string1</STRING>
     </STRUCT>
   </CONTENT>
</OBJECT>
<OBJECT>
  <CONTENT>
     <STRUCT>
        <STRING ID="345">string</STRING>
     </STRUCT>
     <STRUCT>
        <STRING ID="333">string</STRING>
     </STRUCT>
   </CONTENT>
</OBJECT>

I am using the following LINQ query, but the strings are not being sorted:
Dim Contents = From nm In origXML.Descendants("CONTENT")
    Let ID = nm.Element("STRUCT").Element("STRING").Attribute("ID")
    Order By ID Ascending
    Select nm

For Each xmlString In Contents....

Desired output
<OBJECT>
  <CONTENT>
     <STRUCT>
        <STRING ID="1">string</STRING>
     </STRUCT>
     <STRUCT>
        <STRING ID="2">string1</STRING>
     </STRUCT>
   </CONTENT>
</OBJECT>
<OBJECT>
  <CONTENT>
     <STRUCT>
        <STRING ID="333">string</STRING>
     </STRUCT>
     <STRUCT>
        <STRING ID="345">string</STRING>
     </STRUCT>
   </CONTENT>
</OBJECT>

I know there must be other ways to do this, but I want to know if it's possible using LINQ?
Thanks
Rob

A: I don't think that a single linq query can give you the desired output. In order to properly create a new xml document, which has the same structure as the original one, you need multiple nested linq queries applied to the original xml document.
Assuming that the root node of your XML is <OBJECTS>, the following piece of code should give you the desired output:
Dim xElement As XElement = New XElement("OBJECTS",
                              From obj In origXML.Descendants("OBJECT")
                              Select New XElement("OBJECT",
                                 From content In obj.Descendants("CONTENT")
                                 Select New XElement("CONTENT",
                                    From st In content.Descendants("STRUCT")
                                    Let ID = Convert.ToInt32(st.Element("STRING")
                                                    .Attribute("ID").Value)
                                    Order By ID Ascending
                                    Select New XElement("STRUCT",
                                       New XElement("STRING", st.Element("STRING").Value,
                                          New XAttribute("ID", ID)))
                                    )
                                )
                            )

A: If your <OBJECT><CONTENT> hierarchy is static (no attributes, etc., that need to be copied to the output), then you could do this in one LINQ query, using VB.NET's nifty support for XML literals with embedded queries.
Dim origXML =
<OBJECTS>
    <OBJECT>
        <CONTENT>
            <STRUCT>
                <STRING ID="2">string2</STRING>
            </STRUCT>
            <STRUCT>
                <STRING ID="1">string1</STRING>
            </STRUCT>
        </CONTENT>
    </OBJECT>
    <OBJECT>
        <CONTENT>
            <STRUCT>
                <STRING ID="345">string345</STRING>
            </STRUCT>
            <STRUCT>
                <STRING ID="333">string333</STRING>
            </STRUCT>
        </CONTENT>
    </OBJECT>
</OBJECTS>
Dim out = New XDocument(New XElement("OBJECTS",
    From c In origXML...<CONTENT>
    Select _
    <OBJECT>
        <CONTENT>
            <%= From s In c.<STRUCT> Order By CInt(s.<STRING>.@ID) Select s %>
        </CONTENT>
    </OBJECT>
))

The out variable will be an XDocument with the following content:
<OBJECTS>
    <OBJECT>
        <CONTENT>
            <STRUCT>
                <STRING ID="1">string1</STRING>
            </STRUCT>
            <STRUCT>
                <STRING ID="2">string2</STRING>
            </STRUCT>
        </CONTENT>
    </OBJECT>
    <OBJECT>
        <CONTENT>
            <STRUCT>
                <STRING ID="333">string333</STRING>
            </STRUCT>
            <STRUCT>
                <STRING ID="345">string345</STRING>
            </STRUCT>
        </CONTENT>
    </OBJECT>
</OBJECTS>

As noted, this is recreating the <OBJECT> and <CONTENT> elements, so any attributes on those elements would be lost.


text:
Q: Is a closed subset of isolated points in a compact set necessarily finite? If I have a compact set $A$ and a closed subset $\Sigma \subset A$ which only contains isolated points (that is, none of them is a limit point). Does the compactness of $A$ then force $\Sigma$ to have finite cardinality ?
Here is my attempt at a proof that the above question can be answered in the positive:
Suppose for contradiction that $\Sigma$ contains infinitely many distinct points.
EDIT :
Then we can construct a sequence of points in $\Sigma$ which consists of distinct points.
By compactness of A, this sequence must have a convergent subsequence, and by the fact that $\Sigma$ is closed, this limit lies in $\Sigma$. But then it cannot be a limit point, because all points in $\Sigma$ are isolated. So the subsequence must eventually constant and equal to the limit, contrary to the construction of the sequence.
Is the reasoning above correct ? If no, what did go wrong ?

A: What you did is not quite correct even assuming that you're working in a first countable space, so that compactness is equivalent to sequential compactness. Assuming that $\Sigma$ is infinite to get a contradiction is fine (if unnecessary), but that doesn't make $\Sigma$ a sequence: it has no ordering, and it might even be uncountable. However, if $\Sigma$ is infinite there must be a sequence $\langle x_n:n\in\Bbb N\rangle$ of distinct points of $\Sigma$. Then this sequence must have a convergent subsequence, and your argument goes through from there. It's a small point, but it's a good idea to get into the habit of precision in order to avoid confusing yourself when things get more complicated.

A: What you did seems correct if you can show that you can indeed extract a converging subsequence. In fact, you don't need to do it by contradiction: for each $x\in \Sigma$, pick $U_x$ an open neighborhood which doesn't meet any point of $\Sigma$ except $x$. Then $\{U_x\}_{x\in\Sigma}$ is an open cover of $\Sigma$, which is compact as a closed set of a compact, so you can extract a finite sub-cover.

A: Compactness does not mean that sequences have convergent subsequences in a general topological space. See sequential compactness at Wikipedia.
However, your statement is still true. Just stick more closely to the definition of compactness.


text:
Q: GitLab: Job do not return after script is executed, instead fail by timeout after 1 hour In my .gitlab-ci.yml i have the following job:
init_db:
  stage: build
  script:
    - cd database-migration
    - "mvn clean install exec:java"

The database-migration gets executed. The code for it looks like this:
public static void main( String[] args ) {
    doSomeMigration();
    System.out.println("Migration done!");
    System.exit(0);
}

In the log from GitLab I get this at the end:
Migration done!
ERROR: Job failed: execution took longer than 1h0m0s seconds

So to me it seems like the script ran ok, but after that the job does not end. Can you see what I am doing wrong?
Edit
The pom.xml for database-migration looks like this:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.domain</groupId>
  <artifactId>database-migration</artifactId>
  <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <plugin>
              <groupId>org.codehaus.mojo</groupId>
              <artifactId>exec-maven-plugin</artifactId>
              <version>1.4.0</version>
              <configuration>
                <executable>java</executable>
                <mainClass>com.domain.DatabaseMigrationApp</mainClass>
              </configuration>
            </plugin>

        </plugins>
    </build>
    <packaging>jar</packaging>

  <dependencies>

    <dependency>
       ... database dependency...
    </dependency>

  </dependencies>
</project>

A: Try adding --batch-mode to your mvn CLI options

A: Even if your task is successfull, it has timed out, so you have to increase your timeout limit.
See the following existing Stackoverflow question
GitLab CI Pipeline Stage Timeout

A: if you use service docker:dind, let's try docker:19.03.5-dind. please find details here.


text: Q: How to feed a long text(to keep the memory from previous sentences) as input for huggingface's transformers model on translation task? I'm trying to translate a long sentence from English to Spanish using Huggingface's transformers model on translation task. And often the models have a max limit of input text length. However, I'd like the model to see as many previous sentences as possible so that it wisely picks the translation words. How could I do that using the transformers model?


text:
Q: Recover files from one of three mdadm RAID5 disks I have lost 2 of 3 mdadm RAID5 disks.
How can i recover whatever files are available on the remaining one disk?
Sundeep

A: RAID 5 distributed data over stripes. In your case, each stripe consists of two data segments and a redundancy segment calculated from both data segments. The distribution of the segments is rotated over the disks from stripe to stripe to provide an even workload for each disk.
With only a single drive left, you've got one third of these segments. These alternate as

*

*data segment from the beginning of one stripe

*data segment from the end of another stripe

*rendundancy segment for a third stripe

The redundancy segment is useless - you don't have any of the data segments you'd need to reconstruct the other data segment.
Only very small files could be reconstructed from these segments - those that fit into a single segment. However, the file system structure is lost, so it's (practically) impossible to tell which segment belonged to a certain file other than guessing from its contents.
Essentially, take a disk editor and see what you can find. There's nothing more anyone can do.
RAID doesn't replace backups.

A: RAID5 provides protection from single disk loss.
The only suggestion I can give you, apart to restore from backup, is to run testdisk/photorec against the single disk do you have. For files which are smaller than RAID chunk size, you have a small possibility to recover something.


text:
Q: When click print from 1 to 10, on the second click print from 10 to 20 etc I'm trying to make a button where the user can click and that what will happen:
var score = 0;
document.getElementById('button').addEventListener('click', addScore);
function addScore() {
    score += 5;
}

And now it's the step that I don't know how to make:
When the user click the button the function addScore should work, after this function worked, there is something need to be printed on the screen:
and it must be for the first click:
1
2
3
4
5

on the secound click the printed text must be
6
7
8
9
10
etc

A: You can add a loop and, with a bit of math, calculate the range of numbers that you need to add with each click.

var clicked = 0;

const div = document.querySelector('div');
document.querySelector('button').addEventListener('click', addScore);

function addScore() {

  // Get the new range
  // e.g initially this will be 1 (5 * 0) + 1
  const range = (5 * clicked) + 1;

  // Set up a new array to which we will add the numbers
  let arr = [];

  // Loop from range to range + 5 and push each
  // number into the array
  for (let i = range; i < range + 5; i++) {
    arr.push(i);
  }

  // Join the array with a `<br/>` element and add it to before the
  // end of your output div
  div.insertAdjacentHTML('beforeend', `${arr.join('<br/>')}<br/>`);

  // Increase the click value
  ++clicked;
}
<button>Click</button>

A: Use the following code:
var score = 0;
document.getElementById('button').addEventListener('click', addScore);
function addScore() {
    var html = '';
    for (var i=0; i<5; i++) {
        html+=(score+1)+'
';
        score++;
    }
    document.getElementById('#idofcontentdiv').innerHTML = html;
}

This increments score upto next 5 iterations and keeps its value into a variable 'html', then use the variable to put into a dom element content.

A: Edit: i got working example here is fiddle: https://jsfiddle.net/apd0z7ho/
html
var score = 0;
<button id="button">click me</button>

javascript
var score = 0;
document.getElementById('button').addEventListener('click', addScore);
function addScore() {
    score += 5;
    for(var i = score-5; i < score; i++){
  document.getElementById("results").innerHTML += i+1+"
";
     }
}

A: Add following inside addScore() method :
function addScore(){
  for(var i = 0; i < 5; i++)
    console.log(++score)
}

Variable score should be initialized to 0
Since you have not specified where exactly to print, I am assuming it is console.


text:
Q: Laptop goes into hibernate when it is suspended (only happens on Wednesdays) Every night I put my laptop into suspend mode and disconnect it from power and network.  It seems that each Wednesday (it may not be every Wednesday but it is always on a  Wednesday) morning I find that I have to wake my laptop up from a hibernate.  I've looked in my Windows event logs and I see that there is some activity around 7AM (give or take a couple minutes).  Note that this is about two hours prior to my turning the laptop on.  I see an event from the Power-Troubleshooter source indicating that the that the wake source was a timer but it doesn't tell me which timer.  So I then look at the Task Scheduler and it says that no tasks have run in the past 24 hours.  I then try the command powercfg -lastwake but this is the output:
Wake History Count - 1
Wake History [0]
  Wake Source Count - 0

Does anyone have any ideas what could be causing this seemingly scheduled task to cause a wake up at this time?  This is especially annoying because when my laptop is woken up with the lid closed Windows defaults to 1024x768 (or some other low resolution) and all of my windows are resized and moved to the upper left corner of the screen.
TL;DR - Laptop wakes itself up from suspend on Wednesday mornings and then puts itself into hibernate 2 minutes later for no apparent reason.

A: OK, I think I've resolved this.  I ended up updating my video card driver and so far I'm not seeing the issue anymore (I really can't explain why the driver would somehow behave on a weird schedule like this).  I had to go to Nvidia's web site to get the driver since I was using the latest version that Dell had available.

A: What does your Reliability Monitor show for the last few months? Is anything happening, such as a new add-on to IE or SP1 update?
If you type the day/date into your Search Menu, you should get all that was changed on that/ those days. It shows in 'more search results'.
This will tell you in detail, settings, etc. It prints HTML to desktop and admin:
cd %userprofile%\Desktop
powercfg -energ

*

*Remote management unclicked in 'system props-remote'.

*Disable wake by moving mouse, etc. (cleaners may move it when they do there job-if on that day\night or other employees who get to work earlier).

*Disable 'allow wake up timers'
In Control Panel:
Power Options -> change power settings -> advanced power settings -> sleep -> disable 'allow wake up timers'.
Also in Advanced Power Settings, check 'what bat. does when low' config to below 25% so Windows will show a warning. Above 15-20%, it may try to warn you, then lock down (hibernate) to protect or save.

*Checking the BIOS as pointed out by @Col.

*Remote chances if at all:
When is defrag set to run/ or full security scan/, or is auto backup/ or check for updates (Google or system updates checks)?

A: Try disabling hibernate in the Power Options.  Perhaps whatever is causing it to hibernate will throw an error.


text:
Q: 401 Authorization Error in unofficial xbox api Hello i'm using unofficial x-box one api for sending messages over x-box live accounts.Here is my code sample and error(Problem).
Code:
<?php
     $arr = array('to' => array("gamoneybcn"), 'message' => "This is an Test Test example message sent via XboxAPI.");

     $post = json_encode($arr);

     $proServiceUrl = "https://xboxapi.com/v2/messages/";
     $contentsType = 'application/json';
     $methods = 'POST';
     $auths = 'X-AUTH: XXXX';

     $profilesCurl = curl_init();
     curl_setopt($profilesCurl, CURLOPT_URL, $proServiceUrl);
     curl_setopt($profilesCurl, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($profilesCurl, CURLOPT_POSTFIELDS, $post);
     curl_setopt($profilesCurl, CURLINFO_HEADER_OUT, true);
     curl_setopt($profilesCurl, CURLOPT_HTTPHEADER, Array('Content-type:'.$contentsType.';auth='.$auths));
     curl_setopt($profilesCurl, CURLOPT_HTTPHEADER, Array($auths));
     $profilesJson = curl_exec($profilesCurl);
     echo "<pre>";
     print_r($profilesJson);
     exit;
 ?>

Problem:
If i'm not logged in my x-box one unofficial developer account my api's not working and getting error code like below.
Error:
{"success":false,"error_code":401,"error_message":"A fresh login is required to gain a new token from Microsoft"}.
Note:
As soon as i logged in my x-box one api developer account the api will run.i have also try to first make curl authentication but i dont know is it possible after curl authentication? if is it possible by making first curl authentication so please helping me to solve out this problem as soon as possible.a big thanks in advance.

A: I just ran into the same problem and this was my first search result.
When you initially link your Xbox API account with a Microsoft account, the Xbox API only stores the account email and an oAuth token, rather than saving your password. This token is only valid for a finite period of time, so you need to login to your Microsoft account through the Xbox API website periodically to generate new oAuth tokens for it.
In order to do this, go to your profile page on the Xbox API site and click the "Sign in to Xbox LIVE" on the bottom left.
Enter your account credentials and press "Sign in to Xbox LIVE", or click "Sign in to Xbox LIVE using oAuth" and it will direct you to login on the Xbox site. Both methods should essentially do the same thing since the site says it never stores or logs your password, but if you're paranoid go with the oAuth option.


text:
Q: Is it correct to say that "we did not assume that a or b is positive." is equivalent to "we did not assume that a and b are both positive"? Given a is a real number.

We did not assume that a is positive.

For me, that sentence means either a is positive or a is not positive.
But given a and b are real numbers.
I read a sentence that "we did not assume that a or b is positive." in my textbook.
I wonder what meaning it has.
Are they

we did not assume that a or b is positive.

we did not assume that a and b are both positive

equivalent to each other?

Is it correct to say that
"we did not assume that a or b is positive."
is equivalent to
"we did not assume that a and b are both positive"?

I built a truth table that showed "tautology"
So can we say that?

A:
Are they

we did not assume that a or b is positive.

we did not assume that a and b are both positive

equivalent to each other?

No, the top one means "we did not assume that either a or b is positive" and the bottom one means "we did not assume that both a and b are positive".
"Either a or b is positive" is satisfied by $a=1, b=-1$ or $a=-1, b=1$, but not by $a=-1, b=-1$.
"Both a and b are positive" is satisfied by $a=1$ and $b=1$, but not by $a=-1, b=1$.


text:
Q: FATAL EXCEPTION MAIN - App crashes on startup When I run my app I get this error, how should I fix this error, any ideas will be appreciated.
03-11 18:15:35.795: E/AndroidRuntime(5588): FATAL EXCEPTION: main
03-11 18:15:35.795: E/AndroidRuntime(5588): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.my_autrui/com.example.my_autrui.Login}: android.view.InflateException: Binary XML file line #64: Error inflating class com.facebook.widget.LoginButton
03-11 18:15:35.795: E/AndroidRuntime(5588):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2306)
03-11 18:15:35.795: E/AndroidRuntime(5588):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2356)
03-11 18:15:35.795: E/AndroidRuntime(5588):     at android.app.ActivityThread.access$600(ActivityThread.java:150)
03-11 18:15:35.795: E/AndroidRuntime(5588):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1244)
03-11 18:15:35.795: E/AndroidRuntime(5588):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-11 18:15:35.795: E/AndroidRuntime(5588):     at android.os.Looper.loop(Looper.java:137)
03-11 18:15:35.795: E/AndroidRuntime(5588):     at android.app.ActivityThread.main(ActivityThread.java:5195)
03-11 18:15:35.795: E/AndroidRuntime(5588):     at java.lang.reflect.Method.invokeNative(Native Method)
03-11 18:15:35.795: E/AndroidRuntime(5588):     at java.lang.reflect.Method.invoke(Method.java:511)
03-11 18:15:35.795: E/AndroidRuntime(5588):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
03-11 18:15:35.795: E/AndroidRuntime(5588):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
03-11 18:15:35.795: E/AndroidRuntime(5588):     at dalvik.system.NativeStart.main(Native Method)
03-11 18:15:35.795: E/AndroidRuntime(5588): Caused by: android.view.InflateException: Binary XML file line #64: Error inflating class com.facebook.widget.LoginButton
03-11 18:15:35.795: E/AndroidRuntime(5588):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:698)
03-11 18:15:35.795: E/AndroidRuntime(5588):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
03-11 18:15:35.795: E/AndroidRuntime(5588):     at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
03-11 18:15:35.795: E/AndroidRuntime(5588):     at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
03-11 18:15:35.795: E/AndroidRuntime(5588):     at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
03-11 18:15:35.795: E/AndroidRuntime(5588):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:282)
03-11 18:15:35.795: E/AndroidRuntime(5588):     at android.app.Activity.setContentView(Activity.java:1881)
03-11 18:15:35.795: E/AndroidRuntime(5588):     at com.example.my_autrui.Login.onCreate(Login.java:26)
03-11 18:15:35.795: E/AndroidRuntime(5588):     at android.app.Activity.performCreate(Activity.java:5104)
03-11 18:15:35.795: E/AndroidRuntime(5588):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
03-11 18:15:35.795: E/AndroidRuntime(5588):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2260)
03-11 18:15:35.795: E/AndroidRuntime(5588):     ... 11 more
03-11 18:15:35.795: E/AndroidRuntime(5588): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.facebook.widget.LoginButton" on path: /data/app/com.example.my_autrui-1.apk
03-11 18:15:35.795: E/AndroidRuntime(5588):     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:65)
03-11 18:15:35.795: E/AndroidRuntime(5588):     at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
03-11 18:15:35.795: E/AndroidRuntime(5588):     at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
03-11 18:15:35.795: E/AndroidRuntime(5588):     at android.view.LayoutInflater.createView(LayoutInflater.java:552)
03-11 18:15:35.795: E/AndroidRuntime(5588):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)

A: From the log, it seems LoginButton class is not available which is supposed to be under package com.facebook.widget:

Caused by: java.lang.ClassNotFoundException: Didn't find class
  "com.facebook.widget.LoginButton" on path:
  /data/app/com.example.my_autrui-1.apk

Are you using a third party library?  You need to add that as a dependency and make sure that while exporting the library is packaged as well.
For adding dependency on a third party, right click on the project and select Properties -> Java Build Path -> Libraries Tab.
To check if the libraries are getting exported, in the same window check Order and Export tab.  Make sure the Android Private Libraries are added and selected to be exported.

A: The problem is the package name of the button.
Check the comments here:
Error inflating class com.facebook.widget.LoginButton with Facebook SDK 4.0.1


text:
Q: PostgreSQL Foreign Data Wrapper (MSSQL) I'm trying to do some slow migration from a MS SQL Server 2008 R2 to a PostgreSQL 9.5 + PostGIS.
I created a FDW in PostgreSQL to access my MSSQL data and I imported most of my tables, but a few didn't make It.
Here is an exemple:
CREATE  FOREIGN TABLE ms_table_name(
col1 varchar (64), col2 date, geometry geometry
) SERVER mssql_db_server OPTIONS (query 'SELECT col1, col2, cast(geometry.STAsText() as varchar(max)) "geometry" FROM ms_table_name',
row_estimate_method 'showplan_all');

 CREATE TABLE pg_table_name AS (select * from ms_table_name);

 ALTER TABLE pg_table_name ADD oid serial PRIMARY KEY;

 CREATE INDEX pg_table_name_gix ON pg_table_name USING GIST (GEOMETRY);

I can't use binary because it returns two invalid characters, that's why I need to convert it to text.
As I said, it works for most geometries but for long/big geometries that have a large number of coordinates, it gets truncated.

ERRO: parse error - invalid geometry SQL state: XX000 Hint:
  "...65032851836 8268588.7680116147, 6129" <-- parse error at position
  64513 within geometry

This geometry has 138280 chars, I confirmed all chars are being sent from MSSQL but PosgreSQL only reads 64512. I tried varchar, text, but still I get this 64512 char limit!
How do I work around it?

A: Maybe use an FDW with explicit support for spatial? OGR FDW does what you need, and there is a windows build.
WRT the specifics of your question, the maximum value of 64512 is suspiciously close to the maximum size of a short, 65536. Perhaps you're hitting a max string length limit somewhere in the stack.


text:
Q: yii2: get records by relations id I have Images model with relation:
public function getAlbums()
{
    return $this->hasMany(ImagesTerms::className(), ['id' => 'term_id'])
                ->viaTable(ImagesTermsRelations::tableName(), ['object_id' => 'id'])
                ->andWhere(['type'=>'album']);
}

On image view page I want to show random images with the same albums. Can anyone help?
I tried with the following query, but it didn't gave me what I want:
$related = Images::find()->with([
        'albums' => function($query) {
            $query->andWhere(['in', 'id', [2]]);
        }
])->where(['status'=>'1'])->orderBy('rand()')->limit(9)->all();

This query excludes other albums, but not images. Images with other albums are shown, but without album tag.

A: I solved the problem:
$related = Images::find()->joinWith([
    'albums' => function($query) {
        $query->andWhere(['in', 'images_terms.id', [1,2,3]);
    }
])->where(['images.status'=>'1'])->orderBy('rand()')->limit(9)->all();


text:
Q: How do I use AutoHotKey to read the text at the mouse location? I can read the entire window text using WinGetText() but I am trying to get the text at the current mouse location.
I've found several examples on the AutoHotKey forums but they are all very old (from 2007-2009) and the samples no longer work and in many cases the required files are no longer available.
Is this possible? How would could it be done?

A: If you can tolerate OCR issues (i.e., garbled data sometimes or incorrect characters), there are working examples on the AHK forums using the GDIP OCR library to screen-capture a window around the mouse and then OCR it back into text for you.  Not pretty but it works for some things.


text:
Q: In QT is it safe to emit a signal from a closeEvent function? Please, consider the following code
class A : public QWidget
{
    signals:
       void readyToBeClosed();
    protected:
       void closeEvent(QCloseEvent* e)
       {
           QWidget::closeEvent(e);
           emit readyToBeClosed();
       }
}

class B: public QWidget
{
public:
   B(A* obj)
   {
       connect(obj,SIGNAL(readyToBeCLosed()),this,SLOT(cleanUp());
   }

private slots:
   void cleanUp()
   {
        //DO SOMETHING
   }
}

Is it safe? May I risk to crash cause the object obj is destroyed after the emit signal and before the cleanUp function returned?
Thanks a lot.

A: It is, because the signal/slot system works like function calls (with the addition of the "connection" mechanism), as specified in the Qt Documentation about Signals and Slots.
When you emit a signal, all slots connected to it are called, and once they've all returned, control returns to the code that emitted the signal. So, the next line of code in your closeEvent function, just after the signal, will execute after all slots connected to this signal have returned.
Thus, in your case, the A object will still be there and valid. Note that closing a widget doesn't necessarily delete it (as noted by vahancho in the comments).
EDIT: In fact, it depends if you manipulate A through a pointer in cleanup. If B doesn't store a pointer to A, it will be fine no matter what (because the signal will be emitted anyway, the slot will be called, and if A isn't accessed inside the slot, there'll be no problem at all, whatever the connection type that has been specified or assumed). If cleanup somehow accesses A through a pointer, then read the following:
As pointed out, I should indeed have precised that this is the case only if you're using  a Qt::DirectConnection mode for this connection. Indeed, this mode yields the behavior I described, and is assumed (the default parameter for the connect function is Qt::AutoConnection, which automatically choose based on the context, i.e. signal from a thread to a slot that'd run in another thread)
If you use Qt::QueuedConnection or that the Qt::AutoConnection assumes it, then you could indeed have undefined behavior because the call to the slot will be queued to the receiver thread and will only execute once control returns to this thread's event loop. If this happens after A has been actually destroyed,


text:
Q: Поиск максимальной цепочки в последовательности Имеется к примеру последовательность: [b,ab,bc,bb] из неё надо построить цепочку вида: ab -> bb -> b -> bc (как понял вариант с b->bb тоже рабочий) и для этого я применял сначала вот такой алгоритм:
def chains(words, previous_word_index=None):
   yield []
   if previous_word_index is not None:
       previous_letter = words[previous_word_index][-1]
       words = words[:previous_word_index] + words[previous_word_index + 1:]
   for i, each_word in enumerate( words ):
       if previous_word_index is None or each_word.startswith(previous_letter):
           for tail in chains(words, previous_word_index=i):
                yield [each_word] + tail
print(max(chains(words), key=len))

потом пробовал использовать алгоритм по нахождению эйлерового пути, но там лишнее выводило и я от него отказался.
Библиотечная функция networkx.dag_longest_path тоже не вариант тк в графе есть цикл (b->bb, bb->b).
Есть вариант не рекурсивного алгоритма для поиска такой максимальной последовательности?
p.s. без полного перебора.
Ссылка на задачу с её полным описанием:
atpp.vstu.edu.ru/cgi-bin/arh_problems.pl?id_prb=205

A: Можно что-то и получше придумать чем это:
import copy

class Item(object):
    def __init__(self, value, items):
        self.value = value
        self.next = self._get_next(items)

    def _get_next(self, items):
        return [item for item in items if self.value[-1] == item[0]]

def copy_dictionary(dictionary):
    return {key: copy.deepcopy(value) for key, value in dictionary.items()}

graph = {}
items = ['b', 'ab', 'bc', 'bb']

for index, item in enumerate(items):
    graph[item] = Item(item, items[:index] + items[index + 1:])

longest_path = []

for item in items:
    tmp_graph = copy_dictionary(graph)
    queue = [[tmp_graph[item]]]
    while queue:
        current_items = queue.pop(0)

        if not current_items[-1].next:
            if len(current_items) > len(longest_path):
                longest_path = current_items
            continue

        for next_item in current_items[-1].next:
            if tmp_graph[next_item].value in [current_item.value for current_item in current_items]:
                continue
            queue.append(current_items + [tmp_graph[next_item]])

print(' -> '.join([item.value for item in longest_path]))  # 'ab -> b -> bb -> bc'

UPDATE: в предыдущих примерах делал интуитивно то же самое, что и @pavel, но к своему стыду не знал про Эйлеров граф.
# матрица смежности графа (количество ребер, соединяющих вершины)
graph = [[0] * 26 for _ in range(26)]
# словарь (та же матрица смежности, только вместо количества ребер - массив слов)
dictionary = [[[] for __ in range(26)] for _ in range(26)]
# массив со степенями вершин
deg = [0] * 26
# последовательность слов
stack = []
# массив с индексами позиций слов
result = []

n = int(input())

# если задано всего одно слово, то сразу его и выводим
if n == 1:
    print(input())
else:
    for _ in range(n):
        word = input()
        # первый символ слова (исходящая вершина)
        first_char = ord(word[0]) - ord('a')
        # последний символ слова (входная вершина)
        last_char = ord(word[-1]) - ord('a')
        # увеличиваем количество ребер между этими вершинами
        graph[first_char][last_char] += 1
        # добавляем в словарь
        dictionary[first_char][last_char].append(word)
        # для исходящей вершины повышаем степень
        deg[first_char] += 1
        # для входной понижаем
        deg[last_char] -= 1

    # в результате тестового примера получится следующее:
    #   |  a  |      b      |  c     |
    # --+-----+-------------+--------|
    # a | [ ] | ['ab']      | [ ]    |
    # --+-----+-------------+--------|
    # b | [ ] | ['b', 'bb'] | ['bc'] |
    # --+-----+-------------+--------|
    # c | [ ] | [ ]         | [ ]    |
    # --+----------------------------|

    start = -1
    finish = -1

    # нужно найти подходящую вершину,
    # с которой лучше начинать составлять последовательность слов
    for index in range(26):
        if deg[index] == 0:
            continue
        # подойдет та вершина, из которой исходящих ребер больше, чем входных
        # (в тестовом примере это 'ab', а 'bc' не подойдет - нет исходящих ребер)
        elif deg[index] == 1 and start == -1:
            start = index
        elif deg[index] == -1 and finish == -1:
            finish = index
        else:
            print('NO')
            exit(0)

    # если идеально подходящих для старта вершин нет, то начинаем по порядку
    if start == -1:
        start = 0

    stack.append(start)

    # обычный алгоритм поиска путей в графе
    while stack:
        vertex = stack[-1]
        index = 0

        while index < 26:
            if graph[vertex][index] > 0:
                break
            index += 1

        if index == 26:
            result.append(vertex)
            stack.pop()
        else:
            graph[vertex][index] -= 1
            stack.append(index)

    if len(result) - 1 != n:
        print('NO')
        exit(0)

    for index in range(len(result) - 1, 0, -1):
        print(dictionary[result[index]][result[index - 1]].pop(0))

Результат: данное решение прошло успешно все тесты.

A: Прочитав внимательно и несколько раз условие, ставится понятно, что нужно искать не максимальный путь, а именно полный путь.
Если переформулировать условие. У нас есть граф, где вершины - {a..z} а ребро - слово начинающееся на первую вершину и заканчивающееся на 2. (Да мультиграф, да есть петли).
Нам нужно найти Эйлеров путь. В целом можно уже ничего не писать, а давать ссылку на википедию) Но вот код на С++ (быстро проверить идею). Основной код достаточно маленький
while (!st.empty()){
    int v = st.top();
    int i;
    for (i=0; i<26; ++i)
        if (G[v][i])
            break;
    if (i == 26){
        res.push_back (v);
        st.pop();
    }
    else {
        G[v][i]--;
        st.push (i);
    }
}

ссылка на запускаемый пример https://ideone.com/zvqa9m
Сложность не больше чем 26*N. (и то можно без 26, но это уже мелочи. успевает с диким запасом).


text:
Q: Why does JS RegEx pull multiple values (only one that matches)? Ok this is me totally trying to learn here... in my JS console, why does this happen:
"[test]".match(/\[(\w+)\]/)
=> ["[test]", "test"]

In the example above, I am just expecting "test", why are there 2 results?
The reason this is tripping me up is because I'm actually trying to work with the below (same regex, with g modifier)
"type[][random][][test]".match(/\[(\w+)\]/g)

With the above, what I would have originally expected to get back, just knowing RegEx is this:
["random", "test"]

What I would now expect to get back, given the original question above and experimentation in the console, would be something like this:
["[random]", "random", "[test]", "test"]

What I'm actually getting back is this:
["[random]", "[test]"]

Can anyone explain why what's happening above is happening?

For more context, I'm trying to get the word in the last set of brackets (i.e., "test"), by finding all words in brackets, and then pulling out the last one. But because the behavior I've found is not what I expected, I essentially have to do something pretty redundant, like this:
"type[][random][][test]".match(/\[(\w+)\]/g).slice(-1)[0].match(/\[(\w+)\]/).slice(-1)[0]
=> "test"

And that doesn't feel right to me

A: As the documentation says, it will return the following:

An Array containing the entire match result and any
  parentheses-captured matched results, or null if there were no matches

Which explains why you get this:
"[test]".match(/\[(\w+)\]/)
=> ["[test]", "test"]

As your regex was matching whatever is inside the brackets([]), it matched [test] and test was inside the parentheses.
But if you put the global flag and try again:
"[test]".match(/\[(\w+)\]/g)
=> ["[test]"]

The global flag will make it only return matches not the parentheses-captured results. To understand you can look at the following:
"[test][test2]".match(/\[(\w+)\]/)
=> ["[test]", "test"]

"[test][test2]".match(/\[(\w+)\]/g)
=> ["[test]", "[test2]"]


text:
Q: Unable to run a simple "Hello World!" project using NetBeans IDE 8.1, Glassfish 4.1 I am a beginner in Spring. Trying to run a simple "Hello World!" project using NetBeans IDE 8.1, Glassfish 4.1
Here is my code:
web.xml
<?xml version="1.0" encoding="UTF-8"?>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
    <servlet-name>tryspring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>tryspring</servlet-name>
    <url-pattern>*.jsp</url-pattern>
</servlet-mapping>
<session-config>
    <session-timeout>
        30
    </session-timeout>
</session-config>
<welcome-file-list>
    <welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>

servlet.xml
<?xml version='1.0' encoding='UTF-8' ?>

<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="mappings">
        <props>
            <prop key="index.jsp">indexController</prop>
        </props>
    </property>
</bean>

<bean id="viewResolver"
      class="org.springframework.web.servlet.view.InternalResourceViewResolver"
      p:prefix="/WEB-INF/jsp/"
      p:suffix=".jsp" />

<bean name="indexController"
      class="org.springframework.web.servlet.mvc.ParameterizableViewController"
      p:viewName="index" />

index.jsp

Hello! This is the default welcome page for a Spring Web MVC project.

To display a different welcome page for this project, modify
        <tt>index.jsp</tt> , or create your own welcome page then change
            the redirection in <tt>redirect.jsp</tt> to point to the new
            welcome page and also update the welcome-file setting in
        <tt>web.xml</tt>.

But when I am running the project no page is being displayed.
Error: "HTTP Status 404 - Not Found"

Can any one please help on this?
Also this code is generated by NetBeans IDE.
I have just modified the dispatcher modifier from *.htm to *.jsp. Is it causing the problem?

A: Your code dosen´t really matter. It´s the redirection as mentioned in the error message that is not present. Notice that redirect is only browser side, if you want to do it on server side you need to use forward.
RequestDispatcher rd = request.getRequestDispatcher("your file.js");
rd.forward(request, response);


text:
Q: Sharp image uploader not working when running app with PM2 I have an express app that I am using Sharp to resize images after a user has uploaded them.  When I start the app using 'npm start' I am able to upload the images with no issues, but if I use PM2 to manage the process the images don't get saved on the server.  I can save them without using Sharp to resize them, it is only when I have the code for sharp that they don't get saved.  Below is the code from my controller.  Multer is processing the form and sharp is resizing the image.
doNewRecipe: function(req, res) {
    for (var key in req.body) {
        req.body[key] = req.body[key] || undefined;
    }
    var body = _.pick(req.body, 'title', 'description', 'ingredients', 'instructions', 'yield', 'prep_time', 'cook_time', 'categoryId');
    body.userId = req.session.user.id;

    if (req.file) {
        var tempPath = req.file.path,
            ext = path.extname(req.file.originalname).toLowerCase(),
            //targetPath = path.resolve(finalUploadPath + req.file.filename + ext);
            targetPath = path.resolve(finalUploadPath);
        fs.renameSync(tempPath, tempPath + ext);
        var newFileName = req.file.filename + ext;
        var imageFile = tempPath + ext;

        body.image = newFileName;

        sharp(imageFile)
            .resize(450, 450)
            .max()
            .toFile('./public/finalUpload/' + newFileName, function(err, info) {
                body.image = newFileName;
                fs.unlinkSync(path.resolve(tempPath + ext));

                db.recipe.create(body).then(function(recipe) {
                    res.redirect('/recipe/view/' + recipe.id);
                }, function(e) {
                    console.log(e.message);
                    res.render('error', {message: e.toString()});
                });
            });

        //fs.renameSync(tempPath, targetPath);
    } else {

        db.recipe.create(body).then(function(recipe) {
            res.redirect('/recipe/view/' + recipe.id);
        }, function(e) {
            console.log(e.message);
            res.render('error', {message: e.toString()});
        });
    }
},

A: If you use path to determine where to save the file it will transport easily from one system to another.  I actually created a few variables to determine where to save the file.  Below is my code.
if (process.env.NODE_ENV === 'production') {
   var finalUploadPath = 'hidden';
   var googleTracking = true;
} else if (process.env.NODE_ENV === 'staging') {
   var finalUploadPath = 'hidden';
   var googleTracking = false;
} else {
   var finalUploadPath = 'hidden';
   var googleTracking = false;
}

sharp(imageFile)
            .resize(450, 450)
            .max()
            .toFile(finalUploadPath + req.file.filename + '.jpg', function(err, info) {
                body.image = req.file.filename + '.jpg';
                fs.unlinkSync(path.resolve(tempPath + ext));

                compressAndResize(path.resolve(__dirname, '../public/finalUpload/' + body.image));

                db.recipe.create(body).then(function(recipe) {
                    req.flash('success', 'Recipe created');
                    res.redirect('/recipe/view/' + recipe.id + '/' + recipe.slug);
                }, function(e) {
                    console.log(e.message);
                    req.flash('error', 'Error creating new recipe');
                    res.render('error', {message: e.toString(), csrfToken: req.csrfToken(), google: googleTracking});
                });
            });


text:
Q: How can I upload a video on Instagram using Python? The Instagram page does not have an option to upload videos when you open the page from a computer, I usually use Python Selenium to find a position on the screen and send text or upload/download a file, however, I cannot use Selenium on Instagram because the Instagram version for Computer does not show any button to upload a video.
I did a testing using INSTABOT to upload a photo, the testing was successful, but when I try to upload a video, INSTABOT cannot upload it.
I would like to know if someone has any script to upload videos on Instagram using python.
Thanks

A: Use this library:
https://github.com/instagrambot/instapy-cli/tree/master/examples
Here is an example of what you asked:
from instapy_cli import client

username = 'USERNAME'
password = 'PASSWORD'
video = 'docs/video-sample-upload.mp4'
text = 'This will be the caption of your video.' + '\r\n' + 'You can also use hashtags! #hash #tag #now'

with client(username, password) as cli:
    cli.upload(video, text)


text:
Q: Python: Protect password argument when multiple calls are needed I am implementing a class that represents a connection to e.g., an API/database, and want to provide a method to reconnect when the connection is lost (e.g., due to a timeout). The user provides a username and a password at initialization, which has to be in raw text due to API requirements.
I think one should NOT store the password in any instance variable; I am aware that one may use the "keyring" library, but was wondering if there is any way that does not depend on external libraries and/or the password cannot be later revealed by any means.
One method I came up with is to use a lambda creator:
class Connection:
    def __init__(self, *args, **kwargs):
         # other stuff
         password = input("some message")
         self.connection_handle = (lambda pass : (lambda : api.connect(password=pass))(password)
         del password
         self.conn = self.connection_handle()

    def reconnect(self):
         self.conn = self.connection_handle()

where for simplicity we assume only password, which is a raw password, is used by some API provided connection procedure api.connect.
I tried inspect.showsource and also examined other attributes of connection_handle. It seemed to me that one cannot find the value of the password anywhere. But I am not entirely sure.
So here are my questions:

*

*Is this lambda creator method really secure in that password cannot be recovered even if one can access the instance of the Connection?

*Is there any "standard paradigm" to deal with such scenarios when a method needs to be called several times with sensitive argument which one does not wish to store?
Thanks in advance.


text:
Q: C++ detached thread continues to work after its associated object was deleted In a scope I create an object, which contains a thread. The thread is detached in object c-tor. Finally I delete the object, but the thread keeps continuing, after the associated object memory was freed. Does the detached thread saves the objects copy or it only reference to the program stack, which will be erased further on?
struct test_detach {
    test_detach()
    : thr_(&test_detach::loop, this) {
        thr_.detach();
    }

    void loop() {
        while(true) {
            cout << "loop test" << endl;
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
        }
    }

    std::thread thr_;
};

int main()
{
    {
        test_detach *test = new test_detach;
        std::this_thread::sleep_for(std::chrono::seconds(1));

        delete test;
    }
    cout << "Sleep" << endl;;
    std::this_thread::sleep_for(std::chrono::seconds(3));

    cout << "Finish!" << endl;;

    return 0;
}

The program output:
loop test
loop test
Sleep
loop test
loop test
loop test
loop test
loop test
loop test
Finish!

A: Well the thread keeps on going until the program is terminated. Your thread doesn't use any data fields of the particular test_detach structure, so there is no SEGFAULT. If you however add a member variable to the structure and attempt to access it from the detached thread after the structure was deleted from the main thread it might cause a SEGFAULT / undefined behaviour etc. The test_detach structure is located on the heap. It is not copied anywhere, that is sort of the point. However:
void loop() {
   int x = 0;
    while(true) {
        cout << "loop test, x: " << x++ << endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }
}

will work correctly since x is on the stack which is maintained for the particular thread.


text:
Q: Why I'm getting 404 Resource Not Found to my newly Azure OpenAI deployment? I've gone through this quickstart and I created my Azure OpenAI resource + created a model deployment which is in state succeedded. I also playaround it in https://oai.azure.com/ and it works there.
But, If I try to reach it from REST API is returns 404 Resource Not Found.
I defined the api-key header, and took the url and json from Code View -> json from inside the playground.
I'm executing
POST
https://raz-openai.openai.azure.com/openai/deployments/raz-model-2/completions?api-version=2022-12-01
{
"prompt": "",
"max_tokens": 100
}
with api-key header
Am I missing another step?

A: Adding as an answer use a GET request instead of POST.


text:
Q: jquery checking if the selected page is current page How to check using jquery if the page selected in drop down menu is the one that i'm already on, so that it's not being loaded again?
here is a snippet:
$('select').change(function () {
    window.location.href = $(this).val();
});

thanks!

A: Use an if statement:
$('select').change(function() {
    if(window.location.href != this.value)
        window.location.href = this.value;
});


text:
Q: PHP SoapClient: Object of class stdClass could not be converted to string I'm making what's likely to be a really simple mistake but can't seem to work out. I'm attempting to send a SOAP request to a web service using the PHP SoapClient library. The following error occurs when attempting to print:

"Object of class stdClass could not be converted to string"

Here is the code, taken primarily from the PHP SoapClient Manual.
<?php

try {
    $options = array(
                     'soap_version'=>SOAP_1_2,
                     'exceptions'=>true,
                     'trace'=>1,
                     'cache_wsdl'=>WSDL_CACHE_NONE
                    );
    $client = new SoapClient('http://www.webservicex.net/ConvertTemperature.asmx?WSDL', $options);

    $results = $client->ConvertTemp(array('Temperature'=>'100', 'FromUnit' => 'degreeCelsius',
                                          'ToUnit' => 'degreeFahrenheit'));
    }
    catch (Exception $e)
    {
      echo "
Exception Error!
";
      echo $e->getMessage();
    }

$results = $client->ConvertTemp(array('Temperature'=>'100', 'FromUnit' => 'degreeCelsius',
                                    'ToUnit' => 'degreeFahrenheit'));

print $results;
?>

I understand that the message is telling me that I'm trying to print an entire object rather than a member of that object. What I don't understand is that I'm expecting a call to ConvertTemp to return a string. Why is an object being return? Thanks in advance for any help.

A: Well, your expectations may be wrong. A var_dump or print_r can shed light on what $results actually is, re-examing the wsdl could tell you why:
Hint: __getTypes():
struct ConvertTempResponse {
 double ConvertTempResult;
}


text:
Q: Creating exe from jar file that runs on other computers I have a simple application consisting of 3 classes which are PercentIdentity.java, GUI.java and Aligner.java
I am working with Intellij Idea 11.1.3 (I also tried it with Eclipse) and JRE 1.7. My operating system is Win 7 x64.
My program works fine when I double click the jar file I created by using Intellij. Also, it works when I execute the command "java -jar *.jar" where * is the name of my jar file.
Now I want to create an .exe file, so I can run the program on the other computers.
I opened the .jar file with Winrar and i can see the manifest file (MANIFEST.MF) inside the META-INF folder.
My manifest file:
Manifest-Version: 1.0
Main-Class: com.example.PercentIdentity (with an empty line in the end)

After spending a lot of time on Launch4j, JSmooth and IExpress, I managed to create .exe files which are running perfectly on my computer. However, when I run the .exe file on another compuer (again with Win 7 x64) it gives the error:
"Java Virtual Machine Launcher:
Could not find the main class:
com.example.PercentIdentity. Program will exit."
My JSmooth settings are as follows:
Skeleton Selection: Window Wrapper
Executable: test.exe
Current Directory: . (not sure what to put)
Main Class: com.example.PercentIdentity
Embedded Jar: *.jar
Classpath: *.jar (the same with above)
Min JVM Version: 1.0
Max JVM Version: 1.7
The settings I am using in Launch4j:
Output file: C:\Users\{name}\Desktop\test.exe
Jar: *.jar
(I am not checking the checkbox "Don't wrap the jar")
Manifest: (empty)
Min JRE Version: 1.0
I read an answer in another similar question that the problem may occur because of JRE 1.7, so I tried 1.6 also. However, this time it didn't run even on my own computer.
Anyone have an idea how I can overcome this problem?
Thanks in advance.

A: In Jsmooth , is classpath for the .jar?
Don't say it matters and can be left blank for the jar (implicit location),
current directory maybe left blank better than a dot, if anything probably .\ (with a backslash for windows - means current directory).
for main class you can probably just say "PercentIdentity" as the classpath and paths get searched so if there is only one there in the .jar it will be chosen.
about implying where the jar is it is probably given a blank notation or in some configuration documents it is given the notation . , dot is usually used for web sever purposes unless it is part of . in windows or ./ in unix meaning "this directory its in".
If you wish to learn a small quantity of C/C++ you can get away with a short one liner using
execv() function and an array or execlp() function and a list, However you will need to learn a large quantity of C/C++ to use the **args pointer array to pass command line parameters.


text:
Q: How to prevent MVC ActionFilterAttribute from being cached? I have a MVC API ActionFilterAttribute that does a permissions check using the Entity Framework.  I've found that because of ActionFilterAttribute caching the EF connection is often broken.  You can find other questions about here. So does anyone know how to prevent caching in ActionFilterAttributes?

A: Just a Note to your title: I would say that Action Filters in MVC are not cached, they act as singletons (as explained in the link you've provided).
As the answer to your needs I would say use Request based persistence. Because you would most likely want to do some stuff like:
- OnActionExecuting() (e.g. open Transaction)
- OnActionExecuted() (commit or rollback)
So put your object (_unitOfWork) into
System.Web.HttpContext.Current.Items

You can access it form the singleton methods, while operating on request dependent objects. I am doing it similar way with NHibernate Session


text:
Q: Jquery: Open a new HTML windows when button is click 1) I'm trying to get this working just for testing purpose, can you help me out?
$(document).ready(function (){
   var name = 'Juan';
   var pass = '123456';
   $('#boton').click( function () {
    if ($('#name') === name && $('#pass') === pass ) {
        windows.open('mainScreen.html'):
    }
    else {
        alert("WRONG PASSWORD");
    }

    });
});

A: You can use this code:-
Here is working demo: https://output.jsbin.com/qitedoq
<!doctype html>
<html lang="en">
<head>
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script>
  $(document).ready(function (){
    var name = 'Juan';
    var pass = '123456';
    $('#boton').click( function () {
      if ($('#name').val() === name && $('#pass').val() === pass ) {
          window.open('https://www.google.com/');
      } else {
          alert("WRONG PASSWORD");
      }
    });
  });
  </script>
</head>
<body>
<input type="text" id="name" placeholder="Username"> <br />
<input type="text" id="pass" placeholder="Password">
<button id="boton">Click Here</button>
</body>
</html>


text:
Q: Wildcard namespaces in lxml How to query using xpath ignoring the xml namespace? I am using python lxml library. I tried the solution from this question but doesn't seem to work.
In [151]: e.find("./*[local-name()='Buckets']")
  File "<string>", line unknown
SyntaxError: invalid predicate

A: Use e.xpath, not e.find:

import lxml.etree as ET

content = '''\
<Envelope xmlns="http://www.example.com/zzz/yyy">
  <Header>
    <Version>1</Version>
  </Header>
  <Buckets>
    some stuff
  </Buckets>
</Envelope>
'''
root = ET.fromstring(content)
print(root.xpath("./*[local-name()='Buckets']"))
# [<Element {http://www.example.com/zzz/yyy}Buckets at 0xb73a62ac>]


text:
Q: Call a Function After MVC's Remote Validation I want to call a function after MVC's Remote Validation returns true. But looks like I need another event to call that function. I have tried to call onchange on same  datepicker element but they are not called in the right sequence. I want to call validation first and myFunction later.
P.s. I have also gone through jquery.validate invalidHandler but that doesn't seem to solve the problem. As it also needs some event call.
<span class="fgroup">
    @Html.TextBoxFor(model => model.master.D1, new { @id = "datepicker" })

    @Html.ValidationMessageFor(model => model.master.D1, "", new { @class = "text-danger" })
</span>

Here is my function that I want to call after Remote Validation returns true:
function myFunction1() {

    var datVal = $("#datepicker").val();

    var url = "/TrM/AutoDocNoGen?date=" + datVal;
     $.ajax({
              data: datVal,
              type: "GET",
              url: url,
              success: function (data) {
                 var formValid = $("#allSaveForm").validate().form();

                 if (!formValid) {
                 return false;
                     }
                  $(".vchrNoField").val(data.NewValue);
                      },
              error: function () {

           }

      }); }

After return from the Ajax call I want to update the value of this field. Its very important that the validation is called first and this field below is updated afterwards.
@Html.EditorFor(model => model.master.S1, new { htmlAttributes = new { @class = "text-input-grey vchrNoField" } })

A: I have successfully resolved the issue by using Jquery's ajaxComplete method. It bothered me a lot until I resolved it. Here is what I have done.
$(document).ajaxComplete(function (event, xhr, settings) {
    if (settings.url === "/Rules/datecheck" && xhr.responseJSON == true) {

                        var datVal = $("#datepicker").val();

                            var ur = "/TrM/AutoDocNoGen?date=" + datVal;
                            $.ajax({
                                data: datVal,
                                type: "GET",
                                url: ur,
                                success: function (data) {
                                    $(".vchrNoField").val(da.NewValue);
                                },
                                error: function () {

                                }

                            });
    }
});

So basically I have called my ajax request on ajaxComplete and adding an if statement to check if the response from the remote validation is returned true. And Tada! Its Done!


text:
Q: Manipulating ordering of results of whereis command Right now, if I type whereis on an executable that I'm interested in knowing the location, I get back several results where this software is located.  What configuration can be done to get the last result at the front of the list?
If I'm running whereis gcc, I may have 5 different versions of gcc on the OS, but the highest/most-recent version displays last in the results of whereis gcc, so it's not the preferred version of gcc.  So even though I have version 7.1 of GCC, running gcc -v displays the lowest version that's installed on my box.

A: whereis python | sed 's/ /\n/g' | sort | uniq
Then sort has many options
If you want to reverse the order:
whereis python | sed 's/ /\n/g' | sort -r | uniq
-r, --reverse
    reverse the result of comparisons

if you (could) have some odd binary/source/manual files containing special chars:
-i, --ignore-nonprinting
    consider only printable characters


text:
Q: How to fetch array of JSON object in PHP {
  "HEADER": {
    "TALLYREQUEST": "Import Data"
  },
  "BODY": {
    "IMPORTDATA": {
      "REQUESTDESC": {
        "REPORTNAME": "Vouchers",
        "STATICVARIABLES": {
          "SVCURRENTCOMPANY": "Kraiburg"
        }
      },
      "REQUESTDATA": {
        "TALLYMESSAGE": [{
          "VOUCHER": {
            "@attributes": {
              "REMOTEID": "93584c36-9ad4-47d1-ac37-0205053cd15e-00000137",
              "VCHKEY": "93584c36-9ad4-47d1-ac37-0205053cd15e-0000ab00:00000008",
              "VCHTYPE": "Sales",
              "ACTION": "Create",
              "OBJVIEW": "Invoice Voucher View"
            },
            "OLDAUDITENTRYIDS.LIST": {
              "@attributes": {
                "TYPE": "Number"
              },
              "OLDAUDITENTRYIDS": "-1"
            },
            "DATE": "20191108",
            "GUID": "93584c36-9ad4-47d1-ac37-0205053cd15e-00000137",
            "STATENAME": "Karnataka",
            "COUNTRYOFRESIDENCE": "India",
            "PARTYNAME": "Party A",
            "VOUCHERTYPENAME": "Sales",
            "VOUCHERNUMBER": "2",
            "PARTYLEDGERNAME": "Party A",
            "BASICBASEPARTYNAME": "Party A",
            "CSTFORMISSUETYPE": {},
            "CSTFORMRECVTYPE": {},
            "FBTPAYMENTTYPE": "Default",
            "PERSISTEDVIEW": "Invoice Voucher View",
            "PLACEOFSUPPLY": "Karnataka",
            "BASICBUYERNAME": "Party A",
            "BASICDATETIMEOFINVOICE": "8-Nov-2019 at 16:02",
            "BASICDATETIMEOFREMOVAL": "8-Nov-2019 at 16:02",
            "VCHGSTCLASS": {},
            "CONSIGNEESTATENAME": "Karnataka",
            "ENTEREDBY": "a",
            "DIFFACTUALQTY": "No",
            "ISMSTFROMSYNC": "No",
            "ASORIGINAL": "No",
            "AUDITED": "No",
            "FORJOBCOSTING": "No",
            "ISOPTIONAL": "No",
            "EFFECTIVEDATE": "20191108",
            "USEFOREXCISE": "No",
            "ISFORJOBWORKIN": "No",
            "ALLOWCONSUMPTION": "No",
            "USEFORINTEREST": "No",
            "USEFORGAINLOSS": "No",
            "USEFORGODOWNTRANSFER": "No",
            "USEFORCOMPOUND": "No",
            "USEFORSERVICETAX": "No",
            "ISEXCISEVOUCHER": "No",
            "EXCISETAXOVERRIDE": "No",
            "USEFORTAXUNITTRANSFER": "No",
            "IGNOREPOSVALIDATION": "No",
            "EXCISEOPENING": "No",
            "USEFORFINALPRODUCTION": "No",
            "ISTDSOVERRIDDEN": "No",
            "ISTCSOVERRIDDEN": "No",
            "ISTDSTCSCASHVCH": "No",
            "INCLUDEADVPYMTVCH": "No",
            "ISSUBWORKSCONTRACT": "No",
            "ISVATOVERRIDDEN": "No",
            "IGNOREORIGVCHDATE": "No",
            "ISVATPAIDATCUSTOMS": "No",
            "ISDECLAREDTOCUSTOMS": "No",
            "ISSERVICETAXOVERRIDDEN": "No",
            "ISISDVOUCHER": "No",
            "ISEXCISEOVERRIDDEN": "No",
            "ISEXCISESUPPLYVCH": "No",
            "ISGSTOVERRIDDEN": "No",
            "GSTNOTEXPORTED": "No",
            "IGNOREGSTINVALIDATION": "No",
            "ISVATPRINCIPALACCOUNT": "No",
            "ISBOENOTAPPLICABLE": "No",
            "ISSHIPPINGWITHINSTATE": "No",
            "ISOVERSEASTOURISTTRANS": "No",
            "ISDESIGNATEDZONEPARTY": "No",
            "ISCANCELLED": "No",
            "HASCASHFLOW": "No",
            "ISPOSTDATED": "No",
            "USETRACKINGNUMBER": "No",
            "ISINVOICE": "Yes",
            "MFGJOURNAL": "No",
            "HASDISCOUNTS": "No",
            "ASPAYSLIP": "No",
            "ISCOSTCENTRE": "No",
            "ISSTXNONREALIZEDVCH": "No",
            "ISEXCISEMANUFACTURERON": "No",
            "ISBLANKCHEQUE": "No",
            "ISVOID": "No",
            "ISONHOLD": "No",
            "ORDERLINESTATUS": "No",
            "VATISAGNSTCANCSALES": "No",
            "VATISPURCEXEMPTED": "No",
            "ISVATRESTAXINVOICE": "No",
            "VATISASSESABLECALCVCH": "No",
            "ISVATDUTYPAID": "Yes",
            "ISDELIVERYSAMEASCONSIGNEE": "No",
            "ISDISPATCHSAMEASCONSIGNOR": "No",
            "ISDELETED": "No",
            "CHANGEVCHMODE": "No",
            "ALTERID": " 743",
            "MASTERID": " 311",
            "VOUCHERKEY": "188016488349704",
            "EXCLUDEDTAXATIONS.LIST": {
              "0": "      "
            },
            "OLDAUDITENTRIES.LIST": {
              "0": "      "
            },
            "ACCOUNTAUDITENTRIES.LIST": {
              "0": "      "
            },
            "AUDITENTRIES.LIST": {
              "0": "      "
            },
            "DUTYHEADDETAILS.LIST": {
              "0": "      "
            },
            "SUPPLEMENTARYDUTYHEADDETAILS.LIST": {
              "0": "      "
            },
            "EWAYBILLDETAILS.LIST": {
              "0": "      "
            },
            "INVOICEDELNOTES.LIST": {
              "0": "      "
            },
            "INVOICEORDERLIST.LIST": {
              "0": "      "
            },
            "INVOICEINDENTLIST.LIST": {
              "0": "      "
            },
            "ATTENDANCEENTRIES.LIST": {
              "0": "      "
            },
            "ORIGINVOICEDETAILS.LIST": {
              "0": "      "
            },
            "INVOICEEXPORTLIST.LIST": {
              "0": "      "
            },
            "LEDGERENTRIES.LIST": {
              "OLDAUDITENTRYIDS.LIST": {
                "@attributes": {
                  "TYPE": "Number"
                },
                "OLDAUDITENTRYIDS": "-1"
              },
              "LEDGERNAME": "Party A",
              "GSTCLASS": {},
              "ISDEEMEDPOSITIVE": "Yes",
              "LEDGERFROMITEM": "No",
              "REMOVEZEROENTRIES": "No",
              "ISPARTYLEDGER": "Yes",
              "ISLASTDEEMEDPOSITIVE": "Yes",
              "ISCAPVATTAXALTERED": "No",
              "ISCAPVATNOTCLAIMED": "No",
              "AMOUNT": "-400.00",
              "SERVICETAXDETAILS.LIST": {
                "0": "       "
              },
              "BANKALLOCATIONS.LIST": {
                "0": "       "
              },
              "BILLALLOCATIONS.LIST": {
                "NAME": "2",
                "BILLCREDITPERIOD": "10 Days",
                "BILLTYPE": "New Ref",
                "TDSDEDUCTEEISSPECIALRATE": "No",
                "AMOUNT": "-400.00",
                "INTERESTCOLLECTION.LIST": {
                  "0": "        "
                },
                "STBILLCATEGORIES.LIST": {
                  "0": "        "
                }
              },
              "INTERESTCOLLECTION.LIST": {
                "0": "       "
              },
              "OLDAUDITENTRIES.LIST": {
                "0": "       "
              },
              "ACCOUNTAUDITENTRIES.LIST": {
                "0": "       "
              },
              "AUDITENTRIES.LIST": {
                "0": "       "
              },
              "INPUTCRALLOCS.LIST": {
                "0": "       "
              },
              "DUTYHEADDETAILS.LIST": {
                "0": "       "
              },
              "EXCISEDUTYHEADDETAILS.LIST": {
                "0": "       "
              },
              "RATEDETAILS.LIST": {
                "0": "       "
              },
              "SUMMARYALLOCS.LIST": {
                "0": "       "
              },
              "STPYMTDETAILS.LIST": {
                "0": "       "
              },
              "EXCISEPAYMENTALLOCATIONS.LIST": {
                "0": "       "
              },
              "TAXBILLALLOCATIONS.LIST": {
                "0": "       "
              },
              "TAXOBJECTALLOCATIONS.LIST": {
                "0": "       "
              },
              "TDSEXPENSEALLOCATIONS.LIST": {
                "0": "       "
              },
              "VATSTATUTORYDETAILS.LIST": {
                "0": "       "
              },
              "COSTTRACKALLOCATIONS.LIST": {
                "0": "       "
              },
              "REFVOUCHERDETAILS.LIST": {
                "0": "       "
              },
              "INVOICEWISEDETAILS.LIST": {
                "0": "       "
              },
              "VATITCDETAILS.LIST": {
                "0": "       "
              },
              "ADVANCETAXDETAILS.LIST": {
                "0": "       "
              }
            },
            "ALLINVENTORYENTRIES.LIST": {
              "STOCKITEMNAME": "Item 1",
              "ISDEEMEDPOSITIVE": "No",
              "ISLASTDEEMEDPOSITIVE": "No",
              "ISAUTONEGATE": "No",
              "ISCUSTOMSCLEARANCE": "No",
              "ISTRACKCOMPONENT": "No",
              "ISTRACKPRODUCTION": "No",
              "ISPRIMARYITEM": "No",
              "ISSCRAP": "No",
              "RATE": "400.00\/Nos",
              "AMOUNT": "400.00",
              "ACTUALQTY": " 1 Nos",
              "BILLEDQTY": " 1 Nos",
              "BATCHALLOCATIONS.LIST": {
                "GODOWNNAME": "Damaged GoDown",
                "BATCHNAME": "213",
                "DESTINATIONGODOWNNAME": "Damaged GoDown",
                "INDENTNO": {},
                "ORDERNO": {},
                "TRACKINGNUMBER": {},
                "DYNAMICCSTISCLEARED": "No",
                "AMOUNT": "400.00",
                "ACTUALQTY": " 1 Nos",
                "BILLEDQTY": " 1 Nos",
                "ADDITIONALDETAILS.LIST": {
                  "0": "        "
                },
                "VOUCHERCOMPONENTLIST.LIST": {
                  "0": "        "
                }
              },
              "ACCOUNTINGALLOCATIONS.LIST": {
                "OLDAUDITENTRYIDS.LIST": {
                  "@attributes": {
                    "TYPE": "Number"
                  },
                  "OLDAUDITENTRYIDS": "-1"
                },
                "LEDGERNAME": "Sales",
                "GSTCLASS": {},
                "ISDEEMEDPOSITIVE": "No",
                "LEDGERFROMITEM": "No",
                "REMOVEZEROENTRIES": "No",
                "ISPARTYLEDGER": "No",
                "ISLASTDEEMEDPOSITIVE": "No",
                "ISCAPVATTAXALTERED": "No",
                "ISCAPVATNOTCLAIMED": "No",
                "AMOUNT": "400.00",
                "SERVICETAXDETAILS.LIST": {
                  "0": "        "
                },
                "BANKALLOCATIONS.LIST": {
                  "0": "        "
                },
                "BILLALLOCATIONS.LIST": {
                  "0": "        "
                },
                "INTERESTCOLLECTION.LIST": {
                  "0": "        "
                },
                "OLDAUDITENTRIES.LIST": {
                  "0": "        "
                },
                "ACCOUNTAUDITENTRIES.LIST": {
                  "0": "        "
                },
                "AUDITENTRIES.LIST": {
                  "0": "        "
                },
                "INPUTCRALLOCS.LIST": {
                  "0": "        "
                },
                "DUTYHEADDETAILS.LIST": {
                  "0": "        "
                },
                "EXCISEDUTYHEADDETAILS.LIST": {
                  "0": "        "
                },
                "RATEDETAILS.LIST": {
                  "0": "        "
                },
                "SUMMARYALLOCS.LIST": {
                  "0": "        "
                },
                "STPYMTDETAILS.LIST": {
                  "0": "        "
                },
                "EXCISEPAYMENTALLOCATIONS.LIST": {
                  "0": "        "
                },
                "TAXBILLALLOCATIONS.LIST": {
                  "0": "        "
                },
                "TAXOBJECTALLOCATIONS.LIST": {
                  "0": "        "
                },
                "TDSEXPENSEALLOCATIONS.LIST": {
                  "0": "        "
                },
                "VATSTATUTORYDETAILS.LIST": {
                  "0": "        "
                },
                "COSTTRACKALLOCATIONS.LIST": {
                  "0": "        "
                },
                "REFVOUCHERDETAILS.LIST": {
                  "0": "        "
                },
                "INVOICEWISEDETAILS.LIST": {
                  "0": "        "
                },
                "VATITCDETAILS.LIST": {
                  "0": "        "
                },
                "ADVANCETAXDETAILS.LIST": {
                  "0": "        "
                }
              },
              "DUTYHEADDETAILS.LIST": {
                "0": "       "
              },
              "SUPPLEMENTARYDUTYHEADDETAILS.LIST": {
                "0": "       "
              },
              "TAXOBJECTALLOCATIONS.LIST": {
                "0": "       "
              },
              "REFVOUCHERDETAILS.LIST": {
                "0": "       "
              },
              "EXCISEALLOCATIONS.LIST": {
                "0": "       "
              },
              "EXPENSEALLOCATIONS.LIST": {
                "0": "       "
              }
            },
            "PAYROLLMODEOFPAYMENT.LIST": {
              "0": "      "
            },
            "ATTDRECORDS.LIST": {
              "0": "      "
            },
            "GSTEWAYCONSIGNORADDRESS.LIST": {
              "0": "      "
            },
            "GSTEWAYCONSIGNEEADDRESS.LIST": {
              "0": "      "
            },
            "TEMPGSTRATEDETAILS.LIST": {
              "0": "      "
            }
          }
        }, {
          "COMPANY": {
            "REMOTECMPINFO.LIST": {
              "@attributes": {
                "MERGE": "Yes"
              },
              "NAME": "93584c36-9ad4-47d1-ac37-0205053cd15e",
              "REMOTECMPNAME": "Kraiburg",
              "REMOTECMPSTATE": "Karnataka"
            }
          }
        }, {
          "COMPANY": {
            "REMOTECMPINFO.LIST": {
              "@attributes": {
                "MERGE": "Yes"
              },
              "NAME": "93584c36-9ad4-47d1-ac37-0205053cd15e",
              "REMOTECMPNAME": "Kraiburg",
              "REMOTECMPSTATE": "Karnataka"
            }
          }
        }]
      }
    }
  }
}

A: <?php
$json ='<replace with your large json string>';
$array = json_decode($json, true);
var_dump($array);

you can try it on http://sandbox.onlinephpfunctions.com/


text:
Q: Why first network call takes more time than subsequent ones? I am trying to understand this behavior where first network call takes more than double of subsequent ones. I know that DNS resolving will not take more than 5-50ms and it happens only in the initial call. Considering this info, there shouldn't be much difference in time taken for the first call and subsequent calls.
I have tested this behavior with some famous URLs in separate incognito windows for each with cache disabled and attached a few screenshots to support my observation below. Can anyone help me understand this behavior?
Note: The readings are taken in full speed internet connection
Thanks in advance

A: After a  few experiments, I found out that Content Download (browser request steps) part of the request is speeding up 1.5-2 times
This looks like a cause of TCP Slow Start algorithm
As it states:

modern browsers either open multiple connections simultaneously or reuse one connection for all files requested from a particular web server

That might be the reason for the first request to be slower than others
Also, @Vishal Vijay made a good addition:
Making initial connection handshake to the server is taking time (DNS Lookup + Initial connection + SSL). Browsers are creating Persistent Connections for HTTP requests and keep it open for some time. If any request came in for the same domain within that time, the browser will try to reuse the same connection for faster response.

A: In some cases it might be server-side cache mechanism causing subsequent request to process faster, but let's just talk about the browser-side stuffs.
When you hover on the waterfall 'blocks' you will get the time details:

Here is a quick reference for each of the phases (from Google Developers):

*

*Queueing. The browser queues requests when:

*

*There are higher priority requests.

*There are already six TCP connections open for this origin, which is the limit. Applies to HTTP/1.0 and HTTP/1.1 only.

*The browser is briefly allocating space in the disk cache

*Stalled. The request could be stalled for any of the reasons described in Queueing.

*DNS Lookup. The browser is resolving the request's IP address.

*Proxy negotiation. The browser is negotiating the request with a proxy server.

*Request sent. The request is being sent.

*ServiceWorker Preparation. The browser is starting up the service worker.

*Request to ServiceWorker. The request is being sent to the service worker.

*Waiting (TTFB). The browser is waiting for the first byte of a response. TTFB stands for Time To First Byte. This timing includes 1
  round trip of latency and the time the server took to prepare the
  response.

*Content Download. The browser is receiving the response.

*Receiving Push. The browser is receiving data for this response via HTTP/2 Server Push.

*Reading Push. The browser is reading the local data previously received.

So what's difference between the first and subsequent requests in traditional HTTP/1.1 scenario?

*

*DNS Lookup: It might take more time to resolve DNS for the first request. Subsequent requests will resolve a lot faster using browser DNS cache.

*Waiting (TTFB): The first request have to establish TCP connecting to the server. Due to HTTP keep-alive mechanism, subsequent requests to the same server will reuse the existing TCP connection to prevent another TCP handshake, thus reducing three round-trip time compared the first request.

*Content Download: Due to TCP slow start, the first request will need more time to download content. Since subsequent requests will reuse the TCP connection, when the TCP window scaled up, the content will be downloaded much faster than the first request.

Thus generally subsequent requests should be much faster than the first request. Actually this leads to a common network optimization strategy: Use as few domains as possible for your website.
HTTP/2 even introduces multiplexing to better reuse a single TCP connection. That's why HTTP/2 will give a performance boost in modern front end world, where we deploy tons of small assets on the CDN servers.


text:
Q: Exaggerated CSS ease-in height transition How would I be able to achieve the exaggerated ease-in height transition as seen in the dropdown menu transition of this website? Normal CSS transitions are a lot more linear then what I am seeing rendered here. Thanks!

A: You can define your own custom easings using the Cubic Bezier timing functions.
For instance, instead of the standard linear easing, you could do something like:
.selector {
    transition: right .5s cubic-bezier(.55,.04,.27,.91);
}

For an easy-to-use tool to make your own easings you can try cubic-bezier.com.


text:
Q: video upload using node.js and mongodb I am New to MongoDB and node.js. I want to know how can I store and fetch a video file in MongoDB using node.js? Any help will be appreciated. The code that I am using is:
app.post('/videos/new', function(req, res) {
  req.form.complete(function(err, fields, files) {
    console.log('here i go');
    if(err) {
      next(err);
    } else {
      ins = fs.createReadStream(files.file.path);
      console.log('insssssssssssss'+ins);
      ous = fs.createWriteStream(__dirname + '/static/uploads/videos/' + files.file.filename);
      util.pump(ins, ous, function(err) {
        if(err) {
          next(err);
        } else { RegProvider.save({
           file: req.param(files.file.filename),
                   filename: req.param('filename')
                 }, function(error, docs) {
              res.redirect('/videos');
         });
        }
      });
      //console.log('\nUploaded %s to %s', files.file.filename, files.file.path);
      //res.send('Uploaded ' + files.file.filename + ' to ' + files.file.path);
    }
  });
});

The code to retrieve video files is:
var fs = require('fs');

var src_path = __dirname + '/static/uploads/vidoes/'
module.exports.list = function(callback) {
  fs.readdir(src_path,function(err, files){
    var ret_files = [];
    files.forEach(function(file) {
    ret_files.push('/uploads/videos/' + file);
    });
    console.log(ret_files);
    callback(err, ret_files);
  });
};

It is working fine, but doesn't store anything in MongoDB.

A: https://github.com/marcello3d/node-mongolian
is useful for string files in GridFS.
There are more examples of how to use the library than I can post here in the examples folder.
here:
https://github.com/marcello3d/node-mongolian/blob/master/examples/mongolian_trainer.js
If you are uncertain of what GridFS is you can find out here:
http://www.mongodb.org/display/DOCS/GridFS
and thanks for improving your question.