text:
Q: Powershell FTP upload questions Powershell guru's --
Two questions that have been driving me crazy:
Question 1:
I see this code everywhere in powershell examples:
= [System.Net.WebRequestMethods+Ftp]::UploadFile

Where is this syntax documented????????????????????????? !!!!!, namely:
[System.Net.WebRequestMethods+Ftp]

I get what is going on (just using the WebRequestMethods.Ftp class field UploadFile), but I thought (by reading the .NET class docs ) that one should be able to use:
[System.Net.WebRequestMethods.Ftp.UploadFile]

Can someone please explain the [System.Net.WebRequestMethods+FTP] powershell syntax -- or at least send me to a page where it is documented??
Question 2:
Does anyone have an example of a powershell script that can read a list of file paths and upload them to an FTP server?  For example if the file "upload_files.txt contains these two lines:
D:\www\index.html
D:\www\test\index.html

The code would read each line in the "upload_files.txt" file and the 2 local files would be uploaded to the FTP server.


text:
Q: Notepad ++ Find word and replace line above and below Here's my example :
class Item478
{
    position[]={14186.376,18.035046,18340.531};
    azimut=-134.41499;
    id=734;
    side="EMPTY";
    vehicle="Land_LampStreet_F";
    skill=0.60000002;
    init="this enableSimulation true; this allowDamage false;";
};

I have multiple paragraphs. I need to find the word "Land_LampSreet_F and delete the line above and below.
How can I use regular expression or extended mode of Find & replace ?

A: Macro allows you to repeat a set of actions again (and again...) but you will need to "teach" Notepad++ what it is you want to do first. So follow the instructions below closely or you could end up with a non-working result.
Please note that for simplicity I will only explain how to work with macros for your first case (your first file) so as not to repeat myself unnecessarily. Also, please make sure you have a backup copy of the original file before you attempt this in case something does not work as intended.
Okay, here goes:
Open up Notepad++, open up your file.
Make sure you are at the beginning of your first line of data, that is, the first line with the first word in your dictionary in your case.
From the "Macro" menu select "Start recording"
Do what you need to do with only the first set of data. The last step here is important because you want to be at the 'right place' for the next run-through of your macro
Now from the "Macro" menu select "Stop recording"
From the "Macro" menu, select "Save the recorded macro", and give it some appropriate name and click "OK"
Now (still having the cursor at the beginning of next line) select "Macro" > "Run a macro multiple times", select the macro you saved in step 6 and choose "Run to end of file", then click OK.
The macro will now work its way through your file. Be sure to give it a moment to finish if your file is large! You should now see that the macro has moved all your lines down as needed.
The same principle can be applied to your second request, although that requires a more advanced macro with more recorded actions. Once you understand the concept and know how to record a macro and play it back, however, it should be doable.
Hope this was helpful!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Permission denied in macbook pro m1 I brought  a new macbook pro m1 and i copied a react project that i am currently  working in a windows laptop ,but it was not running and showing  a permission  denied message and the node modules folder is showing in a gray color in vs code.This project was perfectly running in my windows at the same time.
bimalboby@Bimals-MacBook-Pro netflix % npm start

> netflix@0.1.0 start /Users/bimalboby/Desktop/Projects/Netflix-clone/netflix
> react-scripts start

sh: /Users/bimalboby/Desktop/Projects/Netflix-clone/netflix/node_modules/.bin/react-scripts: Permission denied
npm ERR! code ELIFECYCLE
npm ERR! errno 126
npm ERR! netflix@0.1.0 start: `react-scripts start`
npm ERR! Exit status 126
npm ERR!
npm ERR! Failed at the netflix@0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/bimalboby/.npm/_logs/2021-06-14T04_42_21_515Z-debug.log
bimalboby@Bimals-MacBook-Pro netflix %


text:
Q: Which is the actual surface of a Möbius strip? Usually, the pop explanations of the properties of the Möbius strip say that if you take a pencil and start drawing a line in the middle of the strip, you'll have to make two complete loops to return to the original position. But if you look at the parametrization of the strip, after one loop you are again at the same position, albeit with the opposite chirality: it's like to say that the ink passes through the paper and colors both "faces" of the strip.
Which is the correct way to look at the strip?


text:
Q: How to Spin up docker container & run some command via golang script? I am planning to automate spinning up container and run some commands on it.
But I get the below error
docker run -it alpine sh ls

Error I get is
docker error : the input device is not a TTY.

So I removed interactive part and ran
docker run -t alpine sh ls

I don't get the shell but docker is spinning
I run above docker commands in golangs os.exec package.
package main
import (
    "fmt"
    "os"
    "os/exec"
    "sync"
)
func main() {
    var wg sync.WaitGroup
wg.Add(1)
    go func() {
        defer wg.Done()
        cmd := exec.Command("docker", "run","-it","alpine","sh","ls")
        cmd.Stdout = os.Stdout
        cmd.Stderr = os.Stderr
        cmd.Run()
        // log.Println(cmd.Run())
    }()
}()
    wg.Wait()
}

My intention is to run multiple shell scripts after spinning up the docker.
Any help would be appreciated. Thanks

A: One avenue to explore is the official packages moby/moby integration-cli and moby/moby integration-cli/cli with cli.go.
The func Docker(cmd icmd.Cmd, cmdOperators ...CmdOperator) *icmd is made to run a docker command, with parameters.
Example, for docker run:
cli.Docker(cli.Args("run", "--name", name, "--rm", "busybox", "sh", "-c", "sleep 30; echo hi"))


text:
Q: Significance of 'chiral' form for a qubit? Say I have a qubit with probability amplitude divided evenly among $|0\rangle$ and $|1\rangle$
$$\frac{1}{\sqrt 2}|0\rangle + \frac{1}{\sqrt 2}|1\rangle$$
So it seems that we have a, loosely speaking, 'symmetric' probability amplitude for the states. However, I read in

Explorations in Quantum Computing. Colin P. Williams (Springer, 2011), p. 392.

that this is not the case and
$$\frac{1}{\sqrt 2}|0\rangle + \frac{i}{\sqrt 2}|1\rangle$$
is actually a 'better' representation of a states with a symmetric probability amplitude.
Can someone explain why this is so? The explanation can be very handwavy, I'm looking for some intuition on it why this is the case.

A: That's not really what he means in the book you linked to: he's not talking about the probabilities of getting 1 or 0 if you measure that qubit.
His point is that if you start the quantum walk with the coin qubit in the first state you gave, after waiting for a few timesteps, you get a position probability distribution that doesn't look very symmetric about position zero.  If you have the coin qubit in the second state you gave, you get something that looks more symmetric.


text:
Q: Filtering on a Window function in Django I have the following model:
class Foobar(models.Model):
    foo = models.IntegerField()

And I figured out how to calculate the delta of consecutive foo fields by using window functions:
qs = Foobar.objects.annotate(
    delta=F('foo') - Window(
        Lag('foo'),
        partition_by=F('variant'),
        order_by=F('timestamp').asc(),
    )
)

Now I only want the records from this where delta is negative:
qs.filter(delta__lte=0)

But as you might expect, this gives an error:
django.db.utils.NotSupportedError: Window is disallowed in the filter clause.

How can I do this filtering with the Django ORM?

A: Django 4.2 supports filtering on WINDOW expressions.
See the release notes and also the pull request.


text:
Q: verifying signature java.security.SignatureException: Signature length not correct: got 353 but was expecting 256 I try to verify a signature I'm getting by HTTP GET request using RSA 2048 bit public key from X509 Base64 encoded pem certificate and SHA1RSA algorithm, but I get java.security.SignatureException: Signature length not correct: got 353 but was expecting 256
if I add BC provider
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); in this case I haven't get any exceptions but the result always is false
Why I don't get any exceptions using BC provider? And why I'm getting the exception of 353 bytes? I read that

when a    message of any length < 2^64 bits is input, the SHA-1
  produces a    160-bit output called a message digest.

String signature = java.net.URLDecoder.decode(signedURLString, "utf-8");
byte[] decodedByteArray = java.util.Base64.getMimeDecoder().decode(signature.getBytes("utf-8"));
verifySignature(data.getBytes("utf-8"), decodedByteArray)

private Certificate loadCertificate() throws FileNotFoundException, CertificateException {
    FileInputStream fis = new FileInputStream(keystorePath);
    BufferedInputStream bis = new BufferedInputStream(fis);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    return cf.generateCertificate(bis);
}

private boolean verifySignature(byte[] data, byte[] signatureToVerify) throws Exception {

    Certificate cert = (Certificate) loadCertificate();
    //Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    Signature s = Signature.getInstance("SHA1WithRSA");
    s.initVerify(cert.getPublicKey());
    s.update(data);

    if(s.verify(signatureToVerify)) {
        return true;
    } else {
        return false;
    }

}

if I use java.util.Base64.getDecoder then I get java.lang.IllegalArgumentException: Illegal base64 character a
Why the character 'a' is invalid??
java.util.Base64.getMimeDecoder decodes without any errors
org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [appServlet] in context with path [] threw exception [Request processing failed; nested exception is java.security.SignatureException: Signature length not correct: got 276 but was expecting 256] with root cause
java.security.SignatureException: Signature length not correct: got 276 but was expecting 256
    at sun.security.rsa.RSASignature.engineVerify(RSASignature.java:189)
    at java.security.Signature$Delegate.engineVerify(Signature.java:1219)
    at java.security.Signature.verify(Signature.java:652)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1526)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1482)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)

-
SEVERE: Servlet.service() for servlet [appServlet] in context with path [] threw exception [Request processing failed; nested exception is java.security.SignatureException: doFinal() failed] with root cause
javax.crypto.IllegalBlockSizeException: Data must not be longer than 256 bytes
    at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:344)
    at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389)
    at javax.crypto.Cipher.doFinal(Cipher.java:2165)
    at java.security.Signature$CipherAdapter.engineVerify(Signature.java:1316)
    at java.security.Signature$Delegate.engineVerify(Signature.java:1219)
    at java.security.Signature.verify(Signature.java:652)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1526)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1482)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)


