text:
Q: Will Windows XP sense a drive is an SSD and thereby avoid defragging it even if the user tries to manually run defrag? There's no point in defragging an SSD, but what happens if a user decides on their own to run the native Win XP defragging tool? Will Windows XP sense a drive is an SSD and thereby avoid defragging it even if the user tries to run defrag manually?
I have heard that later Windows versions "usually detects SSD disk after this has been installed or connected and integrates it properly" https://web.archive.org/web/20140206154059/http://support.microsoft.com/kb/2727880 but, then, we are talking about a much older vintage the customers of my employer still use, and which I am obligated to support.

A: Windows XP doesn't defragment a disk automatically. You have to do it manually or set up a task for that. See:
- How to Automate Disk Defragmenter in Windows XP
- How do I turn off fragmentation in Windows XP?  (sic)
Yes, a user can still run the Disk Defragmenter tool on Windows XP. If it doesn't happen to often, it doesn't do any damage. But it should not be set up to run automatically.
When you replace the disks with SSD ones, you should tell your customers that they should not use the Disk Defragmenter tool any more.
If you are really paranoid, you could delete the Disk Defragmenter tool from the Windows XP machines.
Windows 7 and later detect an SSD and refrain from defragmenting when not necessary. See this article. Conclusion:

No, Windows is not foolishly or blindly running a defrag on your SSD every night, and no, Windows defrag isn't shortening the life of your SSD unnecessarily. Modern SSDs don't work the same way that we are used to with traditional hard drives.
Yes, your SSD's file system sometimes needs a kind of defragmentation and that's handled by Windows, monthly by default, when appropriate. The intent is to maximize performance and a long life. If you disable defragmentation completely, you are taking a risk that your filesystem metadata could reach maximum fragmentation and get you potentially in trouble.


text:
Q: Use signals in Django 1.9 In Django 1.8, I was able to do the following with my signals, and all was well:
__init__.py:
from .signals import *

signals.py:
@receiver(pre_save, sender=Comment)
def process_hashtags(sender, instance, **kwargs):
    html = []
    for word in instance.hashtag_field.value_to_string(instance).split():
        if word.startswith('#'):
            word = render_to_string('hashtags/_link.html',
                                    {'hashtag': word.lower()[1:]})

        html.append(word)
        instance.hashtag_enabled_text = ' '.join(html)

In Django 1.9, I get this error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
I know it's coming from the __init__.py, but does anyone know a workaround for this? I'm assuming maybe putting it in the models? If so, could someone please show me how to do that?
models.py:
class Comment(HashtagMixin, TimeStampedModel):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    text = models.TextField(max_length=240)
    hashtag_enabled_text = models.TextField(blank=True)
    hashtag_text_field = 'text'

    objects = CommentManager()

    class Meta:
        app_label = 'comments'

    def __unicode__(self):
        return self.text

Thank you in advance!

A: From the release notes:

All models need to be defined inside an installed application or declare an explicit app_label. Furthermore, it isn't possible to import them before their application is loaded. In particular, it isn't possible to import models inside the root package of an application.

By importing your signals in __init__.py, you're indirectly importing your models in the root package of your application. One option to avoid this is to change the sender to a string:
@receiver(pre_save, sender='<appname>.Comment')
def process_hashtags(sender, instance, **kwargs):
    ...

The recommended way to connect signals that use @receiver decorator in 1.9 is to create an application configuration, and import the signals module in AppConfig.ready().

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating a Windows Mobile emulator image I was wondering if there was a way to create my own Windows Mobile emulator image.  I have a Sony Ericsson XPERIA X1 phone, which has a 480x800 on a 3 inch screen, approximately 300 DPI.
I'd like to create an emulator image with the correct screen properties, and hopefully a skin that resembles the correct button locations and stuff for the phone.
I do own the phone, so I can create an image from the phone if necessary.
Is this possible, and if so, how?