text:
Q: "to which" to "where" - the average age to which Can I change "to which" to "where" in the sentence below?

The practice of medicine has meant the average age to which people in all nations may expect to live is higher than it has been in recorded history.

A: No, age is not a location, and "to" serves an essential role.

A: "To which" is correct, and while you could probably substitute "where" without comment, it doesn't quite fit.
However the entire sentence is confusing and poorly written.  When you run into situations where you have a choice between two awkward phrases, you should consider whether there is a better way to say what you mean. For example, "the average age to which people may expect to live" is called the "the average life expectancy".
Here's one way I would write it:

With the help of modern medical practice, throughout the world the average life expectancy is higher than at any other time in recorded history.


text:
Q: Close off topic issue I recently marked a post off topic, but after 5 votes it start showing my name as closed as duplicated. Which I do not.

It should not count or at least state marked as duplicate by someone who has not actually did it.

A: With close voting (except for migration), the main close reason is simply majority rules.
If 3 users vote to close a "primarily opinion based" and 2 users vote to close as "Too Broad", it will be closed and marked as "Primarily Opinion Based", and attributing that reason to all 5 voters.
When you have 3 or more reasons and you no longer have a simple majority is when things get confusing.  At that point, it depends on which majority vote was earliest:

*

*2 users vote for Primarily Opinion Based

*2 users vote for Off-Topic

*1 user votes for Duplicate

In order to break the tie between primarily opinion based and Off-Topic, the system will choose the close reason of the earliest close vote.
This has been how the system works for as long as I can remember, but the recent Close changes (in June) did take it a step further with the off-topic close reason.
Since "Off-Topic" has multiple sub reasons, when "Off-Topic" is the selected close reason, it will attribute the users who selected each of the sub-reasons separately.
With migration, I believe you need 4 votes to migrate to the same site, so it isn't majority rules anymore but migration is a special case.  If you don't get enough migration votes, it just goes in as Off-Topic.
Given all of this I haven;t really seen a justification of why it is the way it is and if it would be difficult too change.  Personally, I think it should show all of the close reasons, less so for attribution purposes and moreso to convey to the original poster all of the issues with the post.


text:
Q: How can I delete a folder which was temporarily created for a Windows update?
Possible Duplicate:
Can't delete folder in Windows 7

Recently I updated Windows 7 and it seems to have left a folder on my download partition under the name of 'ed4d9301c862cbea71281a6acdc7'. Now when I try to delete this folder I get the following message:

Now I am logged in as administrator and have full control in the Security tab. I also tried adding my username and giving myself full control over the folder as well. But nothing I tried so far has worked as it seems to be the case that only 'SYSTEM' can make changes to this folder. All this despite me having full control over this folder. Could anyone guide me into the right direction please because it seems to me I'm missing something here.
Edit: A Live CD is not an option as my DVD/CD reader/writer is not functional.

A: I've noticed that these folders can't be deleted until after one or two additional reboots.
It may be that after the first reboot, there are still some other things that need to be done before that directory can be removed -- unfortunately Windows doesn't seem to clean them up on its own, which is why we're all left with having to clean up after it.

A: Would "Unlocker" be of any use to you? http://www.softpedia.com/get/System/System-Miscellaneous/Unlocker.shtml


text:
Q: Combine 2 mysql tables in third table I have 3 tables in mySql==> tableA, tableB, tableC
In tableA, I have the following
+---------+----+----+--------+------------+--+
|  Name   | N1 | N2 | Color  |   State    |  |
+---------+----+----+--------+------------+--+
| John    | 60 | 50 | Red    | Newyork    |  |
| Tom     | 70 | 60 | Green  | Kansas     |  |
| Mathew  | 50 | 40 | Blue   | Texas      |  |
| James   | 40 | 30 | Yellow | Texas      |  |
| SSS     | 70 | 60 | Pink   | Washington |  |
+---------+----+----+--------+------------+--+

In tableB, I have the following
+--------+----+----+
| S.Name | N3 | N4 |
+--------+----+----+
| Carl   | 10 | 18 |
| Jason  | 15 |  9 |
| Cindy  | 13 | 12 |
| Tim    |  7 | 18 |
| Pam    | 15 | 14 |
+--------+----+----+

In table C, I want the following
+---------+----+----+--------+------------+--------+
|  Name   | N1 | N2 | Color  |   State    | S.Name |
+---------+----+----+--------+------------+--------+
| John    | 60 | 50 | Red    | Newyork    |        |
| Tom     | 70 | 60 | Green  | Kansas     |        |
| Mathew  | 50 | 40 | Blue   | Texas      |        |
| James   | 40 | 30 | Yellow | Texas      |        |
| SSS     | 70 | 60 | Pink   | Washington |        |
|         | 10 | 18 |        |            | Carl   |
|         | 15 |  9 |        |            | Jason  |
|         | 13 | 12 |        |            | Cindy  |
|         |  7 | 18 |        |            | Tim    |
|         | 15 | 14 |        |            | Pam    |
+---------+----+----+--------+------------+--------+

Please help me with this sql query. Thanks

A: As select result, you can use simple union all:
select Name as Name, N1 as N1, N2 as N2, Color as Color, State as State, null as S_Name from tableA
union all
select null as Name, N3 as N1, N4 as N2,  null as Color,  null as State, S_Name as S_Name from tableB

A: what you can do is just call it by using union all
select name, n1, n2, color, state, null as 's_name' as recordtype from tablea
union all
select null as 'name', n3 as 'n1', n4 as 'n2', null as 'color', null as
'state', s_name from tableb

A: create table tablc as
select name,n1,n2,color,State,' ' as sname FROM tablea
union
select '' as name,n3,n4,'' as color ,'' as State ,'s.name' as sname from tableb

A: There are two table  as mention above
   When we run the code
Create table tablc as
select name,n1,n2,color,State,' ' as sname FROM tablea
union
select '' as name,n3,n4,'' as color ,'' as State ,'s.name' as sname from tableb

the new table will createenter image description here
the output will display as table tablc


text:
Q: migrate application from weblogic 10 to 12c websevice.jar and webserviceclient.jar not supporting I am migrating the application from weblogic 10 to 12 c
I have webservice.jar and webserviceclient.jar in my class path
when i deploy application on weblogic 12c It doesnt have webservice.jar and webserviceclient.jar
is there any alternate jar . Or how can we compile the code without these jar files
Thanks
Ramandeep S

A: Create the wlfullclient.jar and use that for compile classpath. wlfullclient.jar should have everything you need. This is the way to create it: go to weblogic server lib directory, then java -jar wljarbuilder.jar -profile wlfullclient. Hope it helps.

A: everything is in :
wseeclient.jar

instead of
webservice.jar

http://docs.oracle.com/middleware/1212/wls/SACLT/basics.htm#i1069973
..
but the package is changed to
weblogic.wsee.*;

instead of
weblogic.webservice.*;

so make sure that you change some paths


text:
Q: how to authorize by rest api for neo4j I am using neo4j-enterprise 2.2, HA mode.
Now when I access the neo4j instance by rest api, I got 401 response, it seems that this is because of Unauthorized ?
My question is how can I authorize in rest API?
  Thank you!

A: In short: you need to send one request to retrieve a token by sending your username/password. Subsequent requests will use the token.
In detail: read the related section in the manual.


text:
Q: arduino parameter pack working without tuple I'm trying to do a sketch that can return a parameter pack. I found a reference here:
tuple to parameter pack
I modify it to be even more generic and can return any type of object to a void function pointer.
That said, now I'm testing with arduino DUE and this board support tuple. But the arduino uno do not.
So, base on this article:
variadic data structure
I decide to use my own micro-tuple data-structure that will be supported by UNO. The structure work by itself.
Here the code so far:
#include <tuple>

template<size_t idx, typename T>
struct microTupleGetHelper;

template<typename ... T>
struct microTuple
{
};

template<int ...> struct seq {};

template<int N, int ...S> struct gens : gens<N - 1, N - 1, S...> { };

template<int ...S> struct gens<0, S...>{ typedef seq<S...> type; };

template<typename T, typename ... Rest>
struct microTuple<T, Rest ...>
{
microTuple(const T& first, const Rest& ... rest)
    : first(first)
    , rest(rest...)
{}

T first;
microTuple<Rest ... > rest;

template<size_t idx>
auto get() ->  decltype(microTupleGetHelper<idx, microTuple<T,Rest...>>::get(*this))
{
    return microTupleGetHelper<idx, microTuple<T,Rest...>>::get(*this);
}
};

template<typename T, typename ... Rest>
struct microTupleGetHelper<0, microTuple<T, Rest ... >>
{
    static T get(microTuple<T, Rest...>& data)
    {
        return data.first;
    }
};

template<size_t idx, typename T, typename ... Rest>
struct microTupleGetHelper<idx, microTuple<T, Rest ... >>
{
    static auto get(microTuple<T, Rest...>& data) ->  decltype(microTupleGetHelper<idx-1,
microTuple<Rest ...>>::get(data.rest))
    {
        return microTupleGetHelper<idx-1, microTuple<Rest ...>>::get(data.rest);
    }
};

template <typename ...Args>
struct paramsPack
{
//std::tuple<Args...> params;
microTuple<Args...> params;

void (*func)(Args...);

/*    template<int ...S>
auto callFunc(seq<S...>) -> decltype(this->func(std::get<S>(this->params) ...))
{
    return func(std::get<S>(params) ...);
}*/

template<int ...S>
auto callFunc(seq<S...>) -> decltype(this->func(this->params.get<S>() ...))
{
    return func(params.get<S>() ...)
}

auto delayed_dispatch() -> decltype(this->callFunc(typename gens<sizeof...(Args)>::type()))
{
    return this->callFunc(typename gens<sizeof...(Args)>::type()); // Item #1
}

};

the error come in auto callFunc(..), it stand:
microTuple:72:73: error: expected primary-expression before ')' token

 auto callFunc(seq<S...>) -> decltype(this->func(this->params.get<S>() ...))

                                                                     ^

A: The type of params is dependent on the template parameters, so the compiler has no way of knowing whether .get is a template or not when parsing it. You need to tell the compiler explicitly that it is a template:
auto callFunc(seq<S...>) -> decltype(this->func(this->params.template get<S>() ...))


text:
Q: jQuery click animate move down without class Its quite hard to explain. I have a class as selector, which is clickable. After the click, the class gets removed, so that it should'nt be clickable anymore, until the class gets added again.
My code is like this:
$('.inactive').click(function(){
     $('.inactive').addClass('active').removeClass('inactive');
     $('#test').animate({ top: "+=20" }, 400);
});

You can check this jsfiddle

A: As I get your question, you need to stop this behavior once the class is removed. Despite the fact that you have removed the class, the DOM's click event still has this function attached. Remove it with
$(this).off('click');

after DOM manipulation.
Edit. I presume, you are using jQuery v.1.7+, else use:
$(this).unbind('click');

A: What @Anton said, or...
$(document).on('click', '.inactive', function(){
        $(this).addClass('active').removeClass('inactive');
        $('#test').animate({ top: "+=20" }, 400);
});

A: As they are mutually exclusive, you shouldn't need both inactive and active classes. Either one should do the job - styling and selection.
The simplest way to detach an event handler after the event has fired is to use jQuery's .one().
You will end up with something like this.
function activate() {
     $(this).removeClass('inactive');
     $('#test').animate({ top: "+=20" }, 400);
}

$('.inactive').one('click', activate);

By defining the handler as a named function, it remains available to be reattched.
To make an element inactive again you would need to add 'inactive' and reattach the click handler :
var $foo = $(selector);//select an element or elements by whatever means
$foo.each(function() {
    if(!$(this).hasClass('inactive')) {
        $(this).addClass('inactive').one('click', activate);
    }
});


text:
Q: ResourceDictionaries - StaticResource - other assembly I'm currently trying to figure out how I can get the WPF designer to display correctly a list of resources I can use.
For example when using a TextBlock in xaml, I can "preview" the useable resources, for usual.

This does not seem to work well when using it from an external DLL/assembly (binary).

I've already tried to use the usual source strings for ResourceDictionary,
<ResourceDictionary Source="pack://application:,,,/MyAssembly;component/Themes/Generic.xaml"/>
<ResourceDictionary Source="/MyAssembly;component/Themes/Generic.xaml"/>

as mentioned in various other questions and answers while googling this issue, though not even the direct Uri to the required ResourceDictionary seems to work.
Is there any fix for this issue or does it simply not work ?
I don't want to disable the designer, please do not suggest so.


text:
Q: Could the \include{} command be used in a knitr .Rnw file? Using \include{} usually works, unless there are code chunks in the file to be included:
\documentclass{article}
\begin{document}
% \include{test.tex}
\include{test.Rnw}
\end{document}

with test.tex or test.Rnw define e.g. by
<<echo=TRUE,eval=TRUE>>=
plot(cars)
@

won't display the cars plot. Is there some chance to find a way to bypass that trouble?
Thanks,
Julyan

A: You can include .Rnw file with child.
\documentclass{article}
\begin{document}

<<test, child='test.Rnw'>>=
@

\end{document}

were test.Rnw contains:
<<echo=TRUE,eval=TRUE>>=
plot(cars)
@


text:
Q: MVC Models instantiation Where should the Models be instatiated in a MVC arhitecture? I understand the preferred way would be outside controllers, in a bootstrap file and injected using a Dependecy Injection Container. But most of the models I'm working with depend on run time parameters.
//PHP Example
class UserController {
   protected $objUser;
   protected $objDictionary;

   public function Show() {
       $objUserMapper = new UserMapper();
       $this->objUser = $objUserMapper->FindById($_GET['id']);
       $this->objDictionary = new Dictionary($this->objUser->Language);
   }
}

A: View models are generally instantiated in controllers.
Domain models shouldn't be used in controllers unless project is really small.
Inversion of control containers are normally used to inject services that talk to the business layer. This becomes useful when you write your application using TDD as you would normally mock calls to your services.
General flow is:

*

*Retrieve data from service in form of DTO or domain model

*Automap from DTO or domain model to your view model (this can be done in controllers' actions)

*Return view with a view model

A: In the MVC pattern, the Controller instantiates both Models and Views.
It can do so directly or via other means, typically some form of factory or a IoC container. In any case the "new instance" of the Model is held by the controller which passes it to the View.
Also, the view may have its own underlying class (this depends on which MVC framework you are using) and may not receive the model directly - it's OK if the controller translates the "Model language" (business concerns) to the "View language" (presentation concerns).


text:
Q: Android Google Places API Review APPLICATION
    My application displays markers near my current location(which is working perfectly). After that the person can click the marker so that a windows pops up describing that particular location. Once the person clicks the on popup a review activity starts.
PROBLEM
    My Review Activity displays the name, address, contact, website, rating, reviews from users about that location. Everything works fine for some place, but doesn't for some.
This is my Code.java
    TextView addressText = (TextView) findViewById(R.id.addressText);
    TextView contactText = (TextView) findViewById(R.id.contactText);
    TextView websiteText = (TextView) findViewById(R.id.websiteText);

    final JSONObject json = new JSONObject(result);
    JSONObject completeDesc = json.getJSONObject("result");
    addressText.setText(completeDesc.getString("vicinity"));
    contactText.setText(completeDesc.getString("formatted_phone_number"));
    websiteText.setText(completeDesc.getString("website"));

    Double ratStar = completeDesc.getDouble("rating");

    JSONArray photo = json.getJSONArray("photos");
    JSONObject photoDesc = photo.getJSONObject(0);
    String photoRef = photoDesc.getString("photo_reference");

    checkStarCondition(ratStar);

    LinearLayout layout = (LinearLayout) findViewById(R.id.reviewInfo);
    JSONArray reviewArray = completeDesc.getJSONArray("reviews");

    if ( reviewArray.length() > 0 ) {
        TextView noReview = (TextView) findViewById(R.id.noReview);
        noReview.setVisibility(View.GONE);
    }

    for (int i = 0; i < reviewArray.length(); ++i) {
        TextView user = new TextView(ReviewActivity.this);
        TextView comment = new TextView(ReviewActivity.this);
        TextView linebreak = new TextView(ReviewActivity.this);

        JSONObject jObj = reviewArray.getJSONObject(i);
        final LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT);
        user.setLayoutParams(lparams);
        user.setText(jObj.getString("author_name"));
        user.setTextSize(18);
        user.setTypeface(null, Typeface.BOLD);

        comment.setLayoutParams(lparams);
        comment.setText(jObj.getString("text"));
        comment.setTextSize(14);

        linebreak.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        linebreak.setText("           ");

        layout.addView(user);
        layout.addView(comment);
        layout.addView(linebreak);
    }
} catch (JSONException e) {
    e.printStackTrace();
}

review_activty.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mazik.ahmed.funkyproject.ReviewActivity"
    android:orientation="vertical">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:src="@drawable/ic_store"
            android:id="@+id/imageView" />
    </LinearLayout>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:padding="10dp"
        android:layout_height="wrap_content">

        <ImageView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/ratingStar"
            android:src="@drawable/star00" />
    </LinearLayout>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:padding="10dp"
            android:layout_height="wrap_content"
            android:gravity="center">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingRight="10dp"
                android:src="@drawable/ic_name"
                android:id="@+id/imageView4" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="18sp"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:text="Name"
                android:id="@+id/nameText"
                android:textAlignment="center" />
        </LinearLayout>

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:padding="10dp"
            android:layout_height="wrap_content"
            android:gravity="center">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingRight="10dp"
                android:src="@drawable/ic_address"
                android:id="@+id/imageView3" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="18sp"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:text="Address"
                android:id="@+id/addressText"
                android:textAlignment="center" />

        </LinearLayout>

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:padding="10dp"
            android:layout_height="wrap_content"
            android:gravity="center">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingRight="10dp"
                android:src="@drawable/ic_call"
                android:id="@+id/imageView5" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="18sp"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:text="Contact"
                android:id="@+id/contactText"
                android:textAlignment="center" />
        </LinearLayout>

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:padding="10dp"
            android:layout_height="wrap_content"
            android:gravity="center">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingRight="10dp"
                android:src="@drawable/ic_web"
                android:id="@+id/imageView6" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="18sp"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:text="Website"
                android:id="@+id/websiteText"
                android:textAlignment="center" />
        </LinearLayout>

    </LinearLayout>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        android:padding="15dp"
        android:gravity="center">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="28sp"
            android:textStyle="bold"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Reviews"
            android:id="@+id/reviewText" />
    </LinearLayout>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/reviewInfo"
        android:gravity="center">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="No Review Available"
            android:id="@+id/noReview"
            android:textColor="#CCC"
            android:textAlignment="center"
            android:padding="20dp" />
    </LinearLayout>

</LinearLayout>
</ScrollView>

The problem that i am facing is that for some places the data that this api fetches is perfectly working but it fails on other places in some scenario even tho google maps shows rating and reviews for that location.
Can someone help me in where i am going wrong?


text:
Q: How do I find the memory address of a Python / Django model object? An ordinary object, I can use
o.__repr__()

to see something like
'<__main__.A object at 0x9d78fec>'