A: You don't need a custom image for what you're describing (and you couldn't create one if you needed to anyway).  The emulator image contains only the OS functionality itself.  The skin, buttons and screen size are all configured in an XML file.
As an example, install the WinMo 5.0 SDK and then navigate to here:
C:\Program Files\Windows Mobile 5.0 SDK R2\PocketPC\Deviceemulation\Pocket_pc

You'll find Pocket_PC.xml.  In it is describes things like the skin images (as well as button actions):
<view
    titleBar ="Pocket PC - WM 5.0"
    displayPosX="55"
    displayPosY="67"
    displayWidth="240"
    displayHeight="320"
    displayDepth="16"
    mappingImage="pocket_pc_emulator_mask.png"
    normalImage="pocket_pc_emulator_up.png"
    downImage= "pocket_pc_emulator_down.png">

You'll see that the skins are in separate folders at the same level as the 0409 folder, which contains the actual CE image.
Browse around and you'll see the same layout for Smartphone, and in fact the WinMo 6.0 SDK is the same way (not coincidentally).
Now head over to Studio and look in Tools->Options->Device Tools->Devices.  Select any given emulator and click "Properties" and then "Emulator Options".  Here you'll find another way to adjust display settings and skins.  You can copy any existing emulator configuration by clicking "Save As" and then adjust it to match what you're after.


text:
Q: How to update a table using inner join I have two tables Emp & Dept.
SQL> select * from emp where rownum<4;

     EMPNO ENAME      JOB              MGR        SAL     DEPTNO
---------- ---------- --------- ---------- ---------- ----------
      7369 SMITH      CLERK           7902        800
      7499 ALLEN      SALESMAN        7698       1600
      7521 WARD       SALESMAN        7698       1250

SQL> select * from dept;

    DEPTNO DNAME           LOC                  EMPNO
---------- --------------- --------------- ----------
        10 ACCOUNTING      NEW YORK              7369
        20 RESEARCH        DALLAS                7499
        30 SALES           CHICAGO               7521
        40 OPERATIONS      BOSTON

i want to update deptno of emp which should be same as deptno of dept table & where empno of dept should be equal to empno of emp;        In short i want to update dept using inner join operation with emp;

A: In Oracle, the canonical way to do it is the MERGE statement:
MERGE INTO emp e
USING dept d
   ON (d.empno = e.empno)
 WHEN MATCHED THEN UPDATE SET e.deptno = d.deptno

However the above will not work if you are using Oracle 9 (see below), or if there are domain index on your tables (Oracle Text for instance)
I asked a question previously about what MERGE statements do.
It is necessary that each row of e be connected by the join condition (ON section) to none or exactly 1 row of d, otherwise you'll get ORA-30926 "Unable to get a stable set of rows in the source tables".
Rows of e not connected to any department get unchanged, rows of d not connected to any employee could be used for INSERTS (and in Oracle 9 must be used in a  WHEN NOT MATCHED THEN INSERT(cols) VALUES(...) clause; if you're using Oracle 9 then this answer is not suitable for you).
Another option, but subject to the same underlying restrictions:
UPDATE (SELECT e.deptno edeptno, d.deptno ddeptno
          FROM emp e, dept d
         WHERE e.empno = d.empno)
   SET edeptno = ddeptno

Or
UPDATE emp
   SET deptno = ( SELECT deptno FROM dept WHERE empno = emp.empno )
 WHERE empno IN ( SELECT empno FROM dept )

As you can see solutions are numerous but subject to constraints.

A:
Update emp e
set deptno = ( select DEPTNO from dept d where d.empno = e.empno )

Will work as long as the EMPNO in DEPT is unique.
Edit -
As pointed out, this will fail if EMPNO is not there.
The very HACKY fix to this is,

Update emp e
set deptno = (
         SELECT RESULT FROM (
          select DEPTNO RESULT from dept d where d.empno = e.empno
           UNION ALL
           select NULL from DUAL
           ORDER BY 1
           ) WHERE ROWNUM < 2
         )


text:
Q: $\int_{0}^{\infty}\frac{\sin^{2n+1}(x)}{x} \mathrm {d}x$ Evaluate Integral Here is a fun integral I am trying to evaluate:
$$\int_{0}^{\infty}\frac{\sin^{2n+1}(x)}{x} \ dx=\frac{\pi \binom{2n}{n}}{2^{2n+1}}.$$
I thought about integrating by parts $2n$ times and then using the binomial theorem for $\sin(x)$, that is, using $\dfrac{e^{ix}-e^{-ix}}{2i}$ form in the binomial series.
But, I am having a rough time getting it set up correctly. Then, again, there is probably a better approach.
$$\frac{1}{(2n)!}\int_{0}^{\infty}\frac{1}{(2i)^{2n}}\sum_{k=0}^{n}(-1)^{2n+1-k}\binom{2n}{k}\frac{d^{2n}}{dx^{2n}}(e^{i(2k-2n-1)x})\frac{dx}{x^{1-2n}}$$
or something like that. I doubt if that is anywhere close, but is my initial idea of using the binomial series for sin valid or is there a better way?.
Thanks everyone.

A: There is a theorem that states if $f(x)$ is continuous and $\pi$-periodic on $\mathbb{R}$, then $$ \displaystyle\int_{-\infty}^{\infty} \frac{\sin x}{x} f(x) \ dx = \int_{0}^{\pi} f(x) \ dx. $$
See Graham Hesketh's comment for a way to prove this.
Using this theorem, $$ \begin{align} \int_{0}^{\infty} \frac{\sin^{2n+1} (x)}{x} \ dx &= \frac{1}{2} \int_{-\infty}^{\infty} \frac{\sin^{2n+1} (x)}{x} \ dx = \frac{1}{2} \int_{-\infty}^{\infty} \frac{\sin x}{x} \sin^{2n} (x) \ dx \\ &= \frac{1}{2} \int_{0}^{\pi} \sin^{2n} (x) \ dx = \int_{0}^{\frac{\pi}{2}} \sin^{2n} (x) \ dx \\ &= \frac{\pi}{2^{2n+1}} \binom{2n}{n}. \tag{1} \end{align}$$
$(1)$ http://en.wikipedia.org/wiki/Wallis%27_integrals

A: One more just for luck...
Use the evenness of the integrand, the binomial expansion of $\sin(x)^{2n}$ in terms of exponentials, and the Fourier transform representation of the rectangular function and you have:
\begin{aligned}
 \frac{1}{2}\int _{-\infty}^{\infty }\!{\frac { \sin \left( x \right)   ^{
 2\,n+1}}{x}}{dx}&=\frac{1}{{2}^{2n+1}}\sum _{k=0}^{2\,n}  {2\,n\choose k} \left( -1
 \right) ^{n-k}\int _{-\infty }^{\infty }\!{\frac {\sin \left( x
 \right) {{\rm e}^{-2ix \left( n-k \right) }}}{x}}{dx}\\
&=\frac {\pi
}{{2}^{2n+1}}\sum _{k=0}^{2\,n}{2\,n\choose k} \left( -1 \right) ^{n-k}
\cases{1 &$ \left| n-k \right| <1/2$\cr 1/2 &$ \left| n-k \right| =1/2$\cr 0&$ \left| n-k \right|>1/2 $\cr}\\
&=\frac{\pi}{{2}^{2n+1}}{2\,n\choose n}
\end{aligned}
The rectangular function advantageously shows us that the only non-zero-weighted term in the sum is the $k=n$ term and we are spared any further manipulation or evaluation of sums.

A: Using
$$
  \sin^{2n+1}(x) = \sum_{k=0}^n \frac{(-1)^k }{4^n} \binom{2n+1}{n+k+1} \sin\left((2k+1)x\right)
$$
We get
$$ \begin{eqnarray}
  \int_0^\infty \frac{\sin^{2n+1}(x)}{x}\mathrm{d} x &=& \sum_{k=0}^n \frac{(-1)^k }{4^n} \binom{2n+1}{n+k+1}\int_0^\infty \frac{\sin\left((2k+1)x\right)}{x}\mathrm{d} x\\ &=& \sum_{k=0}^n \frac{(-1)^k }{4^n} \binom{2n+1}{n+k+1}\int_0^\infty \frac{\sin\left(x\right)}{x}\mathrm{d} x \\
  &=& \frac{\pi}{2^{2n+1}}\sum_{k=0}^n (-1)^k \binom{2n+1}{n+k+1} = \frac{\pi}{2^{2n+1}} \binom{2n}{n}
\end{eqnarray}
$$
The latter sum is evaluated using telescoping trick:
$$
  \sum_k (-1)^k \binom{2n+1}{n+k+1}  =  \sum_k (-1)^k \frac{2n+1}{n+k+1} \binom{2n}{n+k} =
     (-1)^{k+1} \binom{2n}{n+k} =: g(k)
$$
meaning that
$$
 g(k+1) - g(k) = (-1)^k \binom{2n+1}{n+k+1}
$$
Hence
$$
  \sum_{k=0}^n (-1)^k \binom{2n+1}{n+k+1} = \sum_{k=0}^n \left(g(k+1)-g(k)\right) = g(n+1) - g(0) = -g(0) = \binom{2n}{n}
$$

A: I am just adding the proof of the identity for those who have interest:
$$ \sin^{2n+1} x = \frac{1}{4^n}\sum_{k=0}^{n}(-1)^{n-k}\binom{2n+1}{k}\sin\left(\left(2(n-k)+1\right)x\right). $$
Using the complex representation and the Binomial Theorem, we have
$$\begin{aligned}
\sin^{2n+1}x&=\left(\frac{\mathrm{e}^{ix}-\mathrm{e}^{-ix}}{2i}\right)^{2n+1}\\
&=\frac{(-1)^n}{2^{2n+1}i}\sum_{k=0}^{2n+1}\binom{2n+1}{k}\mathrm{e}^{i(2n+1-k)x}(-1)^k\mathrm{e}^{i(-kx)}\\
&=\frac{(-1)^n}{2^{2n+1}i}\sum_{k=0}^{2n+1}(-1)^k\binom{2n+1}{k}\mathrm{e}^{i(2(n-k)+1)x}\\
&=\frac{(-1)^n}{2^{2n+1}i}\sum_{k=0}^{2n+1}(-1)^k\binom{2n+1}{k}\left[\cos\left(\left(2(n-k)+1\right)x\right) + i\sin\left(\left(2(n-k)+1\right)x\right)\right]\\
&=\frac{(-1)^n}{2^{2n+1}}\sum_{k=0}^{2n+1}(-1)^k\binom{2n+1}{k}\left[\sin\left(\left(2(n-k)+1\right)x\right) - i\cos\left(\left(2(n-k)+1\right)x\right)\right]
\end{aligned}
$$
Now, observe that
$$\begin{aligned}
\sum_{k=0}^{2n+1} a_{k} &= \sum_{k=0}^{n}a_{k}+\sum_{k=n+1}^{n+n+1}a_{k}\\
&=\sum_{k=0}^{n}a_{k}+\sum_{k=0}^{n}a_{n+1+k}\\
&=\sum_{k=0}^{n}a_{k}+\sum_{k=0}^{n}a_{n+1+n-k}\\
&=\sum_{k=0}^{n}\left(a_{k}+a_{2n+1-k}\right)
\end{aligned}
$$
Apply with $a_{k}=(-1)^{k}\binom{2n+1}{k}\left[\sin\left(\left(2(n-k)+1\right)x\right) - i\cos\left(\left(2(n-k)+1\right)x\right)\right]$, so
$$\begin{aligned}
a_{2n+1-k}&=-(-1)^{k}\binom{2n+1}{2n+1-k}\left[-\sin\left(\left(2(n-k)+1\right)x\right) - i\cos\left(\left(2(n-k)+1\right)x\right)\right]\\
&=(-1)^{k}\binom{2n+1}{k}\left[\sin\left(\left(2(n-k)+1\right)x\right) + i\cos\left(\left(2(n-k)+1\right)x\right)\right].
\end{aligned}
$$
Then,
$$ a_{k}+a_{2n+1-k}=2(-1)^{k}\binom{2n+1}{k}\sin\left(\left(2(n-k)+1\right)x\right). $$
Therefore,
$$\begin{aligned} \sin^{2n+1} x&=\frac{1}{4^{n}}\sum_{k=0}^{n}(-1)^{n-k}\binom{2n+1}{k}\sin\left(\left(2(n-k)+1\right)x\right)\\
&=\frac{1}{4^n}\sum_{k=0}^{n}(-1)^k\binom{2n+1}{n-k}\sin\left((2k+1)x\right)\\
&=\frac{1}{4^n}\sum_{k=0}^{n}(-1)^k\binom{2n+1}{n+k+1}\sin\left((2k+1)x\right),
\end{aligned}$$
as desired.

A: Since $\dfrac{\sin^{2n+1}(x)}{x}$ is an even function, we can integrate over the whole real line and divide by $2$.
Write $\sin(x)=\dfrac{e^{ix}-e^{-ix}}{2i}$. Since there are no singularities and the integrand vanishes as $|x|\to\infty$, we can move the path of integration in the direction of $-i$. Expand using the binomial theorem, and close the paths of  integration in two ways: for the integrands with $e^{+ikx}$ circle back counter-clockwise around the upper half-plane ($\gamma^+$); for the integrands with $e^{-ikx}$ circle back clockwise around the lower half-plane ($\gamma^-$).
Note that $\gamma^-$ contains no poles, so those integrals can be ignored.
We will use the identity
$$
\begin{align}
\sum_{k=0}^m(-1)^k\binom{n}{k}
&=\sum_{k=0}^m(-1)^k\binom{n}{k}\binom{m-k}{m-k}\\
&=(-1)^m\sum_{k=0}^m\binom{n}{k}\binom{-1}{m-k}\\
&=(-1)^m\binom{n-1}{m}
\end{align}
$$
Finally, to the point:
$$
\begin{align}
\int_0^\infty\sin^{2n+1}(x)\frac{\mathrm{d}x}{x}
&=\frac12\int_{-\infty}^\infty\sin^{2n+1}(x)\frac{\mathrm{d}x}{x}\\
&=\left(-\frac14\right)^{n+1}i\int_{-\infty}^\infty\left(e^{ix}-e^{-ix}\right)^{2n+1}\frac{\mathrm{d}x}{x}\\
&=\left(-\frac14\right)^{n+1}i\sum_{k=0}^{n}(-1)^k\binom{2n+1}{k}\int_{\gamma^+}e^{ix(2n-2k+1)}\frac{\mathrm{d}x}{x}\\
&+\left(-\frac14\right)^{n+1}i\sum_{k=n+1}^{2n+1}(-1)^k\binom{2n+1}{k}\int_{\gamma^-}e^{ix(2n-2k+1)}\frac{\mathrm{d}x}{x}\\
&=\left(-\frac14\right)^{n+1}i\sum_{k=0}^{n}(-1)^k\binom{2n+1}{k}2\pi i\\
&=\left(-\frac14\right)^{n}\frac{\pi}{2}\sum_{k=0}^{n}(-1)^k\binom{2n+1}{k}\\
&=\left(-\frac14\right)^{n}\frac{\pi}{2}(-1)^n\binom{2n}{n}\\
&=\frac{1}{4^n}\frac{\pi}{2}\binom{2n}{n}
\end{align}
$$


text:
Q: Some files in /assets/css not found [Playframework] Hi I was having this problem with an unresolved dependency:

sbt.ResolveException: unresolved dependency: play#sbt-plugin;2.2.0:
  not found

and then I found the solution here: Upgrading project to version 2.2.0 of the Play Framework
I followed the steps now when I compile or run play there are not errors but when I load the webpage I'm working with it can't find some of the files in /assets/css. After all the changes proposed on the solution I use the command clean, but still the same problem [Status Code:404 Not Found].
This is how I call the files in assets:
> layout.scala.html

    <link rel="stylesheet" href="@routes.Assets.at("css/layout.min.css")" type="text/css">
    <link rel="stylesheet" href="@routes.Assets.at("css/style.min.css")" type="text/css">
    <link rel="stylesheet" href="@routes.Assets.at("css/blocks.min.css")" type="text/css">

I'm using play 2.2.0. Any idea about how to solve it? Thanks


text:
Q: Retrieve results JAX-RS + Jersey + Jackson I have this entity class
@Entity
@XmlRootElement
@Table(name="user")
@NamedQuery(name="User.findAll", query="SELECT u FROM User u")
public class User implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id_user", unique=true, nullable=false)
private String idUser;

@Column(nullable=false, length=50)
private String docnum;

@Column(nullable=false, length=50)
private String email;

@Column(nullable=false, length=50)
private String firstname;

@Column(nullable=false, length=50)
private String lastname;

@Column(nullable=false, length=45)
private String pwd;

//bi-directional many-to-many association to Transaction
@ManyToMany
@JoinTable(
    name="transaction_users"
    , joinColumns={
        @JoinColumn(name="user", nullable=false)
        }
    , inverseJoinColumns={
        @JoinColumn(name="transaction", nullable=false)
        }
    )
private List<Transaction> transactions;

public User() {
}

public String getIdUser() {
    return this.idUser;
}

public void setIdUser(String idUser) {
    this.idUser = idUser;
}

public String getDocnum() {
    return this.docnum;
}

public void setDocnum(String docnum) {
    this.docnum = docnum;
}

public String getEmail() {
    return this.email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getFirstname() {
    return this.firstname;
}

public void setFirstname(String firstname) {
    this.firstname = firstname;
}

public String getLastname() {
    return this.lastname;
}

public void setLastname(String lastname) {
    this.lastname = lastname;
}

public List<Transaction> getTransactions() {
    return this.transactions;
}

public void setTransactions(List<Transaction> transactions) {
    this.transactions = transactions;
}

}
generated from a database table. Then i have this rest service
@Path("service/2.0")
public class ServiceTest {
@GET
@Path("/users")
@Produces(MediaType.APPLICATION_JSON)

public Response getUser() {
    EntityManager entityManager = EntityManagerUtil.getEntityManager();
    entityManager.getTransaction().begin();
    Query q = entityManager.createQuery("SELECT u FROM User u");
    @SuppressWarnings("unchecked")
    List<User> listOfUser = q.getResultList();
    System.out.print(listOfUser);
    return Response.ok(listOfUser).build();
}

I'm (supposed) to be using the jackson API to handle json but i'm not using maven. For this reason, i've added in my buildpath the following .jars:

*

*jackson-annotations-2.9.3.jar

*jackson-core-2.9.3.jar

*jackson-databind-2.9.3.jar

*jackson-jaxrs-base-2.9.3.jar

*jackson-module-jaxb-annotations-2.9.3.jar

*jersey-media-json-jackson-2.26.jar

*jackson-jaxrs-json-provider-2.9.3.jar

Then i have an ApplicationConfig.java class
package prova;
import com.fasterxml.jackson.jaxrs.json.*;
import org.glassfish.jersey.server.ResourceConfig;
import javax.ws.rs.ApplicationPath;

@ApplicationPath("rest")
public class ApplicationConfig extends ResourceConfig {
    public ApplicationConfig() {
        packages("com.fasterxml.jackson.jaxrs.json");
        packages("prova");
    }
}

When i try to submit a GET request with postman, i obtain an "HTTP 500 internal server error" with the description:
"The server encountered an unexpected condition that prevented it from fulfilling the request."
While from the eclipse console i can see
[EL Fine]: sql: 2017-12-16 17:44:54.251--ServerSession(1869059368)--
Connection(771012214)--Thread(Thread[http-nio-8080-exec-80,5,main])--
SELECT id_user, DOCNUM, EMAIL, FIRSTNAME, LASTNAME, PWD FROM user
[prova.User@3c713cb0, prova.User@49e51730, prova.User@d9ecdd7,
prova.User@383fe468]dic 16, 2017 5:44:54
PM org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWr
iterInterceptor aroundWriteTo
GRAVE: MessageBodyWriter not found for media type=application/json,
type=class java.util.Vector, genericType=class java.util.Vector.

So what i can deduce is that the query is correctly executed and it returns an array of 4 object (prova is the name of my entity manager) but then i have the GRAVE:MessageBodyWriter Error
What the hell i'm not doing correctly?why i can not retrieve my JSON data?
Thanks
UPDATE
Following the advice, i've modified the GET resource into
@GET
@Path("/users")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public String getUser() {

    return String.valueOf(10+4);

}

and submitting the GET request gives me the expected JSON answer from Postman "14"....
Can the problem be the conversion of a List into Json?if yes, what to do?
Thanks
UPDATE 2
I've edited the code of the REST resource in this way:
@GET
@Path("/users")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public String getUser() {
    EntityManager entityManager = EntityManagerUtil.getEntityManager();
    entityManager.getTransaction().begin();
    Query q = entityManager.createQuery("SELECT u FROM User u");
    List<User> listOfUser = q.getResultList();
    System.out.print(listOfUser);

    if (listOfUser.isEmpty()) {
        System.out.println("VOID LIST");
        entityManager.close();
        return String.valueOf(2);
    }
    for (User user : listOfUser) {
        System.out.println(user.getFirstname());
        System.out.println("---");
    }
    return String.valueOf(3);
    }

The postman Output is "3" so, everything fine while the consoloe output is:
[EL Fine]: sql: 2017-12-17 13:48:33.214--ServerSession(286337061)--
Connection(2132504260)--Thread(Thread[http-nio-8080-exec-2,5,main])--
SELECT id_user, DOCNUM, EMAIL, FIRSTNAME, LASTNAME, PWD FROM USER
[prova.User@2d3017ff, prova.User@6361d00, prova.User@7ab0944a,
prova.User@5945162f]

matteo
---
tony
---
bruce
---
peter
---

which is perfectly consistent with what i have in the table of the DB... :(

A: Try to convert your response entity in an array of users. There is proper equivalent for array in json.
Other way ist to have a wrapper class for your list of users.
@XmlType
@XmlRootElement
class Wrapper {
  @XmlElement
  List<User> users;
}

Return this in your response.


text:
Q: What does mean "The instance of entity type 'X' are mapped to the same row with the key value Guid, but have different original property" exception I have a complex model in ef core. There are a lots of inheritance and references. Sometimes I am getting an error on saving context:

The instance of entity type 'X' and the instance of entity type 'Y' are mapped to the same row with the >key value '{Guid: 29421520-1733-4659-b38b-f1b8bdafb0c1}', but have different original property values

What does this error mean? Is the problem is in the model, or in business logic, mapping ... and how to resolve it?

A: You never got an answer eh?  I'm assuming you found an answer by now, but I just ran into this problem today, and since I resolved it, figured I'd share my answer.
Cause: two separate entities that were both mapped to the same column in the database and were both being saved during the same transaction but with different values.
In my case, I had a DateTime column Xyz in a ProgressTracking [ComplexType] child-object, and apparently someone couldn't find the property in the ComplexType object so they added the same fields to the parent object...so reading works fine and most saves work fine...until you update one of the values but not the other...then when you save...CRASH!  If you wanted it to work, I'm assuming you would have to do:
var newValue = DateTime.Now;
obj.Xyz = newValue;
obj.ProgressTracking.Xyz = newValue;

Which, I'm not going to try the above to see if it works because that would be asinine.  So:
Solution: remove the property from the parent object and leave it on the ComplexType, then refactor any usages...there were none :-/ ... I really hope I'm not the one who did that (afraid to check source control :-P )


text:
Q: Selecting a range of users active in the past month, but not in the past week I have two tables, users and meetings. I'm trying to select all the users who have NOT made a meeting in the past week, but have made a meeting in the past month.
SELECT  u.id, u.given_name, u.family_name, u.email
    FROM users u
    JOIN meetings m ON (u.id != m.user_id)
    AND m.created_at BETWEEN %s and %s
    AND u.state ='active'
    AND u.id in (SELECT user_id
                 from meetings
               where created_at BETWEEN %s and %s)
    GROUP BY u.id, u.given_name, u.family_name, u.email

This is using the psycopg2 adapter, so %s will be replaced by a datetime object. The %s replacement is in the order of:
7 days ago, today, a month ago, 8 days ago.
Also, the reason i did u.id != m.useridis because the userid will not be in the meetings table if the user has not organized a meeting in the last week.
This doesn't seem to be working, as I am still getting people who have organized a meeting in the past week.

A: You can write a CTE[1] to compute a date interval, take a look:
WITH last_month_minus_thisweek AS(
     SELECT GENERATE_SERIES(CURRENT_DATE - '1 Month'::interval, CURRENT_DATE - '1 week'::INTERVAL, '1 day') AS day
), date_list AS (
     SELECT MIN(day) AS start_date, MAX(day) as end_date FROM last_month_minus_thisweek
)

SELECT * FROM date_list;

To use with your query, put date_list on there FROM clause when adjust your filter, eg:
WITH last_month_minus_thisweek AS(
     SELECT GENERATE_SERIES(CURRENT_DATE - '1 Month'::interval, CURRENT_DATE - '1 week'::INTERVAL, '1 day') AS day
), date_list AS (
     SELECT MIN(day) AS start_date, MAX(day) as end_date FROM last_month_minus_thisweek
)

SELECT  u.id, u.given_name, u.family_name, u.email
FROM users u, last_month_minus_thisweek
JOIN meetings m ON (u.id != m.user_id)
AND m.created_at BETWEEN %s and %s
AND u.state ='active'
AND u.id in (SELECT user_id
             from meetings
           where created_at BETWEEN date_list.start_date and date_list.end_date)
GROUP BY u.id, u.given_name, u.family_name, u.email;

I Hope it helps.
[1] https://www.postgresql.org/docs/current/static/queries-with.html

A: joining on u.id != m.user_id is going to make everyone join on everyone but themselves if their ID is in your subquery. try joining twice and having the week join be null. this will only show users who have never made a meeting in the past week.
SELECT  u.id, u.given_name, u.family_name, u.email
FROM users u
INNER JOIN meetings m_month ON u.id = m_month.user_id
and m_month.created_at > getdate() - interval '1 month'
LEFT JOIN meetings m_week on u.id = m_week.user_id
and m_week.created_at > getdate() - interval '1 week'
where m_week.created_at is null
GROUP BY u.id, u.given_name, u.family_name, u.email


text:
Q: Retrofit2: serializer doesn't get called for @Field-annotated parameters I need to send HTTP PUT request with custom JSON object in one of request's parameter. Here is a problem: when I use it with Retrofit2, my serializer doesn't called.
My object should looks like this:
{
    "ignore":["item1", "item2"]
}

When I call it directly it works well:
final Gson gson = new GsonBuilder()
        .registerTypeAdapter(MyModel.class, new MyModelSerializer())
        .create();
String s = gson.toJson(new MyModel(MyModel.ActionName.ACCEPT, new ArrayList<String>()));
Log.d("tag", s);

I get {"accept":[]}. But when I call it with Retrofit I see in logs this: D/OkHttp: name=abc&items=ru.bartwell.myapp.MyModel%4010a3d8b
I make request with this code:
try {
    MyModel myModel = new MyModel(MyModel.ActionName.ACCEPT, new ArrayList<String>());
    Response<ResultModel> response = getMyApi().getResult(1, "abc", myModel).execute();
    if (response.isSuccessful()) {
        ResultModel resultModel = response.body();
        // handle resultModel
    }
} catch (Exception e) {
    e.printStackTrace();
}

MyApi:
@FormUrlEncoded
@PUT("path/{id}")
Call<ResultModel> getResult(@Path("id") long item, @Field("name") @NonNull String name, @Field("items") @NonNull MyModel myModel);

getMyApi() method:
public static MyApi getMyApi() {
    final Gson gson = new GsonBuilder()
        .registerTypeAdapter(MyModel.class, new MyModelSerializer())
        .create();

    return new Retrofit.Builder()
            .baseUrl(BuildConfig.END_POINT_MY_API)
            .client(MyOkHttpClient.create())
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build()
            .create(MyApi.class);
}

Model:
public class MyModel {
    @NonNull
    private ActionName mActionName;
    @NonNull
    private List<String> mItems = new ArrayList<>();

    public MyModel(@NonNull final ActionName actionName, @NonNull final List<String> items) {
        mActionName = actionName;
        mItems = items;
    }

    @NonNull
    public ActionName getActionName() {
        return mActionName;
    }

    @NonNull
    public List<String> getItems() {
        return mItems;
    }

    public enum ActionName {
        ACCEPT("accept"), DECLINE("decline"), IGNORE("ignore");

        private String mName;

        ActionName(@NonNull final String name) {
            mName = name;
        }

        public String getName() {
            return mName;
        }
    }
}

Serializer:
public class MyModelSerializer implements JsonSerializer<MyModel> {
    @Override
    public JsonElement serialize(@NonNull MyModel src, @NonNull Type typeOfSrc, @NonNull JsonSerializationContext context) {
        JsonObject obj = new JsonObject();
        obj.add(src.getActionName().getName(), new Gson().toJsonTree(src.getItems()));
        return obj;
    }
}

How to fix it?

A: This happens because @Field-annotated parameters are serialized with stringConverter. To override the default behavior, you just need to add another Converter.Factory with the stringConverter method overridden:
.addConverterFactory(new Converter.Factory() {
    @Override
    public Converter<?, String> stringConverter(final Type type, final Annotation[] annotations, final Retrofit retrofit) {
        // Example check for supported classes
        if ( type instanceof Class ) {
            final Class<?> clazz = (Class<?>) type;
            if ( MyModel.class.isAssignableFrom(clazz) ) {
                return (Converter<Object, String>) value -> gson.toJson(value, type);
            }
        }
        return super.stringConverter(type, annotations, retrofit);
    }
})

Then your query parameter string will look like this:

name=abc&items=%7B%22accept%22%3A%5B%5D%7D

(this %7B%22accept%22%3A%5B%5D%7D' is URI-encoded {"accept":[]}).
A few side-notes:

*

*Gson instances are thread-safe and can be created once per the whole application (And this is perfectly fine to pass the single instance to all your components).

*Your MyModelSerializer can be improved: you should not create a Gson instance there since deserializers are bound to the Gson instance configuration, so you have to delegate the serialization via the given context like context.serialize(myModel.mItems, itemsType), where itemsType is new TypeToken<List<String>>() {}.getType().


text:
Q: Handling object between classes I am working with a properties object and I need to use it in a few different classes, the same instant of it. I could just pass it between them I suppose but I feel like that could get out of hand pretty quickly. Is the solution to my problem an interface?
Because I have this method where I load in the properties to the properties object:
public void loadFile(String filepath) throws FileNotFoundException{

        if(!filepath.contains(".properties")){
            System.out.println("Not a properties file.");
            return;
        }
        try{
            prop.load(new FileInputStream(filepath));
        } catch(IOException e){
            throw new FileNotFoundException("File '" + filepath
                    + "' not found.");
        }

        setProperties();
        System.out.println(this.getFtpHost());
    }

and in setProperties() I just set everything, like ftpHost = prop.getProperty("ftp.host"). Aside from getters for all of the properties I set that's all this class is used for (creating the object).
I guess if the solution is an interface could someone explain how I'd put some of this stuff into one conceptually?

A: You can make class like this and put all properties in it.
class PropertiesObject {

   private PropertiesObject instance = null;

   public static PropertiesObject instace() {
       if(instance == null) {
           loadInstance(); // this is done one time
       }
       return instance;
   }
}

A: I think the Singleton pattern is what you should use.


text:
Q: Mongo atlas recommends cloud provider snaphots for backup - Is it effective? MongoDB has deprecated the continuous back up of data. It has recommended using CPS (Cloud provider snapshots). As far as I understood, snapshots isn't really going to be effective compared to continuous backup coz, if system breaks, then we can only be able to restore the data till the previous snapshot which isn't gonna make the database up-to-date or close to it atleast.
Am I missing something here in my understanding?

A: Cloud provider snapshots can be combined with point in time restore to give the recovery point objective you require. With oplog based restores you can get granularity of one second.


text:
Q: jQuery Validate and go to page after successful submit I am working with jquery.validate.min.js script and its working fine as far as validation goes.
My problem is that its posting/submiting to data as it should but I need it to actually go to the success.php page after a successful submit.
Right now it just echos from success.php and shows in my main page.
How is the code below:
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script>
$(document).ready(function() {

$("#form1").validate({

    debug: false,
    rules: {
    name: "required",
    email: {
    required: true,
    email: true,
    }
    },
    messages: {
    name: "Please enter your name.",
    email: "Please enter a valid email address.",
    },
    submitHandler: function(form) {

    $.post('success.php', $("#form1").serialize(), function(data) {
    $('#result').html(data);
    });

    }
});

});

<form id="form1" action="success.php" method="POST">
    <input name="name" type="text" />
    <input name="email" type="text" />
    <input type="submit" value="submit" />
</form>
</script>

How can I get it to go to the posting page after a successful submit?

A: Your code:
submitHandler: function(form) {
    $.post('success.php', $("#form1").serialize(), function(data) {
        $('#result').html(data);
    });
}

"Right now it just echos from success.php and shows in my main page."

Yes, that's exactly how jQuery $.post() is supposed to function.  It's ajax.
Simply remove the entire submitHandler callback function from .validate().  There's really no point in using ajax to submit the form in this case if you just want it to redirect to the default page.  Remove the submitHandler option and it will behave like a standard form with a redirect based on your action attribute.
By default, the plugin will test the validity, and if the form is valid, it will submit like any other standard form and follow your action="success.php".
Working DEMO:  http://jsfiddle.net/yCePj/
$(document).ready(function () {

    $("#form1").validate({
        debug: false,
        rules: {
            name: "required",
            email: {
                required: true,
                email: true,
            }
        },
        messages: {
            name: "Please enter your name.",
            email: "Please enter a valid email address.",
        }
    });

});

A: What about this?
    <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script>
$(document).ready(function() {

$("#form1").validate({

    debug: false,
    rules: {
    name: "required",
    email: {
    required: true,
    email: true,
    }
    },
    messages: {
    name: "Please enter your name.",
    email: "Please enter a valid email address.",
    }
});

});

function SubmitIfValid()
{
    if(!$("#form1").valid()) return false;
    return true;
}

</script>

<form id="form1" action="success.php" method="POST">
    <input name="name" type="text" />
    <input name="email" type="text" />
    <input type="submit" value="submit" onclick="return SubmitIfValid();" />
</form>


text:
Q: pandas filter if name appears in column more than n times this is my dataframe
df = pd.DataFrame({'Col1':['Joe','Bob','Joe','Joe'],
                  'Col2':[55,25,88,80]})

I only want the names of if it appears more than once in 'Col1'
I can do it like this
grouped = df.groupby("Col1")
grouped.filter(lambda x: x["Col1"].count()>2)['Col1'].unique()

However that is ugly looking code
Is there simpler cleaner way?

A: Use value_counts and isin
vc = df.Col1.value_counts() > 2
vc = vc[vc]

df.loc[df.Col1.isin(vc.index)]

A: Here's a NumPy based solution using np.unique -
unq,count = np.unique(df.Col1,return_counts=True)
out = unq[count>n]

Sample run -
In [34]: df
Out[34]:
  Col1  Col2
0  Joe    55
1  Bob    25
2  Joe    88
3  Joe    80
4  Joe    44
5  Bob    24
6  Joe    45

In [35]: unq,count = np.unique(df.Col1,return_counts=True)

In [36]: unq[count>3] # n = 3
Out[36]: array(['Joe'], dtype=object)


text:
Q: How is the scope of pattern variables resolved in java? I was going through the pattern variables in java. While reading the JLS it mentioned several conditions regarding when a pattern variable is introduced.
It mentions -

The analysis relies on the technical term "introduced by", which has the following form:

*

*a pattern variable is introduced by an expression when true

*a pattern variable is introduced by an expression when false

*a pattern variable is introduced by a statement

In 6.3.1 it mentions Scope for Pattern Variables in Expressions under which it states when pattern variables are introduced for &&, ||, !, ?:, etc.
But I feel the explanation is very confusing, can anyone elaborate on &&, ||, !
Example of pattern variables-
Object o = "a";

if(o instanceof String s) {
    System.out.println(s);
}

Where I am confused-
class foo {
    String s, n, p, m;

    void method() {
        Object o = "s";
        if (!(o instanceof Integer s) && o instanceof Integer n) {
            System.out.println(s + " " + n);  // n in scope but s is not in scope
        } else {
            System.out.println(s + " " + n); // neither s nor n is in scope
        }
        System.out.println(s + " " + n); // neither s nor n is in scope (Instance variables s and n over here)

        if (!(o instanceof String p) || o instanceof Integer m) {
            System.out.println(p + " " + m); // neither p nor m is in scope (Instance variables p and m over here)
        } else {
            System.out.println(p + " " + m); // p in scope but m is not in scope
        }

    }

}

I don't get how it resolute the scope of a variable at compile time. Also, why isn't s in the scope of else block and why is p in the scope of else block. I don't understand how pattern variable scoping works with a mix of &&,|| and !.

Please give simple as well as complicated examples.
Please try to explain it with simple and difficult examples, would really be helpful.

A: Lets just consider this:
if (!(o instanceof Integer s)) {
    System.out.println(s);

It says:

When o is an Integer bind it to s.
Then if o is not an Integer, print s.

Intuitively: when o is not an Integer, we didn't bind it to s, so s is meaningless.
If you look at a more complicated example, it will most likely have this kind of logic at its root.
The section of the JLS that specifies this is ... complicated.  But I don't think you need to understand all of that complexity to use pattern variables.  Just use the intuitive meaning behind these two sentences from the JLS 6.3:

"The scope of a pattern variable declaration (that is, a local variable declared by a pattern) is the part of the program that might be executed after the matching of a value against the pattern has succeeded. It is determined by considering the program points where the pattern variable is definitely matched in a region beginning with the pattern that declares the pattern variable."

So in our simple example, the System.out.println(s) is NOT part of the program that would be executed if (o instanceof Integer s) succeeded.  The ! means that the then branch of this if is executed when (o instanceof Integer s) does not succeed.


text:
Q: Virtual work - Tension in a string I am confused about the way Tension or Thrust is used in equation of virtual work. I mean whether to use $ T\cdot dr$ or  $-T\cdot dr$ (work done by tension). For instance in the below case :

A string of length a forms the shorter diagonal of a rhombus of four uniform rods each of length b and weight W which are hinged together. If the uppermost rod be supported in a horizontal position , prove that the tension of the string is
  $$ \frac{2W(2b^2 - a^2 )}{b\sqrt{4b^2-a^2}}. $$

My Approach:
Assuming T is tension in string BD.
$$ BD = 2b\cos\theta$$
As $ \theta $ increases, the length of the string decreases or movement of string is in the direction of tension, hence the work done by tension should be postive. Hence the equation of principle work would be $$ T\delta(2b \cos\theta) + 4W \delta(b \sin\theta \cos\theta) = 0 $$ but the solution in book says
$$ -T\delta(2b \cos\theta) + 4W \delta(b \sin\theta \cos\theta) = 0 $$

A: Work done by Tension in virtual work equation should be simplified in the following way.
If the length of string is increasing (decreasing) -> 'dr' is  positive(negative).
If the Change in length is in the direction (opposite) of force -> Tension is postive (negative).


text:
Q: The code seems correct but my files aren't getting deleted I heard that python can make life easier, I wanted to remove duplicates in folderA by comparing folderB with folderA, so I decided to download python and try coding with python. My code seems correct, however, my files are failing to delete, what's wrong with it?
I tried unlink but doesn't work.
import os

with open(r"C:\pathto\output.txt", "w") as a:
    for path, subdirs, files in os.walk(r'C:\pathto\directoryb'):
       for filename in files:
         #f = os.path.join(path, filename)
         #a.write(str(f) + os.linesep)
         a.write(str(filename) + '\n')

textFile = open(r'C:\output.txt', 'r')

line = textFile.readline()
while line:
 target = str(line)
 todelete = 'C:\directorya' + target
 if (os.path.exists(todelete)):
  os.remove(todelete)
 else:
  print("failed")
 line = textFile.readline()

textFile.close()

I want my files deleted, basically folderA contains some files in folderB, and I'm trying to delete it.

A: The problem is that the place where you're deleting the file isn't actually deleting a file - it's deleting a variable that contains the file's information.
 todelete = 'C:\directorya' + target
 if (os.path.exists(todelete)):
  os.remove(todelete) # this is deleting todelete, but doesn't get rid of the file!

I had a similar problem in a program I've started on but with a list, and in the end I had to use this kind of format:
lst.remove(lst[val1][val2][val3]) # as opposed to something cleaner-looking, like 'lst.remove(var_to_del)'

It's a pain, but I hope that clarifies the issue! You'll have to go to the file without giving it a variable name.


text:
Q: How to copy items from one list box to another list box? In my web application , I am having 2 List box as "MenuBox" and "UpdatedBox". The MenuBox items were populated from Database using Dataset. Now If I select a Item in MenuBox and Click "Move" button, the selected Item has to be copied to "UpdatedBox".... Can any one tell me how to achieve this ?

A: ListBox SelectionMode can be set single or multiple, in both cases below code will work
int[] selection = MenuBox.GetSelectedIndices();
while (selection.Length >0)
{
    UpdatedBox.Items.Add(MenuBox.Items[selection[0]].ToString());
    MenuBox.Items.RemoveAt(selection[0]);
    selection = MenuBox.GetSelectedIndices();
}

A: ListBox2.Items.Add(ListBox1.SelectedItem);

A: Try this
 while(ListBox1.Items.Count!=0)
 {
    for(int i=0;i<ListBox1.Items.Count;i++)
    {
        ListBox2.Items.Add(ListBox1.Items[i]);
        ListBox1.Items.Remove(ListBox1.Items[i]);
    }
 }

A: Hey Try this one this is tested code.
if (ListBox1.SelectedIndex > -1)
        {
            ListBox2.Items.Add(ListBox1.SelectedItem);
            ListBox1.Items.RemoveAt(ListBox1.SelectedIndex);
            ListBox2.ClearSelection();
        }

Hope it helps you

A: You can do something like this.
UpdatedBox.Items.Add(MenuBox.SelectedItem);


text:
Q: How can i add multiple images using php powerpoint library? Can u pls tell me how to bind multiple images in powerpoint using php powerpoint library? In the below code i used foreach loop to add multiple images in powerpoint but only one image is adding so pls help me.
<?php
require_once("db_config.php");
set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/');
include 'PHPPowerPoint.php';
include 'PHPPowerPoint/IOFactory.php';
?>

Welcome <?php echo $_SESSION['user_name'];?>

Logout

<?php
echo "
";
echo "<form method='post' action=''>";
echo "

ID
Firstname
Lastname
UserName

";
$result = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($result))
{
echo "
";
echo "<input type='checkbox' name='user_id[]' value='".$row['user_id']."' />  	";
echo "" . $row['user_id'] . "	";
echo "" . $row['first_name'] . "	";
echo "" . $row['last_name'] . "	";
echo "" . $row['user_name'] . "	";
echo "
";
}
echo "

";
echo "<input type='submit' name='submit' value='Export PPT' />";
echo "</form>
";
?>

<?php
if(isset($_POST['submit']) && isset($_POST['user_id'])){
$user_id = $_POST['user_id'];

foreach($user_id as $selected){
echo $selected."
";

$result = mysql_query("SELECT * FROM users WHERE user_id ='".$selected."'");
$row = mysql_fetch_array($result);

$img = '';

$objPHPPowerPoint = new PHPPowerPoint();
// block sets slide logo.
$currentSlide = $objPHPPowerPoint->getActiveSlide();
$shape = $currentSlide->createDrawingShape();
$shape->setPath('images/'.$row["image_name"]);
$shape->setWidth(640);
$shape->setHeight(480);
$shape->setOffsetX(10);
$shape->setOffsetY(10);

// block sets text for first slide.
$shape = $currentSlide->createRichTextShape();
$shape->setHeight(700);
$shape->setWidth(600);
$shape->setOffsetX(10);
$shape->setOffsetY(500);
$shape->getAlignment()->setHorizontal(        PHPPowerPoint_Style_Alignment::HORIZONTAL_CENTER );
$textRun = $shape->createTextRun('FirstName:'.$row["first_name"].'   Lastname:'.$row["last_name"].' UserName:'.$row["user_name"]);
$textRun->getFont()->setBold(true);
$textRun->getFont()->setSize(30);
$textRun->getFont()->setColor( new PHPPowerPoint_Style_Color( '#FFFF' ) );

// block sets text for first slide ends.

$filename = str_replace('.php', '.pptx', __FILE__);
$newname = "PresentationReport-" . date('Y-m-d-H-i-s') . ".pptx";
$objWriter = PHPPowerPoint_IOFactory::createWriter($objPHPPowerPoint, 'PowerPoint2007');
$objWriter->save(str_replace('.php', '.pptx', __FILE__));

// block to download file.
header("Pragma: no-cache");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename=" . $newname);
ob_clean();
flush();
readfile($filename);
exit();
}
}
else
{

echo "
Please choose the user
";
exit;
}
?>

A: How can i add multiple images using php powerpoint library?
Two troubles can be indentified in your snippet:
1 - You're calling "new Powerpoint" to each element in foreach, and due this
you always override the previous slide.
2 - You're positioning your shapes in the same x/y offset:
$shape->setOffsetX(10);
$shape->setOffsetY(10);

So in the foreach all shapes will be stacked.
To a functional solution you'll need to mount a valid algorithm like:
I'll have 4 photos by slide for example so:
$resultsFromDataBase = $resultsFromDataBase;

// Array chunk to create a "logic" 4 photos ... jump to the new slide
$resultsBySlide = array_chunk($resultsFromDataBase, 4);

// Each photo needs your independent X offset
// Note the fake values, you need to calculate them
$positionsByIndex = [
    0 => 10,
    1 => 20,
    2 => 30,
    3 => 40
];

foreach ($resultsBySlide as $i => $rows) {
    // 4 photos -> Jump the slide and create another one
    $ppt->createSlide();

    // SlideCount -1 gets your current index
    $slideIndex = $ppt->getSlideCount()-1;
    $currentSlide = $objPHPPowerPoint->getActiveSlide();

    foreach ($rows as $position => $row) {
        $shape = $currentSlide->createDrawingShape();
        $shape->setPath('images/'.$row["image_name"]);
        $shape->setWidth(640);
        $shape->setHeight(480);
        $shape->setOffsetX($positionsByIndex[$position]); // Here the point
        $shape->setOffsetY(10);
    }
}

And the last point but not less important: Don't use mysql_* in your project
use: PDO or mysqli_* instead


text:
Q: Deployment Failed from Github via Code Pipeline I am trying to deploy new things on our server.
It's failing every time i don't know why, every time i get:
[Instance: i-0767cd899da6be838] Command failed on instance.
Return code: 2 Output: (TRUNCATED)... see <https://getcomposer.org/doc/04-schema.md#minimum-stability> for more details. -
It's a private package and you forgot to add a custom repository to find it Read <https://getcomposer.org/doc/articles/troubleshooting.md> for further common problems. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/10_composer_install.sh failed.
For more detail, check /var/log/eb-activity.log using console or EB CLI.

Code Pipeline raise this message:
Deployment completed, but with errors:
During an aborted deployment, some instances may have deployed the new application version.
To ensure all instances are running the same version, re-deploy the appropriate application version.
Failed to deploy application.
Unsuccessful command execution on instance id(s) 'i-0767cd899da6be838'.
Aborting the operation.
[Instance: i-0767cd899da6be838] Command failed on instance.
Return code: 2 Output: (TRUNCATED)... see <https://getcomposer.org/doc/04-schema.md#minimum-stability> for more details. - It's a private package and you forgot to add a custom repository to find it Read <https://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.
Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/10_composer_install.sh failed.
For more detail, check /var/log/eb-activity.log using console or EB CLI.

I checked /var/log/eb-activity.log and /var/log/httpd/error_log in elastic beans but they have nothing.
This is composer.json may help to track issue:
{
    "require": {
        "php": "7.2",
        "algolia/algoliasearch-client-php": "^3.1",
        "authy/php": "3.0.5",
        "barryvdh/laravel-cors": "^0.11.3",
        "barryvdh/laravel-translation-manager": "^0.5.3",
        "berkayk/onesignal-laravel": "^1.0",
        "cviebrock/eloquent-sluggable": "^4.6",
        "darkaonline/l5-swagger": "5.7.*",
        "doctrine/dbal": "2.10.1",
        "dusterio/laravel-aws-worker": "^0.1.26",
        "fideloper/proxy": "^4.0",
        "google/apiclient": "^2.4",
        "guzzlehttp/guzzle": "^6.3",
        "intervention/image": "^2.4",
        "jenssegers/agent": "^2.6",
        "laravel/framework": "5.7.*",
        "laravel/scout": "^7.0",
        "laravel/slack-notification-channel": "v1.0.3",
        "laravel/socialite": "^4.4",
        "laravel/tinker": "^1.0",
        "laravelcollective/html": "^5.7",
        "league/flysystem-aws-s3-v3": "^1.0",
        "maatwebsite/excel": "3.1.25",
        "pusher/pusher-php-server": "^4.1",
        "segmentio/analytics-php": "^1.7",
        "sentry/sentry-laravel": "1.6.1",
        "spatie/laravel-activitylog": "v2.8.4",
        "spatie/laravel-medialibrary": "^6.19.0"
    },
    "minimum-stability": "dev"
}

Any help ?

A: I got my problem solved.
At first i tried to apply solutions at this post but it didn't solve my problem.
The only thing that solved my problem was by upgrading my composer version.
So i upgraded my composer from 1.8.0 to 2.1.3 by:
composer self-update 2.1.3

I had to do this in the elastic beanstalk configuration file:
commands:
  01updateComposer:
    command: export COMPOSER_HOME=/root && /usr/bin/composer.phar self-update 2.1.3

Hope this helps you guys one day.


text:
Q: loadrequest cannot find cache entry that I created with NSURLCache I can create a cache entry by:
[[NSURLCache sharedURLCache] storeCachedResponse:cachedURLresponse forRequest:request];

for the URL http://www.punkoffice.com/hello.html
If I run this straight after I see that my cache entry exists
NSLog(@"cache = %@",[[NSURLCache sharedURLCache] cachedResponseForRequest:request]);

and i can see it in the SQLite database file.
However, when I do a loadrequest with the exact same request like so:
[self.webView loadRequest:request]

The cache entry for that request isn't found and a new one is created.  It ends up over-writing the cache entry I put in there previously.
How do I get loadRequest to see the cache entry I stored with storeCachedResponse?
(edit)
Here is the full code I'm using to create the cache entry.  I can tell this bit works 'cos it exists in the cache database and I can retrieve it from cachedReponseForRequest
NSString *strURL = @"http://www.punkoffice.com/hello.html";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:strURL]];
NSString *strData = @"Some other content";
NSData *dataContent = [strData dataUsingEncoding:NSUTF8StringEncoding];

NSURLResponse *response = [[NSURLResponse alloc] initWithURL:[NSURL URLWithString:strURL] MIMEType:@"text/html" expectedContentLength:[dataContent length] textEncodingName:nil];
NSCachedURLResponse *cachedURLresponse = [[NSCachedURLResponse alloc] initWithResponse:response data:dataContent];

I have also tried adding headers like so:
NSDictionary *headers = @{@"Cache-Control":@"max-age=3600"};
NSHTTPURLResponse* httpResponse = [[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:strURL] statusCode:200 HTTPVersion:@"HTTP/1.1" headerFields:headers];
NSCachedURLResponse *cachedURLresponse = [[NSCachedURLResponse alloc] initWithResponse:httpResponse data:dataContent];

A: You need to specify the cachePolicy when creating the NSURLRequest.
+ (id)requestWithURL:(NSURL *)theURL cachePolicy:(NSURLRequestCachePolicy)cachePolicy timeoutInterval:(NSTimeInterval)timeoutInterval

Value of the cachePolicy should be NSURLRequestReturnCacheDataElseLoad.

NSURLRequestReturnCacheDataElseLoad
Specifies that the existing cached
  data should be used to satisfy the request, regardless of its age or
  expiration date. If there is no existing data in the cache
  corresponding the request, the data is loaded from the originating
  source.

In order to take advantage of NSURLCache, a shared URL cache must be initialized and set.
  NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024
                                                       diskCapacity:20 * 1024 * 1024
                                                           diskPath:nil];
  [NSURLCache setSharedURLCache:URLCache];

You should also make sure the response contains the Cache-Control HTTP header. This header must be present in the response from the server to enable HTTP caching by a client.

A: I had the same problem. To resolve this, I have done it like this.
    NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
    if (cachedResponse) {
        [myWebView loadData:cachedResponse.data MIMEType:cachedResponse.response.MIMEType textEncodingName:cachedResponse.response.textEncodingName baseURL:request.URL];
    }
    else{
        [myWebView loadRequest:request];
    }

Not sure, but it seems to me that loadRequest method of UIWebView always ignores the cachePolicy and always tries connecting to the server at request URL instead looking into cache.


text:
Q: Spice Simulation from Electric on OSX I'm using Electric as design system. I want to simulate in LTSPICE the designed circuit.
I've linked LT Spice and Electric (cmosedu) as the tutorial show (http://cmosedu.com/videos/electric/tutorial1/electric_tutorial_1.htm), but
when I try to simulate from Electric, it doesn't open LT Spice.
Any solution?

A: This is what I did. It works.
Setup parameters in electric-9.07.jar:
Run program: /Applications/LTspice.app/Contents/MacOS/script.sh
With args: ${FILENAME_NO_EXT} -r ${FILENAME_NO_EXT}.raw -o ${FILENAME_NO_EXT}.out

!!IMPORTANT!!
    First argument isn't "-i ${FILENAME}". IT'S "${FILENAME_NO_EXT}".
    I create "ELECTRIC" folder in Desktop and I use it for saving my *.spi files.
    To allow the script to work, you must insert your libraries inside this folder on desktop (ELECTRIC).
SCRIPT
        You need to create /Applications/LTspice.app/Contents/MacOS/script.sh
######START HERE######
    #!/bin/bash

                                # Get argument from electric

    args=("$@")

                                # Create *.net file for LTspice

    cd  ~/Desktop/ELECTRIC/

    cp ${args[0]}.spi ${args[0]}.net

                                # Launch LTspice and pass it parameters.

    cd /Applications/LTspice.app/Contents/MacOS/

    ./LTSpice ~/Desktop/ELECTRIC/${args[0]}.net ${args[1]} ~/Desktop/ELECTRIC/${args[2]} ${args[3]} ~/Desktop/ELECTRIC/${args[4]}
######END HERE######

It needs execution privileges:
    sudo chmod +x /Applications/LTspice.app/Contents/MacOS/script.sh
Use Electric as tutorial says (http://cmosedu.com/videos/electric/tutorial1/electric_tutorial_1.htm).
It will open a small window with a netlist.
Click on run button to see the simulation.
To close LTspice, you must exit from it.
INFO:
    If LTspice says you that you haven't its latest version, close the window and go on.


text:
Q: Ebay Daily Deals API I am trying to implement ebay's daily deals api.
[http://deals.ebay.com/feeds/json]
into my angular web application. The only problem is when I go to this url the json comes back is this:
   ({ebaydailydeals:{"items": [
 {
  "endtime": "1433170740000",
  "convertedcurrentprice": "329.99",
  "smallpictureurl": "http://i.ebayimg.com/00/s/NTAwWDUwMA==/z/1kMAAOSwBLlVZc9d/$_1.JPG",
  "location": "Elizabeth, NJ",
  "pricedisplay": "MSRP",
  "itemid": "331566158178",
  "savingsrate": "40%",
  "title": "Acer Aspire E5 15.6\" Notebook - I5-4210U, 4GB Ram, 500GB HDD, Windows 8.1",
  "msrp": "549.99",
  "autopay": true,
  "description": "N/A",
  "primarycategoryid": "177",
  "quantity": 722,
  "picture175url": "http://i.ebayimg.com/00/s/NTAwWDUwMA==/z/1kMAAOSwBLlVZc9d/$_1.JPG",
  "dealurl": "http://deals.ebay.com/5002063567",
  "pictureurl": "http://i.ebayimg.com/00/s/NTAwWDUwMA==/z/1kMAAOSwBLlVZc9d/$_1.JPG",
  "primarycategoryname": "Computers/Tablets & Networking:Laptops & Netbooks:PC Laptops & Netbooks",
  "quantitysold": 88
},

If I copy the json into a formatter its saying the json is not valid. Before I spend any more time bulldogging this thing I am looking for some validation that this is doable or not.

A: It seems like you need to make a request to the following URL:
http://api.epn.ebay.com/deals/v1/country/us/feed/json?feedType=json
You can customize this as you please, here's some helpful documentation:
http://www.helios825.org/eDD.php


text:
Q: Liferay 7 Como solucionar NoClassDefFoundError BaseBodyTagSupport en portlet Como soluciono error que arroja al entrar modo edición en un portlet implementado en liferay 7.
Estoy importando las librerías que muestro en el código, pero al parecer revienta en <%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet"%>.
Muestro código del Archivo edit.jsp el cual ya esta configurado en el web.xml.
<%@ page import="javax.portlet.RenderRequest"%>
<%@ page import="javax.portlet.RenderResponse"%>
<%@ page import="javax.portlet.PortletPreferences"%>
<%@ page import="javax.portlet.PortletURL"%>
<%@ page import="net.grupobit.Guardar"%>
<%@ page import="com.liferay.portal.kernel.servlet.*"%>
<%@ page import="com.liferay.taglib.BaseBodyTagSupport"%>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet"%>
<%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt" %>

<portlet:defineObjects />

<portlet:actionURL var="actionURL" />

El error que arroja el log de catalina.out es el siguiente:

2021-09-03 16:56:03.612 ERROR [http-nio-8080-exec-68][PortletRequestDispatcherImpl:304] Unable to dispatch request: java.lang.NoClassDefFoundError:
com/liferay/portal/kernel/servlet/taglib/BaseBodyTagSupport
2021-09-03 16:56:03.613 ERROR [http-nio-8080-exec-68][PortletServlet:119]  javax.portlet.PortletException: javax.servlet.ServletException: java.lang.NoClassDefFoundError: com/liferay/portal/kernel/servlet/taglib/BaseBodyTagSupport
javax.portlet.PortletException: javax.servlet.ServletException: java.lang.NoClassDefFoundError: com/liferay/portal/kernel/servlet/taglib/BaseBodyTagSupport
at com.liferay.portlet.internal.PortletRequestDispatcherImpl.dispatch(PortletRequestDispatcherImpl.java:307)
at com.liferay.portlet.internal.PortletRequestDispatcherImpl.include(PortletRequestDispatcherImpl.java:131)
Caused by: javax.servlet.ServletException: java.lang.NoClassDefFoundError: com/liferay/portal/kernel/servlet/taglib/BaseBodyTagSupport

Gracias por la ayuda.

A: Lo solucioné actualizando las librerías util*.jar de mi proyecto.


text:
Q: wp_head() gives me some weird CSS I was trying to enqueue my stylesheets but it didn't work. Turns out I had forgotten to include wp_head() inside my <head> tag. So I did and then my stylesheets where loading fine.
The problem is that a get a CSS value that is not from my stylesheet. And I can also not override it from my stylesheet since it appears to be loading after mine. It started to come up as soon as I included wp_head(). If I delete wp_head() everything looks fine.
This is the weird CSS value that I get:
media="screen"
html {
    margin-top: 32px !important;
}

As you can understand this is a problem since I know have a 32px margin on top of my websites. And as I stated before, I have no idea where this value comes from. I use no plugins and the only stylesheet enqueued is my style.css and this value is not from that file. In the "console" it says that the value comes from "index" on line 334. But I got nothing there, so it must be something from WP?
Can anyone explain to me where this value comes from? And how do I change it?

A: The fact that
<style type="text/css" media="screen">
    html { margin-top: 32px !important; }
    * html body { margin-top: 32px !important; }
    @media screen and ( max-width: 782px ) {
        html { margin-top: 46px !important; }
        * html body { margin-top: 46px !important; }
    }
</style>

is added for Admin bar by wp-core at the top of the site.
The trick below will remove those CSS out from yout HTML output Just add this code to your functions.php
add_action('get_header', 'my_filter_head');

function my_filter_head() {
   remove_action('wp_head', '_admin_bar_bump_cb');
}

UPDATE
Answering question-starter request.
1) Admin Bar is showing by default if you're logged in. It wrapper has id="wpadminbar" in your HTML responce.
It also enqueue /wp-includes/js/admin-bar.min.js script and add "Support Script" at the bottom of page.
2) Admin Bar can be disabled when you're viewing site for specified users at
Users -> User_Record -> "Show Toolbar when viewing site" checkbox.
Additionally it can be disabled in your functions.php (using show_admin_bar filter as described here How do I remove the admin bar (styling) from frontend only?)
3) In WP source code _admin_bar_bump_cb() looks like this. It can be found at wp-includes/admin-bar.php
function _admin_bar_bump_cb() { ?>
 <style type="text/css" media="screen">
     html { margin-top: 32px !important; }
     * html body { margin-top: 32px !important; }
     @media screen and ( max-width: 782px ) {
         html { margin-top: 46px !important; }
         * html body { margin-top: 46px !important; }
     }
 </style>
 <?php
}

This function is used to be added as action to wp_head inside wp-includes/class-wp-admin-bar.php in this way:
if ( empty($header_callback) )
   $header_callback = '_admin_bar_bump_cb';

   add_action('wp_head', $header_callback);

By removing _admin_bar_bump_cb from action queue you cancel those styles printing


text:
Q: regex won't match as expected using beautifulsoup I'm trying to use a regex to match tags with class="calendar-days-list2" but not  class="calendar-days-list2 prev-next-month". I loaded up a sample piece of HTML with tags containing both options.
When I search the sample HTML using re.findall(), the regex matches as I would like. When I use that sample regex in beautifulsoup, it returns both the wanted and the unwanted class. I don't understand why this is, any thoughts? Thanks!
html = '''
       7

              Special Exhibitions
              10:00 AM

       '''

soup = BeautifulSoup(html)
# WORKS
print re.findall(r"(calendar\-days\-list2)(?!\sprev\-next\-month)",html), "\n\n"

regex = re.compile(r"(calendar\-days\-list2)(?!\sprev\-next\-month)")
# DOESN'T WORK
tds = soup.find_all("td", {"class": regex})
print tds

output:
# re.findall
['calendar-days-list2']

# soup.find_all
[
7

Special Exhibitions
        10:00 AM

	, 	]

`

A: regex = re.compile(r"(calendar\-days\-list2)(?!\sprev\-next\-month)")
# DOESN'T WORK
tds = soup.find_all("td", {"class": regex})

This is not working since the regular expression is applied to every class value separately and not to the entire attribute value. This is because class is a special multi-valued attribute. There were several related to the problem posts recently:

*

*BeautifulSoup returns empty list when searching by compound class names

*Include multiple class names in findAll in BeautifulSoup4

*Disable special "class" attribute handling
Probably the simplest approach is to go with a CSS selector to make a full class attribute match:
soup.select('[class="calendar-days-list2"]')


text:
Q: compare month in a range of months and get next higher month in oracle Rephrasing, I have a string in a column having months like '3-6-9-12'. I have to  get the next processing month by comparing the month from the string and extract(month from sysdate).
e.g in may the month is 5 ,So I want 6 as the next month from the string.
 in july the month is 7 ,SO I should get 9 as next month.I want to do it in an inline query if possible.
I was trying with this query to get the next month -
select instr(x,extract(month from sysdate))+1 from
   (select listagg(to_number(regexp_substr((extract(month from sysdate)||'-3-6-2-12'), '[^-]+', 1 ,level)),'-') within group (order by to_number(regexp_substr((extract(month from sysdate)||'-3-6-2-12'), '[^-]+', 1 ,level)))x from dual
          connect by regexp_substr((extract(month from sysdate)||'-3-6-2-12'), '[^-]+', 1 ,level) is not null order by to_number(x) )
Please help if there is any other better approach to find the next month in sql.

A: You can just do a mapping of month and quater and then select the quater
     with date_mapping as(select 1 month,3 quater from dual union all
                         select 2 month,3 quater from dual union all
                         select 3 month,3 quater from dual union all
                         select 4 month,6 quater from dual union all
                         select 5 month,6 quater from dual union all
                         select 6 month,6 quater from dual union all
                         select 7 month,9 quater from dual union all
                         select 8 month,9 quater from dual union all
                         select 9 month,9 quater from dual union all
                         select 10 month,12 quater from dual union all
                         select 11 month,12 quater from dual union all
                         select 12 month,12 quater from dual),
     data as (select   date '2020-12-01' date1 from dual)
     select ds.quater from data dd ,date_mapping ds
     where extract (month from dd.date1)=ds.month

IF your Quater is not fixed you can use the below
WITH quaters
 AS (SELECT to_number(Regexp_substr(quaters, '[^-]+', 1, LEVEL)) quater
     FROM   (SELECT ( '1-4-7-10' ) AS quaters
             FROM   dual)
     CONNECT BY LEVEL <= Regexp_count(quaters, '[^-]+')),
 min_max_quater
 AS (SELECT Max(quater) max_quater,
            Min(quater) min_quater
     FROM   quaters),
 date_mapping
 AS (SELECT lvl         month,
            Min(quater) quater
     FROM   dual,
            quaters
            cross join (SELECT LEVEL lvl
                        FROM   dual
                        CONNECT BY LEVEL < = 12)
     WHERE  lvl <= quater
     and lvl <> quater
     GROUP  BY lvl
     UNION ALL
     SELECT LEVEL month,
            min_quater
     FROM   min_max_quater
     WHERE  LEVEL > max_quater
     CONNECT BY LEVEL <= 12
     UNION ALL
     SELECT max_quater,
            min_quater
            FROM
        min_max_quater
     )
  SELECT ds.quater
   FROM   dual dd,
   date_mapping ds
  WHERE  Extract (month FROM sysdate) = ds.month


text:
Q: comparing files to find difference between them in ruby returns wrong result. I'm trying to compare two text file and write their difference into another text file. but im getting wrong differences. that is, name which is existing in both the files are also coming under difference file.
Im using this code, which i got from stackoverflow.
#new file
f1 = IO.readlines("file1.txt").map(&:chomp)
#old file
f2 = IO.readlines("file2.txt").map(&:chomp)

File.open("result.txt","w"){ |f| f.write("NEED TO ADD:\n")}
File.open("result.txt","a"){ |f| f.write((f1-f2).join("\n")) }
File.open("result.txt","a"){ |f| f.write("--------------------\n")}
File.open("result.txt","a"){ |f| f.write("NEED TO REMOVE:\n")}
File.open("result.txt","a"){ |f| f.write((f2-f1).join("\n")) }

and i have the following content in my file1.txt and file2.txt
file1.txt contains:
colors
channel [v]
star plus
star utsav
sony
life ok
zee salaam
zee tv
nepal one
zee anmol
flowers tv

file2.txt contains:
colors
sony entertainment
star plus
star utsav
zee tv
life ok
dd national
etc bollywood
zee anmol

and my result.txt file contains:
NEED TO ADD:
colors
channel [v]
star plus
star utsav
sony
life ok
zee salaam
zee tv
nepal one
zee anmol
flowers tv
---------------------------------------------------
NEED TO REMOVE:
colors
sony entertainment
star plus
star utsav
zee tv
life ok
dd national
etc bollywood
zee anmol

i hope you can understand my problem from the result file. help me with a direct answer as im a newbie.

A: It looks like you have trailing whitespace in file1.txt, which causes the differences.
E.g. "colors  " is not equal to "colors", causing them to be listed in different sections.
If you want to strip away all leading and trailing whitespace before comparing lines, you can use .strip:
f1 = IO.readlines("file1.txt").map(&:strip)
f2 = IO.readlines("file2.txt").map(&:strip)

That should produce the result you expected, even if you accidentally have some trailing whitespace.


text:
Q: BERT embeddings are different in batches, compared to single input I'm using BERT embeddings in an SVM. For computational efficiency, I'm batching my data, feeding them into BERT to get the embeddings from the last 4 hidden layers, and then using these embeddings in the SVM.
However, I find that my embeddings are different depending on if I feed in text into BERT as a single input, or multiple sentences at a time. Should that be the case? I would have thought that the embeddings would be independent of the other inputs?
Eg, if I feed into BERT 3 sentences
text = ["Huang began to row at the age of 12.", "The ship is colored blue", "Who are you?", "True"], the embedding is different for each entry than if I had fed each one into the model separately. E.g. text=["Huang began to row at the age of 12."]


text:
Q: java.sql.SQLException: Invalid Oracle URL specified Error I am trying to connect Oracle Database with JDBC Driver. I am getting java.sql.SQLException: Invalid Oracle URL specified error. Please help me in resolving the issue.
package test_connection;

import java.sql.*;

public class TestConnection {
    public static void main(String[] args) {
        // TODO code application logic here

        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            System.out.println("Driver loaded successfully ");
            Connection con = DriverManager.getConnection("jdbc:oracle:thin@:localhost:1521:XE", username, password);
            System.out.println("Connection established successfully ");

            con.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Here is the stacktrace of the error.
run:
Driver loaded successfully
java.sql.SQLException: Invalid Oracle URL specified
BUILD SUCCESSFUL (total time: 0 seconds)

A: It is a typo, you misplaced the @:
"jdbc:oracle:thin@:localhost:1521:XE"

It should be:
"jdbc:oracle:thin:@localhost:1521:XE",

A: You can get some samples from github. Example., DataSourceSample


text:
Q: given a polynomial how can you derive its bezier representation I am developing an application that renders ECG rhythms that need to be animatable in response to user input. That part is not relevant to this site3, however I am starting with hand drawn rhythms, determining their polynomial representation and need to determine a bezier representation of those polynomials, which is the reason I am asking the question here. ( I can draw the rhythms using software like adobe illustrator, however the representation is not predictable and in order to animate them the bezier representation has to fit a certain format, so illustrator and the like are not an option, only drawing them by hand is).
So the question I need help with is, given a curve how can you derive the control points of its bezier representation? for example, if I wished to derive the bezier representation of a parabola:
$$F(x) = x^2, \:\:  \{-2 \leq x \geq 2\}$$
with a parameterization such as:
$$F(t) = (4t -2)^2, \:\: \{0 \leq t \geq 1\} $$
what is method of obtaining the bezier coefficients for $F(t)$?

A: The equation of a Bézier curve is $$P(t) = \sum_{k=0}^n \binom{n}{k} (1-t)^{n-k} t^k P_k = \sum_{k=0}^n \binom{n}{k} \sum_{j=0}^{n-k} \binom{n-k}{j} (-t)^j t^k P_k $$
So if you have an expression for $P(t)$ in the form $$P(t) = \sum_{i=0}^n t^i A_i$$ you can equate coefficients of powers of $t$ to get simultaneous linear equations which you can solve for the $P_k$.

Your example is a quadratic, so $n = 2$ and $$\begin{eqnarray}
P(t) &=& \binom{2}{0}(1-t)^2 t^0 P_0 + \binom{2}{1}(1-t)^1 t^1 P_1 + \binom{2}{2}(1-t)^0 t^2 P_2 \\
&=& (1-2t+t^2) P_0 + (2t-2t^2) P_1 + t^2 P_2 \\
&=& t^2 (P_0 - 2 P_1 + P_2) + t(-2 P_0 + 2 P_1) + P_0 \\
\end{eqnarray}$$
If we equate coefficients with the general quadratic $P(t) = t^2 A_2 + t A_1 + A_0$ we get
$$\begin{eqnarray}
P_0& & &=& A_0 \\
-2P_0& + 2P_1& &=& A_1 \\
P_0& - 2P_1& + P_2 &=& A_2 \\
\end{eqnarray}$$
which we can solve by Gaussian elimination without pivoting to get
$$\begin{eqnarray}
P_0 &=& A_0 \\
P_1 &=& A_0 + \tfrac12 A_1 \\
P_2 &=& A_0 + A_1 + A_2 \\
\end{eqnarray}$$
This can now be applied separately in the $x$- and $y$-coordinates: $$\begin{eqnarray}
x(t) &=& 4t-2 & \implies & x_0 = -2, & x_1 = 0, & x_2 = 2 \\
y(t) &=& (4t-2)^2 & \implies & y_0 = 4, & y_1 = -4, & y_2 = 4 \\
\end{eqnarray}$$
So the Bézier control points are $(-2, 4), (0, -4), (2, 4)$.


text:
Q: How can I read an value or deserialize this JSON-structure in Javascript? from an associative and multidimensional Array in PHP i get this object by json_encode():
{"2047":
  {"f1a":
   {"val":["7","7","6","1","6","6"],
    "cnt":6,
    "sum":33,
    "avg":5.5
   },
  {"f2a":
   {"val":["7","6","5","7","5","3","5","7","6","7"],
    "cnt":10,
    "sum":58,
    "avg":5.8
   },
  "2048": ...
}

and i want to read the value of avg of f2a and 2047.

A:   var myJson = {
  2047: {
    f1a: {
      val: [7, 7, 6, 1, 6, 6],
      cnt: 6,
      sum: 33,
      avg: 5.5
    },
      f2a: {
        val: [7, 6, 5, 7, 5, 3, 5, 7, 6, 7],
        cnt: 10,
        sum: 58,
        avg: 5.8
      }
  }
};
console.log(myJson['2047']['f1a']['avg']);

A: You can deserialize your JSON with JSON.parse (serialized)

A: You can use var obj = JSON.parse(str), then traverse the object using obj['2047']['f1a']


text:
Q: Customize closing Tag using Dart XML -        builder.element(
              'mxCell'
              ' '
              'id= "${myId}"'
              ' '
              'value=""'
              ' '
              'style="outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=${_myObjects[i]};fillColor=#F58534;gradientColor=none;"'
              ' '
              'vertex="1"'
              ' '
              'parent="1"', nest: () {
            builder.element('mxGeometry'
                ' '
                'x= "${_myObjects[i + 1]}"'
                ' '
                'y= "${_myObjects[i + 2]}"'
                ' '
                'width= "${_myObjects[i + 3]}"'
                ' '
                'height= "${_myObjects[i + 4]}"'
                ' '
                'as="geometry"');
          })

I am generating xml from strings using Dart xml builder.element.  My challenge is that the closing tags include all the properties in the opening tags. I am trying to just get the closing tags by itself.
//Output
<mxCell id= "135" value="" style="outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.s3;fillColor=#F58534;gradientColor=none;" vertex="1" parent="1">
                        <mxGeometry x= "40.56576085090637" y= "87.17634147405622" width= "360.3372859954834" height= "494.9196102619171" as="geometry"/>
                    "</mxCell id= "135" value="" style="outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.s3;fillColor=#F58534;gradientColor=none;" vertex="1" parent="1">"

//Desired output
<mxCell id= "135" value="" style="outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.s3;fillColor=#F58534;gradientColor=none;" vertex="1" parent="1">
                        <mxGeometry x= "40.56576085090637" y= "87.17634147405622" width= "360.3372859954834" height= "494.9196102619171" as="geometry"/>
                    </mxCell>

The closing tags include the elements in the opening tag. I want it to be just the name of the tag without it properties.

A: If you're talking about package:xml in the pub, I can see that you ended up putting everything as the name of the tag, so of course it's going to repeat it in the close tag.  You want something closer to this:
final builder = XmlBuilder();
builder.processing('xml', 'version="1.0"');
builder.element('bookshelf', nest: () {
  builder.element('book', nest: () {
    builder.element('title', nest: () {
      builder.attribute('lang', 'en');
      builder.text('Growing a Language');
    });
    builder.element('price', nest: 29.99);
  });
  builder.element('book', nest: () {
    builder.element('title', nest: () {
      builder.attribute('lang', 'en');
      builder.text('Learning XML');
    });
    builder.element('price', nest: 39.95);
  });
  builder.element('price', nest: 132.00);
});
final bookshelfXml = builder.buildDocument();

Note the use of builder.attribute, so that it appears as an attribute of the element in which it is within.
EDIT: (untested)
builder.element('mxCell', nest: () {
  builder.attribute('id', myId);
  builder.attribute('value', '');
  builder.attribute('style', 'outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=${_myObjects[i]};fillColor=#F58534;gradientColor=none;');
  builder.attribute('vertex', 1);
  builder.attribute('parent', 1);
})


text:
Q: C# - Updating an ID that requires guessing an AUTO_INCREMENT Ok, so in my MySQL Database, I have a table called groups. In that table, there is one column called id and one column called group_id. Both are needed. Groups are inserted via a C# Emulator. I need to know, how can I edit my code to make it match id and group_id in the database? id is an AUTO_INCREMENT in my groups table and is the primary key.
Here is my C# code,
queryreactor.setQuery(string.Concat(new object[]
                {
                    "INSERT INTO groups (`name`, `desc`,`badge`,`owner_id`,`created`,`room_id`,`colour1`,`colour2`) VALUES(@name, @desc, @badge, ",
                    Session.GetHabbo().Id,
                    ", UNIX_TIMESTAMP(), ",
                    RoomId,
                    ",'",
                    Colour1,
                    "','",
                    Colour2,
                    "')"
                }));
                queryreactor.addParameter("name", Name);
                queryreactor.addParameter("desc", Desc);
                queryreactor.addParameter("badge", Badge);

Anyone any ideas? I know MySQL doesn't support 2 AUTO_INCREMENT columns. But, I basically just need to match the id column and group_id column.

A: I don't get it why you need two columns just to have exactly same values, because you can always use ID column for both group_Id and ID.
If you still want to have such columns, then a simple solution would be to
fire an update query after your Insert query where your group_id gets updated with your newly inserted id column.
something like
update groups
set group_id = id
where group_id is null

or even better, write a trigger on your groups table so that your group_id column gets updated automatically with that of id column on an insert statement of the row


text:
Q: Run script only on index of url Here is a snippet of some script which allows it to run on a URL containing a specific string.
if(location.href.indexOf("MODULE=MESSAGE")>0||location.href.indexOf("/message")>0) { //GOOD TO GO
    if(location.href.indexOf("c=0")>0||location.href.indexOf("c=0")>0) chatLinkStyle = " style='display:none'";

I need to add a second allowance for the script to run on indexOF("SEQNO")
Here is the URL string for the current allowed pages
mysite/2015/55392?MODULE=MESSAGE1
mysite/2015/55392?MODULE=MESSAGE2
mysite/2015/55392?MODULE=MESSAGE3

ect.....MESSAGE20
Here is the other URL string i want to allow in addition to the current
mysite/2015/options?L=55392&O=247&SEQNO=0
mysite/2015/options?L=55392&O=247&SEQNO=1
mysite/2015/options?L=55392&O=247&SEQNO=2

ect...SEQNO=20
No idea how to edit the above to allow for multiple indexOf , any help please.

A: Just add multiple if statements (||)
    <script type="text/javascript">
var myurl = "http://yourwebsite.com/index.php";
var currenturl = window.location;
if(myurl == currenturl) {
    //run your code
}
</script>

A: A bit more cleaner way of doing it. The advantage here is that you can keep adding patterns and don't need to change the code, such as adding another if condition etc.
var allowedPatterns = [
    "MODULE=MESSAGE",
    "/message",
    "c=0",
    "SEQNO"
],
    href = location.href,
    valid = true;

for (var i=0, j = allowedPatterns.length; i<j; i++) {
    if ( href.indexOf(allowedPatterns[i]) === -1 ) {
        valid = false;
        break;
    }
};

if (valid) {
    //Your code
}


text:
Q: How to use the Dictionary javascript class in Google Apps Script? I am trying to make and use a Dictionary object in Google Apps Script. Before, I used a very long switch statement for my script the first time around, and when I submitted it to the Gallery, the person who approved it asked why I didn't use a Javascript Dictionary object instead. I looked into how to use Dictionary objects, but now my script wont' work because Google Apps Script doesn't understand the command:
Components.utils.import("resource://gre/modules/Dict.jsm");

This 'import' line of code was copied straight from this Javascript Reference webpage:
http://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Dict.jsm
How do I include this javascript library needed to make it work, or what is the Google Apps Script alternative to a javascript Dictionary object?

A: Any time you've got a switch statement that looks something like:
switch ( someValue ) {
case "string1": doSomething( valueForString1 ); break;
case "string2": doSomething( valueForString2 ); break;
// ...
case "stringN": doSomething( valueForStringN ); break;
}

you can replace that with:
var dict = {
  "string1": valueForString1,
  "string2": valueForString2,
  // ...
  "stringN": valueForStringN
};

doSomething( dict[ someValue ] );

The values can be anything, of course: strings, numbers, objects, functions, whatever.  And you probably would want to check for a value being missing from the dictionary:
if (dict[someValue]) doSomething(dict[someValue]);


text:
Q: Different list item Hey, I've a very funny problem. I have a very loong ul li a menu and want to have ONE item with different width and height.
The menu looks like this:

The smallest item

Another item

Another item

Another item

  (...)

Then I have something like in:
style.css:
#nav {
  list-style-type: none;
}

#nav li {
  display: inline-block;
  line-width: 2em;
  width: 20px;
  height: 20px;
}

#nav li a {
  display: inline-block;
  width: 20px;
  height: 20px;
}

#smaller {
  width: 10px;
  height: 10px;
}

#smallerLink {
  width: 10px;
  height: 10px;
}

Why the first item isn't 10x10px?

A: Because it contains an a-tag with width and height of 20px. Set overflow:hidden on your #smaller css definition, then it should work. And make it #nav li#smaller for greater specifity.
#nav li#smaller {
    width: 10px;
    height: 10px;
    overflow: hidden
}


text:
Q: ShutdownGracefully() never returns In this snippet of code, shutdownGracefully().syncUninterruptibly() never returns.
Is this the expected behaviour or have I misunderstood something ?
Tested with netty 4.0.35.Final
public class ShutdownGracefullyDemo {
    private ServerBootstrap bootstrap;

    public static void main(String[] args) throws Exception {
        new ShutdownGracefullyDemo().initialize();
    }

    private void initialize() throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        bootstrap = new ServerBootstrap();
        bootstrap.group(group)
            .channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new MyInboundHandler())
            .bind(2025)
            .sync()
            .channel()
            .closeFuture()
            .sync();
    }

    @ChannelHandler.Sharable
    private class MyInboundHandler extends SimpleChannelInboundHandler<ByteBuf> {
        Charset charset = Charset.forName("US-ASCII");

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg)
            throws Exception {
            String data = msg.toString(charset);
            System.out.println("Received: " + data);
            if ("quit\r\n".equals(data)) {
                shutdown();
            }
        }
    }

    private void shutdown() {
        if (bootstrap != null && bootstrap.group() != null) {
            bootstrap.group().shutdownGracefully().syncUninterruptibly();
            System.out.println("shutdown completed");
        }
    }
}

A: The problem is that you are creating a deadlock.
You are calling shutdownGracefully from a thread inside the current event loop, this will cause it to schedule a shutdown, and then wait until every thread is shutdown before continuing. Every thread won't shutdown because you are waiting until the loop has shut down, effectively creating a deadlock.
In a large application, there are multiple ways to solve this:
Using a master thread:
this is solves by having a global application main thread, that calls the shutdown method.
Adding a listener to the graceful shutdown:
Instead of:

.shutdownGracefully().syncUninterruptibly();
System.out.println("shutdown completed");

do
shutdownGracefully().addListener(e -> {System.out.println("shutdown completed");})

As that allows it to unwind the stack from the shutdown method and close that thread properly

A: You can shutdown using code like below:
public void shutdown() {
    LOG.info("Gracefully shutdown http server ...");
    bossGroup.shutdownGracefully(2, 2, TimeUnit.SECONDS);
    workerGroup.shutdownGracefully(2, 2, TimeUnit.SECONDS);
}

The method "syncUninterruptibly()" source code on class "io.netty.util.concurrent.DefaultPromise":
@Override
public Promise<V> awaitUninterruptibly() {
    if (isDone()) {
        return this;
    }

    boolean interrupted = false;
    synchronized (this) {
        while (!isDone()) {
            checkDeadLock();
            incWaiters();
            try {
                wait();
            } catch (InterruptedException e) {
                // Interrupted while waiting.
                interrupted = true;
            } finally {
                decWaiters();
            }
        }
    }

    if (interrupted) {
        Thread.currentThread().interrupt();
    }

    return this;
}

Task blocked on wait() method, it will be never continue until notify(), so application can't shutdown completed.


text:
Q: MongoDB Prometheus-Community exporter not able to fetch the metrics of MongoDB which is enabled by TLS Using Prometheus-community Exporter for fetching metrics from MongoDB Which is TLS enabled. but metrics are not showing in the Prometheus and in logs of Exporter pod as:
kubectl  logs expo-prometheus-mongodb-exporter-55865c7f86-kvg4r -n final-test
time="2022-03-15T11:25:27Z" level=info msg="Starting mongodb_exporter (version=, branch=, revision=)" source="mongodb_exporter.go:94"
time="2022-03-15T11:25:27Z" level=info msg="Build context (go=go1.11.13, user=, date=19700101-00:00:00)" source="mongodb_exporter.go:95"
time="2022-03-15T11:25:27Z" level=error msg="(CommandNotSupportedOnView) Namespace local.system.tenantMigration.oplogView is a view, not a collection. Collection stats will not be collected for this collection. This log message will be suppressed from now." source="collections_status.go:169"
time="2022-03-15T11:25:27Z" level=error msg="(Unauthorized) not authorized on admin to execute command { aggregate: "system.version", pipeline: [ { $indexStats: {} } ], cursor: {}, lsid: { id: UUID("8224906c-49b8-4699-8b3a-972d5518caa0") }, $clusterTime: { clusterTime: Timestamp(1647343521, 1), signature: { hash: BinData(0, F43E74F913B4AECCA2BC772062CFA55B067693D8), keyId: 7073820031389270020 } }, $db: "admin", $readPreference: { mode: "nearest" } }. Index usage stats will not be collected for this collection. This log message will be suppressed from now." source="index_usage.go:104"
time="2022-03-15T11:25:27Z" level=error msg="(Unauthorized) not authorized on admin to execute command { aggregate: "system.keys", pipeline: [ { $indexStats: {} } ], cursor: {}, lsid: { id: UUID("8224906c-49b8-4699-8b3a-972d5518caa0") }, $clusterTime: { clusterTime: Timestamp(1647343521, 1), signature: { hash: BinData(0, F43E74F913B4AECCA2BC772062CFA55B067693D8), keyId: 7073820031389270020 } }, $db: "admin", $readPreference: { mode: "nearest" } }. Index usage stats will not be collected for this collection. This log message will be suppressed from now." source="index_usage.go:104"
time="2022-03-15T11:25:27Z" level=error msg="(Unauthorized) not authorized on admin to execute command { aggregate: "system.users", pipeline: [ { $indexStats: {} } ], cursor: {}, lsid: { id: UUID("8224906c-49b8-4699-8b3a-972d5518caa0") }, $clusterTime: { clusterTime: Timestamp(1647343521, 1), signature: { hash: BinData(0, F43E74F913B4AECCA2BC772062CFA55B067693D8), keyId: 7073820031389270020 } }, $db: "admin", $readPreference: { mode: "nearest" } }. Index usage stats will not be collected for this collection. This log message will be suppressed from now." source="index_usage.go:104"
time="2022-03-15T11:25:27Z" level=error msg="(Unauthorized) not authorized on config to execute command { aggregate: "system.indexBuilds", pipeline: [ { $indexStats: {} } ], cursor: {}, lsid: { id: UUID("8224906c-49b8-4699-8b3a-972d5518caa0") }, $clusterTime: { clusterTime: Timestamp(1647343521, 1), signature: { hash: BinData(0, F43E74F913B4AECCA2BC772062CFA55B067693D8), keyId: 7073820031389270020 } }, $db: "config", $readPreference: { mode: "nearest" } }. Index usage stats will not be collected for this collection. This log message will be suppressed from now." source="index_usage.go:104"
time="2022-03-15T11:25:27Z" level=error msg="(Unauthorized) not authorized on config to execute command { aggregate: "system.sessions", pipeline: [ { $indexStats: {} } ], cursor: {}, lsid: { id: UUID("8224906c-49b8-4699-8b3a-972d5518caa0") }, $clusterTime: { clusterTime: Timestamp(1647343521, 1), signature: { hash: BinData(0, F43E74F913B4AECCA2BC772062CFA55B067693D8), keyId: 7073820031389270020 } }, $db: "config", $readPreference: { mode: "nearest" } }. Index usage stats will not be collected for this collection. This log message will be suppressed from now." source="index_usage.go:104"
time="2022-03-15T11:25:27Z" level=error msg="(Unauthorized) not authorized on local to execute command { aggregate: "replset.minvalid", pipeline: [ { $indexStats: {} } ], cursor: {}, lsid: { id: UUID("8224906c-49b8-4699-8b3a-972d5518caa0") }, $clusterTime: { clusterTime: Timestamp(1647343521, 1), signature: { hash: BinData(0, F43E74F913B4AECCA2BC772062CFA55B067693D8), keyId: 7073820031389270020 } }, $db: "local", $readPreference: { mode: "nearest" } }. Index usage stats will not be collected for this collection. This log message will be suppressed from now." source="index_usage.go:104"
[ { $indexStats: {} } ], cursor: {}, lsid: { id: UUID("8224906c-49b8-4699-8b3a-972d5518caa0") }, $clusterTime: { clusterTime: Timestamp(1647343521, 1), signature: { hash: BinData(0, F43E74F913B4AECCA2BC772062CFA55B067693D8), keyId: 7073820031389270020 } }, $db: "local", $readPreference: { mode: "nearest" } }. Index usage stats will not be collected for this collection. This log message will be suppressed from now." source="index_usage.go:104"
time="2022-03-15T11:25:27Z" level=info msg="Starting HTTP server for http://:9216/metrics ..." source="server.go:140"
MongoDB is Enabled by TLS
Connection string is:
"mongodb://mongo:mongo123@mongodb-2.mongodb.final-test.svc.cluster.local:27017/admin?replicaSet=rs1&tls=true&tlsCertificateKeyFile=/tmp/tls-combined.pem&tlsCAFile=/tmp/ca.crt"
Any Suggestions would be helpful.

A: I have encountered this issue with a mongodb-exporter deployed through bitnami's helm chart where in order to get mongodb metrics besides mongodb_up was to provide "--collect-all" flag to exporter. If you are using the same chart then you need to provide it through extraFlags in the values.yaml
extraFlags: "--collect-all"

if the exporter is spinned-up via compose then you will need to have it under command such as (it will obviously be different considering that you will tls flags in there):
    command:
      - "--mongodb.uri=mongodb://mongo:27017"
      - "--mongodb.collstats-colls=Test.Listings"
      - "--discovering-mode"
      - "--mongodb.direct-connect"
      - "--collect-all"

The image being used within our chart was "bitnami/mongodb-exporter:0.32.0-debian-10-r3".
However, the available dashboards make use of older metric names so my dashboards that I picked from under percona's repository even after modifying the datasources did not get populated.
One suggestion regarding when I was searching online was that is adding "--compatible-mode" as well but that has been reported to be not working with mongo:5 and up. I have yet to confirm with previous releases such as mongo:4.2
I am currently trying to convert the queries of the dashboards accordingly with the new metric names though it ain't pretty.
Hope this helps.