But, say, a Django User just returns
<User:bob>

How can I see the actual address of one of these, or compare whether two such model-objects are actually the same object or not?

A: id() will return the identity of the object (generally implemented as the address), which is guaranteed unique for two objects which exist at the same point in time.  However the obvious way to check whether two objects are identical is to use the operator explicitely designed for this: is
ie.
 if obj1 is obj2:
     # Objects are identical.

A: You can get the id of any object:
a = object()
print hex(id(a))

Although for CPython, this is the address of the object, this is not guaranteed I believe (and may be different on other implementations like iron python). Same id means same object, though.

A: Use the id() function for that. Or equivalently just compare "obj1 is obj2".


text:
Q: VBA Regular Expression not working as intended Alright, I've been trying to figure this one out but being pretty new to Regular Expressions, I've been less than successful.  What my objective is here is to produce a match comparing one string against another that may be much larger or the same size as the former string.  This match should only occur if the first string 1. is a case insensitive match to some part of the other string, 2. the string successfully matched within the other should be a separate word or phrase, not a part of another word, which means it is lead by either the start of the string or a space and ended by the end of a string or a space.  Any help from a skilled Regular Expression user would be most welcome.
'this yields : run time error 5018 = Unexpected quantifier in regular expression
RegExPattern = "(\b|^)?" + "[" + ColumnArr(PhraseCt) + "]" + "(\b|[ ])?)"
With RegEx
     .MultiLine = False
     .Global = True
     .IgnoreCase = False
     .Pattern = RegExPattern
End With
Set Matches = RegEx.Execute(SearchTerm)

A: \b should match the beginning of a string (see VBA Excel regex - \b word boundary doesn't match if word is at beginning of string for confirmation of that in Excel 2010). So you should be able to just use
RegExPattern = "\b" + ColumnArr(PhraseCt) + "\b"

(assuming that ColumnArr(PhraseCt) is the word you are searching for). And also use IgnoreCase = True if you want it to be case-insensitive.


text:
Q: React component doesn't append newly added items to the list I have a react component that prints out a list of items from an array of objects. Each object can either be a newly created one, or it can be the same object but with some of its properties updated.
Updating an existing object occurs without problems, but when a new object is received, the length of the array increases by 1, and all elements become duplicates of the newly added object.
Here is the react component:

{quests.map(quest => (

{quest.description.title}

    {quest.description.steps.map(step => (

{`${quest.status}/2 ${step}`}

    ))}

))}

Here is how it gets updated:

@action
setQuests(quest: QuestFuncReturnValue) {
// If the quest doesn't exist, append it to the quests list, else update it
const questExists = this.quests.find(oldQuest => oldQuest.id === quest.id);
if (!questExists) {
    this.quests = [...this.quests, quest];
    return;
}
const updatedQuests = this.quests.map(oldQuest => (quest.id === quest.id ? quest : oldQuest));
this.quests = updatedQuests;
console.log(this.quests);
}

I'm using Mobx for the state: Here is the initial value of the array:

@observable.ref quests: QuestFuncReturnValue[] = [];

A: I am not sure if this is the problem, but there should be "key" everywhere you use rendering list.
See key={quest.id} and key={step}

{quests.map(quest => (

{quest.description.title}

    {quest.description.steps.map(step => (

{`${quest.status}/2 ${step}`}

    ))}

))}

A: It actually looks like you will replace every element with the same quest object on an update because of this:
quest.id === quest.id


text:
Q: RSpec stub environment helper I've got a lib/require/environment_helpers.rb file that contains helper methods.  There are more methods, but it's not wrapped in a module.
def development?
  Rails.env.development?
end

def test?
  Rails.env.test?
end

I'm trying to stub these methods out and am not having any luck. I've tried:
before :each
  allow(Rails.env).to receive(:production?) { false }
end

before :each
  allow(Rails).to receive(:production?) { false }
end

before :each
  allow(ServiceUnderTest).to receive(:production?) { false }
end

A:
trying to stub these methods

You can stub it like this
before :each do
  rails_env = double(:rails_env, development?: false)
  expect(Rails).to receive(:env).and_return(rails_env)
  expect(rails_env).to receive(:development?).and_return(false)
end


text:
Q: Riesel and Gohl's Approximation of the Modified Prime Counting Function, $\pi_{0}$ In their article "Calculations Related to Riemann's Prime Number Formula", Riesel and Gohl claim a simplification of Riemann's evaluation of the modified prime counting function
\begin{align}
\pi_{0}(x) & = \tfrac{1}{2} \lim_{\epsilon \to 0} \pi(x + \epsilon) + \pi(x - \epsilon) \\ & =  \lim_{N \to \infty} R_{N}(x) - F_{N}(x)
\end{align}
where $F_{N}(x)$ is an infinite sum which depends only on the complex zeros of the zeta function in the critical strip and accounts for the discontinuities of $\pi_{0}$ at the primes, while
\begin{align}
R_{N}(x) = \sum_{n \geq 1} \frac{\mu(n)}{n} \mathsf{li}(\sqrt[n]{x}) + \frac{1}{2 \log x} \sum_{m = 1}^{N} \mu(n) + \frac{1}{\pi} \arctan \frac{\pi}{\log x} + \epsilon_{N}(x)
\end{align}
is a smooth function of $x$, and $\epsilon_{N} \to 0$ as $N \to \infty$. The first term is Riemann's well-known approximation to $\pi_{0}$, and the remaining terms depend only on the trivial zeros of the zeta function (at the negative even integers). One often finds the approximation,
\begin{align}
\pi_{0}(x) \approx \sum_{n \geq 1} \frac{\mu(n)}{n} \mathsf{li}(\sqrt[n]{x}) - \frac{1}{ \log x}  + \frac{1}{\pi} \arctan \frac{\pi}{\log x}
\end{align}
usually attributed to them. What of the factor of $\frac{1}{2}$ and sum involving the Möbius function; doesn't this sum diverge?

A: They used the classical formula $$\frac 1{\zeta(s)}=\sum_{n\ge1} \frac{\mu(n)}{n^s}$$ and applied it with different values of $s$ to get :

*

*$\sum_{n\ge1} \mu(n)=-2\ $ ($s=0$ and using $\zeta(0)=-\frac 12$) (warning : conjectured only!)

*$\sum_{n\ge1} \frac{\mu(n)}{n}=0\ $ ($s=1$ and since $\frac 1{\zeta(1)}=0$)

*$\sum_{n\ge1} \frac{\mu(n)\log(n)}{n}=-1\ $ (at $s=1$ with $\left(\frac 1{\zeta(s)}\right)'_{s=1}=1$ and $\left(\frac 1{n^s}\right)'_{s=1}=-\frac{\log(n)}n$)
The transformation used was the first one in your case (with $+$ in front of the initial $\frac 1{\log(x)} \sum \mu(n)$ I think).
But this doesn't seem satisfying for a proof since Hardy wrote about (2) that it was as "deep" as the prime number theorem (in "Ramanujan" page 24, I think that (2) was proved by Landau, for a recent review see Terence Tao's "A remark on partial sums involving the Möbius function").
Concerning your first sum this wikipedia article about the Mertens function should be helpful.
If we define the Mertens function as $M(n)= \sum_{k=1}^n \mu(k)$ then $M(n)=\operatorname{O}\left(n^{\frac 12+\epsilon}\right)$ for every $\epsilon >0$ is equivalent to the Riemann Hypothesis (Anderson 'On the Möbius function').

A: This paper uses very unfortunate notations: most of the functions (Rₖ, Tₖ, etc.) have a hidden parameter N (which limits the summation in n).  So even when you think that some terms do not depend on N, they do!  In most of the places in this paper, N<∞, so the question of convergence in n does not arise…
One should keep in mind that the main purpose of all the formulas in this paper is to calculate with sufficient precision for the plots in the paper.  As far as I can see it today, their strategy is:

*

*Choose N so that the summation of (4) (saying π(x) = ∑ₙ μ(n) f(ⁿ√x)/n) is exact (due to f(x)=0 for x<2);

*Use this N in the last summand ∑ₙ₌₁ᴺ μ(n)/n · li(ⁿ√x^ρ) of (19);

*Show that the second summand of (19) has a limit (see (32),(33) above) when N → ∞;

*Show that the first summand in (19) differs from ∑ₙ₌₁ᴺ μ(n) by a term converging when N → ∞.

So the calculations in the formulas (32) and (33) are only a glazing on the cake: the terms with a mysterious dependence on N (in
the last summand of (19)) are completely ignored (analytically), and dealt with numerically.
(Additionally, they put an extra condition on N, that ∑ₙ₌₁ᴺ μ(n) = -2 (after (36)).  Their rationale is completely unclear: why do
they care about decay rate in log x if they have a precise formula?!)


text:
Q: Quero pegar o valor de .getDownloadURL() Eu gostaria de pegar o valor de url_imagem e usar como return da função upImage. Tentei varias coisas e não consegui achar solução.
function upImage(nomeDaPlanta, imgFile){

    var file = imgFile.files[0];
    console.log(file);
    storageRef.child(nomeDaPlanta + ".jpg").put(file).then(function(snapshot) {
        console.log(snapshot);

        var url = snapshot.ref.getDownloadURL().then(function(url_imagem) {
            console.log(url_imagem);

        }).catch(error => {

            console.log(error);
        });

    });
    return url_imagem;
}

A: Sua função é uma função assíncrona. Não há como retornar uma string, somente uma Promise
async function upImage(nomeDaPlanta, imgFile) {
  var file = imgFile.files[0];
  return storageRef
    .child(nomeDaPlanta + ".jpg")
    .put(file)
    .then(function (snapshot) {
      return snapshot.ref.getDownloadURL();
    })
    .catch((error) => {
      console.log(error);
    });
}

// logo você pode chamar a função.
upImage('planta', myFile).then((url) => {
    console.log(`minha url do arquivo enviado é ${url}`);
});

// Você também pode usar async/await (note que a função precisa ter async na frente
const url = await upImage('planta', myFile);


text:
Q: Difference between whitespaces " " and '\ ' in bash Is there any difference between " " and \ in bash?
For example, ls *" "* and ls *\ * will return the same result for me.

A: the "" version will incur a teensy bit more overhead to parse the innards of the quotes for any potential variables/operators. The backslash-space version will be seen as only a literal space without the extra overhead. The actual cost in cpu time/memory usage between the two will be utterly microscopic, however, unless it's inside a loop that's being run kajillions of times.

A: The backslash only masks the next character, and might be faster typed, if you just want to mask one, but that might depend on your keyboard layout, and whether you type with 10 fingers blindly or not. I prefer quotes, because they are more easy to type.
Masking each other and oneself is another difference:
echo \\

will output a backslash, but
echo "\"

will output a ", and wait for the closing quote.
echo \"

will work, and output a quote, but
echo """

will not, for the same reason as above.
Some special characters like linefeed, formfeed, tab, alert and so on can be produced with backslash only, but not with quotes, including backslash itself.
/bin/echo -e "\tfoo\abar\bbar\ffoo\nbar\rfoo"

See man echo for a complete list.
That's not only true for echo, but for many things you can do in scripts, working with strings.


text:
Q: Save last Activity state with a Button I have two Activities: ActivityA and ActivityB.  ActivityA intents to ActivityB which has a button named ClOSE_FOR_NOW. This button should terminate the screen of the app and when relaunching the app, ActivityB should get started rather than the first activity(ActivityA).
Is there any possible suggestion for this ? Any help will be kindly appreciated.
(I'm novice to Android programing)


text:
Q: SSL Errors - Azure API Management I am new to Azure API Management. We are trying to send a custom response to consumer in case of ssl errors.
Can you please help me how to do it ?

A: Look at documentation here https://learn.microsoft.com/en-us/azure/api-management/api-management-howto-mutual-certificates-for-clients
A sample policy below
<choose>
  <when condition="@(context.Request.Certificate == null || context.Request.Certificate.Thumbprint != "desired-thumbprint")" >
    <return-response>
        <set-status code="403" reason="Invalid client certificate" />
    </return-response>
  </when>
</choose>


text:
Q: Format a decimal in background code java I have a program which asks for the price of a Shirt in a method called getCost(). When I run my main class, the decimal prints out like $4.5, and doesn't go to 2 decimal places.
In my main class, I created a DecimalFormat object to try and take care of this issue, but it doesn't help. I feel like I either instantiated it wrong, or I am using it wrong. If decimal format does not work, how can I use printf or any other form to fix this issue?
Here is my main class:
public static void main(String[] args)
{
  Scanner sc = new Scanner (in);
  Object[] Shirts = new Object [6];

  Shirt one = new Shirt(10, false, "green" , "stripes", 14.99);
  Shirts[0] = one;
  Shirt two = new Shirt(9, true, "red", "stripes", 22.90);
  Shirts[1] = two;

  int sz = 0;
  boolean slvs = false;
  String clr = " ";
  String ptrn = " ";
  double cst = 0.0;

  DecimalFormat formatter = new DecimalFormat("#.##");

  //SHIRT 3
  out.println("What is your shirt size::");
  sz = sc.nextInt();
  out.println();

  out.println("How much does your shirt cost::");
  cst = sc.nextDouble();
  //decimal format here
  formatter.format(cst);
  out.println();

  out.println("Your shirt has sleeves. True or False?");
  slvs = sc.nextBoolean();
  out.println();
  sc.nextLine();

  out.println("What is the color of your shirt::");
  clr = sc.nextLine();
  out.println();

  out.println("What pattern does your shirt have::");
  ptrn = sc.nextLine();

  Shirt three = new Shirt(sz,slvs,clr,ptrn,cst);
  sc.nextLine();

  Arrays.sort(Shirts);

  for(int x = 0; x < Shirts.length - 1; x++)
  {
    out.println(Shirts[x].toString());
  }

Here is the toString() in my Shirt class:
 public String toString()
 {
   String str= "Size: " + getSize() + ", It has sleeves: " + getSleeves() + ", Color: "+ getColor() + ", Pattern: " + getPtrn() + ", Cost: $" + getCost();
   return str;
 }

A: The purpose of the formatter is to format the String when you display it, not when you "save" it.
Remove all your formatter.format(whatever), you don't need to format the double when putting it into the shirt (also, you are not doing anything with that line of code).
You need to format when you display the double, in your toString() method:
public String toString()
 {
  String str= "Size: " + getSize() +
              ", It has sleeves: " + getSleeves() +
              ", Color: "+ getColor() +
              ", Pattern: " + getPtrn() +
              ", Cost: $" + formatter.format(getCost()); //Format here
  return str;
 }

Obviously your DecimalFormat must be inside the Shirt class.
Also your pattern isn't correct if you want to always display at least 2 digits. It should be:
DecimalFormat formatter = new DecimalFormat("0.00");

The 0 character is used instead of the pound sign. So 4,3 becomes 4,30.

A: The problem seems to reside within the toString() method:
 public String toString()
 {
      String str= "Size: " + getSize() + ", It has sleeves: " + getSleeves() + ", Color: "+ getColor() + ", Pattern: " + getPtrn() + ", Cost: $" + getCost();
  return str;
 }

Since no formatting seems to be done on whatever it is that getCost() yields.
To fix this, try this:
 public String toString()
 {
     String str= "Size: " + getSize() + ", It has sleeves: " + getSleeves() + ", Color: "+ getColor() + ", Pattern: " + getPtrn() + ", Cost: " + NumberFormat.getCurrencyInstance().format(getCost());
     return str;
 }


text:
Q: C++ float / double : write to / read from file "exact" values I have two programs written in C++, say, calc1 and calc2, which produce results x1 and x2, respectively. They could be float or double.
I mean to write x1 and x2 to file, and read them with another program also in C++, my_oper, which operates with x1 and x2.
I need to keep the full precision that C++ uses for their variables, exactly as if all were done in a single program.
I also mean not to use text files (I do not care about the files being human-readable), so as to reduce the disk space and read/write time.
What should I use for writing and reading?

Question How do I print a double value with full precision using cout? does not fully address the present OP.

Major issue #1: Solutions posted aim at human-readable forms of output, so they do not care about saving disk space. That is an essential part of the question here.

Major issue #2: It does not seem to deal with the whole range of doubles (~ 2^-53 - 2^+53, plus exponents). See snippet below.
And even if it did, issue 1 above already states a different purpose.
Note that if the result from the exact arithmetic is x1=0.1 (e.g.), but the value stored is something slightly different x1* (say, in the 7th significant digit for a float), I want to write and then read x1*, I don't care about x1.
The following snippet
int iexpbase = 0;
fstream file;
file.precision(dbl::max_digits10);
file.precision(17);
file.open("math_precision_io.dat", fstream::out);
for (iexpbase = -100 ; iexpbase <= 100 ; iexpbase+=10) {
    double d2 = pow(10, iexpbase);
    file << fixed << d2 << endl;
}
file.close();

produces this output
0.00000000000000000
0.00000000000000000
0.00000000000000000
0.00000000000000000
0.00000000000000000
0.00000000000000000
0.00000000000000000
0.00000000000000000
0.00000000000000000
0.00000000010000000
1.00000000000000000
10000000000.00000000000000000
100000000000000000000.00000000000000000
1000000000000000019884624838656.00000000000000000
10000000000000000303786028427003666890752.00000000000000000
100000000000000007629769841091887003294964970946560.00000000000000000
999999999999999949387135297074018866963645011013410073083904.00000000000000000
10000000000000002257809904681181209619930771246774403173921223738392576.00000000000000000
100000000000000013190646323278015613777155861640004848960018902522128665705185280.00000000000000000
1000000000000000192640537007097094236487266187713695528897613397388406395002972996141842432.00000000000000000
10000000000000002101697803323328251387822715387464188032188166609887360023982790799717755191065313280.00000000000000000


text:
Q: Rails: Form Validation Errors Are Not Showing (with Formtastic and Bootstrap-Sass) I'm using Bootstrap-Sass along with Formstatic. I thought an error message should be automatically shown next to the field with Formstatic like in this picture:
(source: asciicasts.com)
But even if the user puts an invalid input, my app does not show an error message. This seems to be an easy problem but I cant figure out the reason behind.
PostController
# POST /posts
# POST /posts.json
def create
  @post = Post.new(params[:post])
  @post.view = 0
  @post.like = 0
  @post.hate = 0
  respond_to do |format|
    if @post.save
      @posts = Post.paginate(:page => params[:page], order: 'like desc', per_page: 10)
      format.html { redirect_to posts_path }
      format.json { render json: @post, status: :created, location: @post }
    else
      format.html { render action: "new" }
      format.json { render json: @post.errors, status: :unprocessable_entity }
    end
  end
end

PostModel
  validates :name,  :presence => true
  validates :content, :presence => true,
                      :length => { :minimum => 10, :maximum => 300}

_form (Post)
<% @post = Post.new %>
<%= semantic_form_for @post do |f| %>
<%= f.semantic_errors :name %>
<%= f.inputs do %>
     <%= f.input :name, :label => 'name' %>
     <%= f.input :content, :label => 'body' %>
<% end %>
<%= f.actions do %>
    <%= f.action :submit, :button_html => { :class => "btn btn-primary" }, :as => :button  %>
    <%= f.action :cancel, :as => :link %>
<% end %>

In PostController, I tried deleting the following two lines
    #format.html { render action: "new" }
    #format.json { render json: @post.errors, status: :unprocessable_entity }

and added
render @post.errors

Then, I got
@messages={:name=>["can't be blank"], :content=>["can't be blank", "is too short (minimum is 10 characters)"]}>

So I think the problem might be the way I'm rendering json is wrong. Could someone help me how to fix it?

A: Rails has its own rendering for validation errors, which doesn't match the HTML structure or the CSS structure used by Bootstrap.
To solve this porblem you can just add to view your own code block for output errors.
<% if @posts and @posts.errors and @posts.errors.count > 0 %>

   ×
   <%= pluralize(@posts.errors.count,"error") %> validation problems found.

   <% @posts.errors.full_messages.each do |error| %>

<%= error %>

   <% end %>

Or you can move this block to partial template to avoid dublication of code.
<% if resource and resource.errors and resource.errors.count > 0 %>

    ×
    <%= pluralize(resource.errors.count,"error") %> validation problems found.

    <% resource.errors.full_messages.each do |error| %>

<%= error %>

    <% end %>

<% end %>

And pass @posts to parameters
<%= render "shared/validation_errors", :resource => @posts %>

Here you can find more information about this problem
http://fizzylogic.nl/2013/12/22/temp-slug-54/


text:
Q: Bitbucket Add POST HOOK using API I can see that it is possible to add a git hook to Bitbucket in the interface like so:

Is it possible to add a POST hook like this using Bitbucket's API instead of using the web interface? Is it possible to remove an existing hook using the API?

A: services resource might help you.
Create a POST service example:
curl -u tutorials:8798987 -X POST https://api.bitbucket.org/1.0/repositories/tutorials/testrepo/services/ -d "type=POST&URL=https%3A%2F%2Fbitbucket.org/post"

This will create a new POST hook with https://bitbucket.org/post as URL:
{
    "id": 5,
    "service": {
        "fields": [
            {
                "name": "URL",
                "value": "https://bitbucket.org/post"
            }
        ],
        "type": "POST"
    }
}


text:
Q: Find which cells have a certain colour and list them I am creating an English activity where you practice letters and numbers by having you draw a picture using grid coordinates that I say out loud. The top row has letters and the left column has numbers, and using a combination of both, you can specify what colour is in which cell.
Doing this in excel, I have been drawing the pixel images manually (by printing out images and drawing boxes then coloring background colours in excel cells) and then writing out the answer key (A list of black cells in A, B C etc., Red cells in A, B, C etc.) manually. This has been okay but does come with errors sometimes.
I would like to know a way to list which cells have a certain background colour in them. Ultimately, it would be great if I could list it like the following example:

*

*Black

*A: 1, 2, 3, 4

*B: 4, 5, 6

*C: 4, 5, 6

*etc.

I heard formulas won't work with excel and I would need to use a macro, which is something I have no experience with. Any help would be appreciated!

A: Assuming your Excel workbook has at least one sheet containing the coloured cells (I will refer to that one as "Sheet1") and one extra where to display the result of the query, let's call it "Sheet2", a code listing the coloured cells' addresse could look like this:
Sub ColorIndex()

    Dim RNG         As Range    'the address of the cell you want to check
    Dim lnCol       As Long     'the column of the cell looked at
    Dim lnRow       As Long     'the row of the cell looked at
    Dim c           As Long     'the column on Sheet2 and...
    Dim r           As Long     'the row on Sheet2 where the address of the coloured cell is written to

    c = 1
    r = 1

    For lnCol = 1 To 100  'adjust if necessary, see below

        For lnRow = 1 To 100  'adjust if necessary, see below
        Set RNG = Worksheets("Sheet1").Cells(lnRow, lnCol)

            If RNG.Interior.ColorIndex = 1 Then
                Worksheets("Sheet2").Cells(r, c) = RNG.Address(ReferenceStyle:=xlR1C1) 'Address of the coloured cell on Sheet1 as Row x / Column y
                r = r + 1 'next match written in next row
                ElseIf RNG.Interior.ColorIndex = 2 Then
                    Worksheets("Sheet2").Cells(r, c+1) = RNG.Address(ReferenceStyle:=xlR1C1)
            End If

        Next lnRow

    Next lnCol

End Sub

Note this code checks rows/columns 1 to 100 only. If you have a larger range to check, adjust the number accordingly.
Hope this helps!


text:
Q: how to compare name of data member of class not their value how to campare name of data member(not their value), sending as a argument from function.
The example code  is as follows.
class Example
{
  private:
   std::string value;

  public:
   void Set(const std:: string& MemberName)
   {
      if(MemeberName == value)
       {
         std::cout<<"Same Member Name";
       }
      else
      {
         std::cout<<"Not same Member name";
      }
   }
 ...
}

i did this way but not getting the required result.
Thansks for the help

A: It should be
if(MemeberName == "value")
{
    std::cout<<"Same Member Name";
}
else
{
    std::cout<<"Not same Member name";
}

A: In case you want to find out whether it is the exactly same object, you might use the address, where it is stored:
#include <iostream>
using namespace std;

std::string g;

void foo(const std::string& arg)
{
    if (&arg == &g)                                        // compares addresses
        std::cout << "same object" << std::endl;
    if (arg == g)                                          // compares values
        std::cout << "same value" << std::endl;
}

int main() {
    g = "abc";
    foo(g);
    return 0;
}

Note that when you pass by reference, you are actually working with the same object (no copy is being created) and thus when you use & operator you can retrieve the address of original object. This example prints both same object and same value.


text:
Q: What is the term used for space of analytic functions? I deal with analytic functions in the unit disc represented as the series
$\sum_{n=0}^\infty u_n z^n$, where the coefficients $u_n$ satisfy the condition
$\sum_{n=0}^\infty n^\alpha|u_n| < \infty$
with $\alpha > 0$.
Does there exist any commonly used name for the spaces of such functions?


text:
Q: CSS Nav Element Hover With Bottom Border I am trying to replicate the following effect : http://amplifiedvideodesign.com/capture.png
I can set the background color for hover but how can i do the border and the little arrow that are on the bottom?
Thanks.

A: For the border you can just use the same code you just have to set a border and update its color. You can try my example on jsFiddle
.tabs a:hover {
    background-color: #444;
    border-bottom-color: #484;
    color: #484;
}

As for the arrow/diamond/triangle whatever: That's something you can't setup that easily, but the easiest solution would be adding a background rather than using plain HTML/CSS.
Update: Here's an animated example.


text:
Q: На Spring пишу мэсседжер, при попытке создать ассоциацию друзей через @OneToMany в зависимости от fetchType выдает разные ошибки Весь код сущности
@Entity
public class User implements UserDetails {

public User() {

}

public User(String nick, String pass, String name, String surname, String email, boolean isActivated) {
    this.username = nick;
    this.password = pass;
    this.name = name;
    this.surname = surname;
    this.email = email;
    this.isActivated = isActivated;
}

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String username, password, name, surname, email;

boolean isActivated;

@OneToMany(targetEntity = Dialogue.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Collection<Dialogue> dialogues = new ArrayList<>();

public Collection<Dialogue> getDialogues() {
    return dialogues;
}

public void setDialogues(Collection<Dialogue> dialogues) {
    this.dialogues = dialogues;
}

public Collection<User> getFriends() {
    return friends;
}

public void setFriends(Collection<User> friends) {
    this.friends = friends;
}

@OneToMany(targetEntity = User.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Collection<User> friends = new ArrayList<>();

@ElementCollection(targetClass = Role.class, fetch = FetchType.EAGER)
@CollectionTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"))
@Enumerated(EnumType.STRING)
private Set<Role> roles;

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public void setUsername(String username) {
    this.username = username;
}

public void setPassword(String password) {
    this.password = password;
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    return null;
}

@Override
public String getPassword() {
    return password;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getSurname() {
    return surname;
}

public void setSurname(String surname) {
    this.surname = surname;
}

public String getEmail() {
    return email;
}

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

public boolean isActivated() {
    return isActivated;
}

public void setActivated(boolean activated) {
    isActivated = activated;
}

public Set<Role> getRoles() {
    return roles;
}

public void setRoles(Set<Role> roles) {
    this.roles = roles;
}

@Override
public String getUsername() {
    return username;
}

@Override
public boolean isAccountNonExpired() {
    return true;
}

@Override
public boolean isAccountNonLocked() {
    return true;
}

@Override
public boolean isCredentialsNonExpired() {
    return true;
}

@Override
public boolean isEnabled() {
    return isActivated();
}

"Больная часть"
@OneToMany(targetEntity = User.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private Collection<User> friends = new ArrayList<>();

public Collection<User> getFriends() {
    return friends;
}

public void setFriends(Collection<User> friends) {
    this.friends = friends;
}

При fetchType Eager выдаёт ошибку
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dialogueRepository' defined in Kejkers.Rgr.repo.DialogueRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Cannot resolve reference to bean 'jpaMappingContext' while setting bean property 'mappingContext'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags: [Kejkers.Rgr.Models.User.dialogues, Kejkers.Rgr.Models.User.friends]

при fetchType LAZY сервер запускается, однако при посещении страницы
@GetMapping("/friends")
public String friends (@AuthenticationPrincipal User user, Model model)
{
    Iterable<User> friends = user.getFriends();
    model.addAttribute("friends",friends);
return "friends";
}

Всё ломается
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/friends.html]")

при поиске проблемы с помощью точки останов выдает такую строчку
Unable to evaluate the expression Method threw 'org.hibernate.LazyInitializationException' exception.

@Transactional пробовал, костыли пробовал.

A: MultipleBagFetchException
Согласно ответу одного из создателей Hibernate, Vlad Mihalcea (https://stackoverflow.com/a/51055523/9978153):
Когда вы ставите fetch = FetchType.EAGER над несколькими @OneToMany полями, вы получаете ошибку MultipleBagFetchException при попытке запросить такую сущность. Это защита от потенциально огромного количества записей, которые придется обработать в рамках запроса из-за двойгого JOIN.
Вам необходимо вернуть fetch = FetchType.LAZY
LazyInitializationException
LazyInitializationException случается, когда вы пытаетесь получить лениво связанные сущности (@OneToMany + FetchType.LAZY), вне сессии. Самый простой способ открыть сессию - использовать @Transactional.
Ваш вопрос содержит упоминание "@Transactional  пробовал, костыли пробовал". Было бы замечательно, если бы вы рассказали, где именно вы пробовали установить @Transactional и какие "костыли" вы пробовали.
Решение 1. Возвращать инициализированных пользователей
Судя по всему, Вы используете Spring Security.
Вам необходимо возвращать полностью инициализированных пользователей из UserDetailsService
Для этого можно просто обратиться к списку друзей в рамках сессии, которая возвращаем Вам пользователя.
Но это решение заставит делать запрос за friends всегда, даже когда это на самом деле не нужно.
Решение 2. Использовать отдельный метод репозитория для получения списка друзей.
Это решение является более простым и не требует глубокого погружения.
Можно создать метод в репозитории, который будет возвращать список друзей для пользователя, и не зависеть от возможностей @ObeToMany.
В таком случае можно применить запрос.
SELECT u from User u WHERE :user in u.friends

P.S. Пока я пытался придумать запрос на HQL, я заметил, что User имеет рекурсивную @OneToMany связь (User имeет ссылку на User в поле friends). Не стоит ли заменить связь на @ManyToMany?


text:
Q: find $x$ in $\mathbb{Z}_{100,000,001}$. I am trying to find $100^{101}$ in $\mathbb{Z}_{100,000,001}$.
What I have done is
$100^4 = 100,000,000 = 1$ in $\mathbb{Z}_{100,000,001}$ (Fermat's Theorem).
So $100^{101} = 100^{25+ 4+ 1} = 1+100 = 101$ in $\mathbb{Z}_{100,000,001}$.
Is that correct?

A: $$100^4 = 10^8 \equiv -1 \pmod{10^8+1}$$
$$100^{101}=100^{4\times 25+1}=100(100^4)^{25}\equiv -100 \pmod{10^8+1}$$


text:
Q: How to do generic queries with Objectify, to get a sample entity of each Kind I have many different Kinds in my app, they are unrelated in the Datastore, but they share a common Java base class which helps me process them generically.   (By generically I mean without regard to their kind, not in the Java 'generics' sense.)
Now I want to perform some tests on one entity from each kind, and I can't figure out how to do it.
I want to do something like this:
Class<? extends MyBaseUnit> cl = getNextKind();
MyBaseUnit bu = (MyBaseUnit) ofy().load().type( cl ).filter( ?? ).first().now();

I don't think there is any such thing as a null filter, and if I just remove the filter() call then first() returns a Ref and I can't seem to do much with that.
I guess I could use a filter of ("id >", 0) for all the kinds with a long id, but what would a similar meaningless filter be for the ones with a string name?
Or maybe there is a better way of doing this?  My ideal would be to retrieve a different entity every time I run the test.

A: In the end I did it the ugly way that I contemplated at the end of my question:
for (KindInfo ki: kinds) {
    BaseUnit bu = null;
    List<? extends BaseUnit> lbu = null;

    if (ki.usesLongKey()) {
        lbu = ofy().load().type( cl ).filter( "id !=", 7).limit(1).list();
    } else {
        lbu = ofy().load().type( cl ).filter( "kn !=", "barf35" ).limit(1).list();
    }
    if ((null == lbu) || (0 == lbu.size())) {
        Log.i( "No entities for type=" + cl.getName() );
    } else {
        bu = (BaseUnit) lbu.get(0);
        runTestsOnSampleEntity( bu );
    }
}

The filters are just made up values ("kn" is the attribute name used by all of my Kinds that use a string key name).
I initially tried to use a filter of ("id !=", 0") since 0 is not a valid id, but this caused a ""java.lang.IllegalArgumentException".


text:
Q: custom inspector CSS copied to stylesheet not being applied on refresh I'm using Edge Inspector to build a CSS class, like:
.blurbs .et_pb_button_module_wrapper {background-color: white; padding: 2em;}

I see these attributes being applied on the page.
If I copy this CSS rule and save it into the WP child theme CSS, I can see the rule is there when I load the stylesheet in the browser.
However, the rule is not being applied on the page.
It is not even present when I select the .blurbs .et_pb_button_module_wrapper element, so although it might be overridden if it was present, there's nothing to override.

<link href="https://divi.dev.insightdesign.com.au/agrimin/wp-content/themes/Divi-Agrimin/style.css" rel="stylesheet"/>
<link href="https://divi.dev.insightdesign.com.au/agrimin/wp-content/themes/Divi/style.css" rel="stylesheet"/>

Information For

Company

          Overview

 More

The element that needs the white background the container of the More button: .blurbs .et_pb_button_module_wrapper
Help appreciated.


text:
Q: Reuse host binaries or share between containers in Docker Consider the following scenario:
There are three independent web applications A, B and C that require an apache server to be run on.
A linux server runs web application A and may act as a Docker host. It is required that the applications B and C are isolated from the linux server and each other. They are therefore realized as two Docker containers, initially created from the same image.
My question updates, and security updates in special.
Do the two Docker containers require a full OS installation image? Can they share the host's apache binary, so security updates of the host's apache could be propagated to the containers automatically?
If this doesn't work: Would I need to install updates for apache on both containers independently, or could I benefit from the fact, that they are based on the same image, and somehow simplify the update process?

A: Docker will not share binaries from the host server that would be missing the point. What docker does have is a layered file system which means two docker images that share a common base will be more space efficient when sharing the same host.
As for patching. If you update the base image, you'll need to rebuild the container images that derive from it. Not a big deal, if you're using a registry to store and distribute images. to update the host server you perform a "pull" operation to update the local images, followed by a container restart.


text:
Q: Stop scrapy from redirecting to country specific domain I am trying to extract data from airbnb.com. But whenever I tried to access that website with .com in its domain, it's redirecting to a domain having .ca.
Here is a code snippet which I think would describe my issue
In [46]: fetch(url)
2021-02-05 09:17:36 [scrapy.downloadermiddlewares.redirect] DEBUG: Redirecting (307) to <GET https://www.airbnb.ca/s/nova/homes?tab_id=home_tab&refinement_paths%5B%5D=%2Fhomes&date_picker_type=calendar&source=structured_search_input_header&search_type=search_query&locale=en&_set_bev_on_new_domain=1612519553_NTk3ZTMyZGU4NzI2> from <GET https://www.airbnb.com/s/nova/homes?tab_id=home_tab&refinement_paths[]=%2Fhomes&date_picker_type=calendar&source=structured_search_input_header&search_type=search_query>

2021-02-05 09:17:37 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.airbnb.ca/s/nova/homes?tab_id=home_tab&refinement_paths%5B%5D=%2Fhomes&date_picker_type=calendar&source=structured_search_input_header&search_type=search_query&locale=en&_set_bev_on_new_domain=1612519553_NTk3ZTMyZGU4NzI2> (referer: None)

Actually, airbnb loads prices for each listing with the domain having .com. I tried various solution like don_redirect etc. but haven't received required response.


text:
Q: ?: operator on sprintf Apparently too much Python or too much of any dynamically typed language is not healthy for a programmer. Anyways, I'm struggling with a C++ exercise and have a quick question about syntax. I couldn't find any source code where this is applied (if possible).
Can I use a statement which includes the ?: operator as a sprintf argument?. This is my no-compling code so you get an idea:
return sprintf("The cosine of %2f %s is %2f", angle, (angleType == "g" ? "degrees" : "radians"), result);

angleType is a value entered by the user specifying if he's entering degrees or radians.
angle is the value for the angle.
result is the actual cosine value.
I wanted to print a message as descriptive as possible so I came up with this.
If this possible?
Thanks!

A: Yes, you can use ?: anywhere an expression is expected.
One of your problems is probably with the condition, angleType == "g". In C and C++, you cannot compare strings like that; you need to use strcmp or something like that. Unless angleType is a std::string, in which case this should just work.
The other problem is that you seem to be expecting sprintf to return a string. Instead, you are responsible for passing it a string, to which it will then write its output. But since this is C++, it's better to use std::string anyway!
If this doesn't solve your problem, post your compiler error message!

A: First problem, take another look at the prototype in sprintf(3):
   int sprintf(char *str, const char *format, ...);

The first argument is a buffer that sprintf(3) writes into. You've given it the format string.
Second problem: angleType == "g" -- string comparisons in C don't work that way. == 'g' would work, if angleType is a char. Or if you're confident you've got a C++ std::string, sure, but this line alone doesn't have that data.

A: I think this is the problem with your code: angleType == "g", if I guess right that angleType is a char*, not an std::string. Try changing it to strcmp(angleType, "g") == 0 and see if it is correct.
I do not see any problem with ?:, its only constraint that both results must be the same type.


text:
Q: Fastest Variable Set in Java I need Structure (Arraylist, LinkedList, etc) that is very fast for this case:
While the structure is not empty  I search the structure for elements that satisfy a condition , lets say k, remove the elements that satisfy k and start over for another condition lets say k+1.
e.g.:
for (int i = 1 ; i <= 1000000; i++) {
  structure.add(i);
}

d = 2;

while (!structure.isEmpty()) {
  for(int boom : structure.clone) {
    if (boom % d == 2) {
      structure.remove(boom);
    }

    d++;
  }
}

A: If the elements are primitives, then the fastest structure will most probably be a specialized primitive collection (e.g., trove). Following references for boxed primitives is a nearly sure cache miss and this probably dominates the costs.
I wouldn't suggest a LinkedList for the same reason: It's dead slow due to cache misses.
If the order is unimportant, than an ArrayList is perfect. Instead of removing an element, replace it by the last one and remove the last array element. This is an O(1) operation and doesn't suffer from the bad spatial locality.
If the order is important, you can build your own ArrayList-like structure. Instead of removing an element, you mark it for removal e.g. in a BitSet or in a boolean[]. Finally you perform the removal in one sweep by moving all elements to their right position and adjusting the length. The optimized loop will most probably look similar to CharMatcher.removeFrom loop.
A simpler solution would be to use an ArrayList and copy all surviving elements to another one. I'd bet it'd beat the LinkedList hands down. As a minor GC-friedly optimization you can work with two lists.

A: LinkedList should be fastest for this case. Use the iterator explicitly (structure.iterator()) and call the remove method of the iterator instead of calling structure.remove(element)!

A: I don't know your exact use case, but here's one note.
If you have your predicates P1 .. PN pre-compiled, available, and if you are not modifying the contents of the collection and if your predicates are not dependent on each other, you might want to create a composite predicate, like bundle up N predicates in some logical order, and then in only one iteration over your collection perform the filtering method.
As for data structure, I'd think if it like this:
If my filtering predicates will be totally arbitrary, then a list should be OK to use.
In some more specific cases with very limited and strict value sets, you might consider a tree-like or a graph-like structure, where you could have some master nodes which would denote that property "property1" has value "value1". In case you wanted to drop all items where "property1" value is "value1" you could tell that master node to remove all his children (and that they should detach themselves from any other parent master nodes they might have).

A:  Sorted List data structure
If you construct the lists yourself you can consider using a sorted data-structure. It will give you best search performance( log n complexity so it is very fast).
 Linked List data structure
LinkedList gives you constant time element removal but random access doesn't have constant complexity (is slow).
You will have to benchmark if a LinkedList or a sorted list would be faster for your scenario.

A: If your elements are ints, I suppose bit set would be the fastest data structure for this task. Iteration would be slightly slower than through array list (even not standard java.util.ArrayList, only primitive specialization), but remove ops cost nearly nothing, while removes from any array list are quite expensive.
Note, you can gain much by working directly with long[] as bit set and performing bitwise operations by hand, because java.util.BitSet is not very performance-focused. But, of cause, start with BitSet.


text:
Q: Долгий ответ (вывод данных) ajax еще плохо знаю js, прошу посмотреть участки кода js и php, и не плеваться, а помочь советом, подсказать где исправить ошибки, что бы ускорить работу скрипта, или же что напрочь убрать.
Это виджет поддержки (знаю про сокеты, но нагрузки на этот модуль пока нет, да и опыта такого тоже), при отправке по клику в виджете сообщения пользователю, сообщение появляеться спустя 1 - 1.5 секунды, что визуально долго, и знаю сайты где чат реализован так же с аяксом, но визуальная отправка моментальная.
Прошу помочь мне с этим вопросом
Всем спасибо!
Код js

Код с контроллера
<?php

class controller_support_supportwidget extends controller
{
function main__widget()
{
    $this->_template = 'support__widget.tpl';

    $user = user::i()->getUser();
    $support_list = model_support::getList($user['id']);

    $this->assign('chat_list', $support_list);
    $this->assign('user', $user);

    model_support::setRead();
}

function sendMessage_widget()
{
    $result2 = false;

    $imager = new imager('support');
    $picture = $imager->process('picture');

    if($picture)
        $result2 = model_support::setMessage('/m/support/'.$picture.'');

    $text = $_POST['body'];
    $result = model_support::setMessage($text);

    if($result || $result2)
    {
        user::i()->setFlash('send_message_success');
    }
    else
    {
        user::i()->setFlash('send_message_error', array('error_code' => $result));
    }
    exit();
}

}
Код с модели модуля
    public static function setMessage($text, $user_id = false, $author_type = 'user', $color = '')
{

    if(!$user_id)
    {
        $user = user::i()->getUser();
        $user_id = $user['id'];
    }
    else
    {
        $user = model_user::getById($user_id);
    }

    $readed = ($author_type == 'user') ? 1 : 0;

    if(trim($text) == '')
        return false;

    $new_message = database::i()->support()->insert(array(
        'body' => $text,
        'user_id' => $user_id,
        'author_type' => $author_type,
        'readed' => $readed,
        'created_at' => time(),
        'additional_color' => $color
    ));

    if($author_type == 'manager')
    {
        $maildata = array(
            'text' => $text
        );

        model_mail_query::add(
            config::i()->get('app/mail_from'),      // from
            $user['login'],                         // to
            'Получен ответ от поддержки',           // subject
            'support',                              // template
            $maildata                               // data
        );
    }

    return $new_message;
}

  <input id="chat-widget-toggle" class="chat-widget-toggle" type="checkbox">

    <svg xmlns="http://www.w3.org/2000/svg" width="64" version="1.1" height="64" viewBox="0 0 64 64" enable-background="new 0 0 64 64">
  <g>
    <path fill="#1D1D1B" d="M28.941,31.786L0.613,60.114c-0.787,0.787-0.787,2.062,0,2.849c0.393,0.394,0.909,0.59,1.424,0.59   c0.516,0,1.031-0.196,1.424-0.59l28.541-28.541l28.541,28.541c0.394,0.394,0.909,0.59,1.424,0.59c0.515,0,1.031-0.196,1.424-0.59   c0.787-0.787,0.787-2.062,0-2.849L35.064,31.786L63.41,3.438c0.787-0.787,0.787-2.062,0-2.849c-0.787-0.786-2.062-0.786-2.848,0   L32.003,29.15L3.441,0.59c-0.787-0.786-2.061-0.786-2.848,0c-0.787,0.787-0.787,2.062,0,2.849L28.941,31.786z"/>
  </g>
</svg>

          Чат Поддержки (тут имя проекта)
          Мы ответим Вам в ближайшее время

          {% if chat_list %}
            {% for chat in chat_list %}

                  {{ processPic(chat.body) }}

              {% endfor %}
            {% else %}

У вас пока нет сообщений

            {% endif %}

        <form class="chat-form" id="chat-form ajaxStart" action="" method="post" enctype="multipart/form-data">

          <textarea id="textInput" type="text" name="body" class="form-control chat-form-input"
               placeholder="Введите Ваше сообщение.." required></textarea>
         <button id="send" title="send message" onclick="send_supportWidget(); return false;" type="submit" class="chat-form-button">
            <svg xmlns="http://www.w3.org/2000/svg" x="0px" y="0px"
                 width="535.5px" height="535.5px"
                 viewBox="0 0 535.5 535.5"
                 style="enable-background:new 0 0 535.5 535.5;">
              <polygon points="0,497.25 535.5,267.75 0,38.25 0,216.75 382.5,267.75 0,318.75"/>
            </svg>
          </button>

               <input type="file" name="picture" class="" style="">

        </form>

    <svg xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 60 60" style="enable-background:new 0 0 60 60;" xml:space="preserve">
    <g>
      <path d="M54.072,2.535L19.93,2.465c-3.27,0-5.93,2.66-5.93,5.93v3.124l26.065-0.054c4.377,0,7.935,3.557,7.935,7.929v21.142   c0,0.634-0.083,1.248-0.224,1.84l3.484,3.833c0.193,0.213,0.464,0.327,0.74,0.327c0.121,0,0.243-0.021,0.36-0.067   c0.386-0.148,0.64-0.52,0.64-0.933v-10h1.07c3.27,0,5.93-2.66,5.93-5.93V8.465C60,5.195,57.34,2.535,54.072,2.535z" />
      <path d="M40.069,13.465L5.93,13.535c-3.27,0-5.93,2.66-5.93,5.93v21.141c0,3.27,2.66,5.93,5.929,5.93H12v10   c0,0.413,0.254,0.784,0.639,0.933c0.118,0.046,0.24,0.067,0.361,0.067c0.276,0,0.547-0.114,0.74-0.327l9.704-10.675l16.626-0.068   c3.27,0,5.93-2.66,5.93-5.93V19.394C46,16.124,43.34,13.465,40.069,13.465z M12,34.449c-2.206,0-4-1.794-4-4s1.794-4,4-4   s4,1.794,4,4S14.206,34.449,12,34.449z M23,34.449c-2.206,0-4-1.794-4-4s1.794-4,4-4s4,1.794,4,4S25.206,34.449,23,34.449z    M34,34.449c-2.206,0-4-1.794-4-4s1.794-4,4-4s4,1.794,4,4S36.206,34.449,34,34.449z" />
    </g>
    </svg>


text:
Q: Stop Asp.Net Core tag helpers formatting numbers I have the situation when the asp-for formats my output, I put 5 but it displays me "5,00":

As I am in France, it puts the comas, and then does not validate the input (because of format I suppose).
Is there a way to stop asp.net formatting my numbers - leave 5 as is, no neeed to add something to it.

<input asp-for="X" class="form-control" />

I added
[DisplayFormat(ApplyFormatInEditMode = false)]
public decimal X { get; set; }

but this does not help.
I need to use decimals in my fields, but why it does put the comas by itself, then says "invalid format"?

A: DisplayFormat is considered when you use Html.DisplayFor, I don't know a way how is possible to enforce a number to be in a specific format it you are not changing it yourself to string, or maybe there is..
Another approach is to change the culture, US or invariant
 public ActionResult Index()
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            Thread.CurrentThread.CurrentUICulture =CultureInfo.InvariantCulture;
            return View();
        }

or in view (not very fancy)
CultureInfo.DefaultThreadCurrentCulture = new CultureInfo.InvariantCulture;
Html.DisplayFor(model => model.whatever)

Still I don't think this solved the decimals problem, it will be 4.00 instead of 4,00
If you don't want decimals, on view model use int instead or decimal