Q:

Geo Spatial Analysis in Pyspark ( Point in a Polygon)

I have a use case where Im given 4 geo spatial Point sets  that represents 4 rectangles . I have a table which has a point( which is just a latitude and longitude ) . My task is to check if the point in the table lies within any of the four rectangles.
This should be done in Pyspark . I tried this using udf's but its taking a long time as the main table contains lot of rows. Could anyone help me on how to efficiently solve this problem in Pyspark.
Right now I have used Shapely to help me with Point and Polygon creations

A:

We can think of the rectangle as space bounded by (min_latitude, max_latitude) and (min_longitude, max_longitude). Let's assume your point-of-interest is x = (lat, lon). Now, for each rectangle you need to check whether min_latitude <=x <= max_latitude and min_longitude <= y <= max_longitude. These can be done using native spark functions, no udf is required. Also, before performing these operations, you can select only required columns (dataframe.select(cols...)) from your original dataframe to discard redundant information.


Q:

When I run the test “ rspec item_container_spec.rb ”In the console, I'll get a warning

  it 'add items into the container' do
    item1 = Item.new('kettle', price: 200)
    item2 = Item.new('kettle', price: 300)
    @box.add_item(item1)
    @box.add_item(item2)
    @box.items.should have(2).items
  end

This team might mistake? " @box.items.should have(2).items  " .
In the console, I'll get a warning
**E:\work\storeapp\spec>rspec item_container_spec.rb
F

Failures:

  1) ItemContainer add items into the container
     Failure/Error: @box.items.should have(2).items
     NoMethodError:
       undefined method `have' for #<RSpec::ExampleGroups::ItemContainer:0x2419908>
     # ./item_container_spec.rb:27:in `block (2 levels) in <top (required)>'

Finished in 0 seconds (files took 0.23234 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./item_container_spec.rb:22 # ItemContainer add items into the container**

where is my mistake?

A:

I bet that you have installed rspec 3.0.
The have family of matchers was deprecated in RSpec 2.99 and has been moved to a separate rspec-collection_matchers gem as of RSpec 3.0.
Take a look here.


Q:

Javascript onclick not working on radio button

I have a problem with javascript. I have downloaded a rating star plugin , this one to be exact: http://www.fyneworks.com/jquery/star-rating/#tab-Testing
I have multiple things to rate on one page, so i thought i could use an onclick to send it to a function, that sends it to my database with ajax. The problem is, when a rating star is clicked nothing happens, ive tried it on a regular submit button and the function gets executed.
Here is the code :
            <script type="text/javascript">
               function postform(){
                           alert('Thing is clicked');
                       };
            </script>

And the star is actually a radio button:
<input name="adv1" type="radio" class="star {split:4}" value="0.50" onclick="postform()"/>

I can't see what is wrong with the code, because when i test it on a regular button like this :
 <input type="submit" value="testbutton" onclick="postform()"/>

It gives me the alert Thing is Clicked.
Somehow the star doesn't like the onclick stuff..
Ive tested it in IE, Chrome and FF, nothing ever happens
could someone help me out here?
Thanks alot!
Edit:
As requested by Lukas , i have this in my head :
<script type='text/javascript' src='jquery.min.js'></script>
<script src='jquery.MetaData.js' type="text/javascript"></script>
<script src='jquery.rating.js' type="text/javascript"></script>

A:

That library is handling the onclick event of the radio button for you, so you cannot handle it by adding an attribute onclick to the input element.
According to their documentation you need to put some code like this in a script:
$('.auto-submit-star').rating({
    callback: function(value, link){
        alert(value);
    }
});

Then add the class auto-submit-star to the class list of your radio button:
<input name="adv1" type="radio" class="auto-submit-star {split:4}" value="0.50" onclick="postform()"/>


Q:

Is this possible to list available alphabet of the current locale in GWT?

Is this possible to list available alphanet of the current locale in GWT?

A:

An idea is to define all possible alphabets in a Constants implementation:
@DefaultStringArrayValue("A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z")
String[] alphabet();


Q:

What's the best way to kill prometheans?

In Halo 5, is there any "best" way to kill prometheans? With the dog-like ones, it seems like headshots are effective. But with the soldiers and knights, it seems like headshots and bodyshots are equally effective (in contrast to fighting covenant, where headshots knock-back the enemies and deal more damage). Am I wrong about this? It's very hard for me to tell because there doesn't seem to be knock-back with Prometheans.
What's the optimal way to kill Prometheans of each type?

A:

The information from my answer comes from personal experience and the Halo wiki.
Promethean Crawlers:
Crawlers, as you mentioned, will easily die with a single headshot and that is definitely the best strategy when possible. If you don't have a weapon effective at delivering headshots then a rapid firing weapon or shotgun is a good alternative since they are pretty resistant to damage.
Promethean Watchers:
They don't have any specific weak points however, due to their general location in battle (at distance and supported by the rest of the prometheans), it is best to use a precision weapon against them in order to take away the support the other units are receiving while staying far enough away so as not to get horribly shot up.
Promethean Knights:
First off, kill any watchers around them if possible due to their support abilities. As you noticed, these big fellows do not seem to care where they are getting shot at, but this is only partially true. The reason headshots do not seem to be effect is because of the big metal plates they have in front of their face. Their face will always be protected until you manage to take their shields down. Once their shields are down the metal will expose their glowing face and a single precision shot should kill it.
Alternatively the shotguns and gravity hammer are really good weapons against them, needing only a few shots (or 1-2 swings) no matter the difficulty.
Promethean Soldiers:
Soldiers have good melee resistance but, aside from that, any weapon will be decent at taking them down. Similarly to knights, taking down their shields will expose the glowey stuff underneath which will provide critical damage.
Note: As with every enemy in Halo (except the flood) a good smack on the back is always a good way to immediately kill anything (except the watcher) on this list.


Q:

Can't figure out the error in this simple Java code

public class Test {
    class Foo {
        int frob() {
            return 7;
        }
    }

    class Bar extends Foo {
        @Override
        int frob() {
            return 8;
        }
    }

    class Baz extends Foo {
        @Override
        int frob() {
            return 9;
        }
    }

    public static int quux(Bar b) {
        return b.frob();
    }

    public static void main(String[] args) {
        System.out.println(quux(new Bar()));//this line gives non-static variable this cannot be referenced from a static context
    }

}

A:

You can fix this by declaring the nested classes as static, OR by instantiating Bar in the context of an instance of Test.
It fails because (the non-static) Bar must be instantiated in the context of an existing Test class instance; since main is static, there is no such beast.

A:

public static void main(String[] args) {
    Test test = new Test();
    System.out.println(quux(test.new Bar()));
}


Q:

Is it possible to route requests to different applications via Content-Type?

I'm designing a JSON API, and I'd like to version the API using content negotiation of some kind. I'm currently planning on using Vendor MIME Types to do this.
While I can definitely do this at the application level, I'm thinking it would be best to make this happen at the HTTP server level. Is this possible with Apache or nginx?
The Content-Type would look something like: application/vnd.vendorname-v1+json
or possibly using parameters: application/vnd.vendorname+json;v=1

A:

Nginx's idiomatic approach to this kind of problems is via map. Please see my answer at StackOverflow.
Basically, you define a map in http section
map $any_variable $my_upstream {
  # Default value:
  default upstream1;

  # Exact match:
  application/vnd.vendorname+json;v=1 upstream2;

  # Regexp:
  ~^application.*vnd.vendorname-v1\+json upstream3;
}

You may mix exact matches and regexps in one map.
Then you simply use $my_upstream in you server or location section(s):
location / {
  proxy_pass http://$my_upstream$uri;
}

Nginx evaluates map variables lazily, only once (per request) and when you are using them.


Q:

Which dependencies are required to import `io.mockk.every` when writing Kotlin tests with Mockk?

I'm trying to write a test based on just testCompile group: 'io.mockk', name: 'mockk', version: '1.7.15' but in the code below:
import io.mockk.every
import io.mockk.any
import io.mockk.Runs
import io.mockk.impl.annotations.MockK
import io.mockk.junit5.MockKExtension

@ExtendWith(MockKExtension::class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
internal class ConfigDistributorTest {
        @MockK
        lateinit var configService: ...

        @MockK
        lateinit var centralisedConfigRegisterService: ...

            val configDistributor =  ConfigDistributor(centralisedConfigRegisterService, configService)

            @Test
            fun shouldDistributeConfigToComponents(){
                every {
                    configService.readConfig(any())
                } just Runs
            }
        }

although Runs, MockK and MockKExtension are successfully imported,
the every and any() are not available. Is io.mockk.any the correct import statement and which other dependency is required to use them?

A:

First you need to import every. import io.mockk.every is the correct way to do it. Inside of every any is automatically imported, so you don't need to do that. Other things looks fine
Please invalidates caches, re-import project. Probably you have some issues with IDE.


Q:

TypeError : 'NoneType' object not callable Python with BeautifulSoup XML

I have the following XML file :
<user-login-permission>true</user-login-permission>
        <total-matched-record-number>15000</total-matched-record-number>
        <total-returned-record-number>15000</total-returned-record-number>
        <active-user-records>
            <active-user-record>
                <active-user-name>username</active-user-name>
                <authentication-realm>realm</authentication-realm>
                <user-roles>Role</user-roles>
                <user-sign-in-time>date</user-sign-in-time>
                <events>0</events>
                <agent-type>text</agent-type>
                <login-node>node</login-node>
             </active-user-record>

There are many records
I'm trying to get values from tags and save them in a different text file using the following code :
soup = BeautifulSoup(open("path/to/xmlfile"), features="xml")

with open('path/to/outputfile', 'a') as f:
    for i in range(len(soup.findall('active-user-name'))):
        f.write ('%s\t%s\t%s\t%s\n' % (soup.findall('active-user-name')[i].text, soup.findall('authentication-realm')[i].text, soup.findall('user-roles')[i].text, soup.findall('login-node')[i].text))

I get the error TypeError : 'NoneType' object not callable Python with BeautifulSoup XML for line :  for i in range(len(soup.findall('active-user-name'))):
Any idea what could be causing this?
Thanks!

A:

There are a number of issues that need to be addressed with this, the first is that the XML file you provided is not valid XML - a root element is required.
Try something like this as the XML:
<root>
    <user-login-permission>true</user-login-permission>
    <total-matched-record-number>15000</total-matched-record-number>
    <total-returned-record-number>15000</total-returned-record-number>
    <active-user-records>

        <active-user-record>
            <active-user-name>username</active-user-name>
            <authentication-realm>realm</authentication-realm>
            <user-roles>Role</user-roles>
            <user-sign-in-time>date</user-sign-in-time>
            <events>0</events>
            <agent-type>text</agent-type>
            <login-node>node</login-node>
        </active-user-record>

    </active-user-records>
</root>

Now onto the python. First off there is not a findall method, it's either findAll or find_all. findAll and find_all are equivalent, as documented here
Next up I would suggest altering your code so you aren't making use of the find_all method quite so often - using find instead will improve the efficiency, especially for large XML files. Additionally the code below is easier to read and debug:
from bs4 import BeautifulSoup

xml_file = open('./path_to_file.xml', 'r')

soup = BeautifulSoup(xml_file, "xml")

with open('./path_to_output_f.txt', 'a') as f:
    for s in soup.findAll('active-user-record'):
        username = s.find('active-user-name').text
        auth = s.find('authentication-realm').text
        role = s.find('user-roles').text
        node = s.find('login-node').text
        f.write("{}\t{}\t{}\t{}\n".format(username, auth, role, node))

Hope this helps. Let me know if you require any further assistance!


Q:

Issue with Scope_identity() when used with TransactionScope()

I am using TransactionScope() such that ..
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "proc_insertlot"; cmd.Connection = sqlconn;
da = new SqlDataAdapter(cmd);

    for (int i = 0; i < 3 i++)
    {
          da.Fill(ds);//this insert a row in a table which has identity column
          LotId = ds.Tables[1].Rows[0][0].ToString();//always return same identityvalue
    }

//---TransactionScope commit
It seems that unless i commit the transaction, scope_identity wont increment. In this example scope_identity will return the same value all the 3 times. How do you I solve this?
SQL:
ALTER  procedure proc_insertlot
@AuctionId int=0,
@Title varchar(300)='',
@Description varchar(4000)='',
@lottype varchar(20)='',
@ImproveBidBy varchar(20)='',
@BidDecrement varchar(20)='',
@FrontBuffer varchar(20)='',
@BackBuffer varchar(20)='',
@AttachmentId varchar(30)='',
@MkrId varchar(11)=''  ,
@file_uploadlot varchar(30) =''
as
      set nocount on
insert into tbl_lots(AuctionId,Title,Description,lottype,ImproveBidBy,BidDecrement,FrontBuffer,BackBuffer,AttachmentId,MkrId,MkrDt)
 values (@AuctionId,@Title,@Description,@lottype,@ImproveBidBy,@BidDecrement,@FrontBuffer,@BackBuffer,@AttachmentId,@MkrId,GETDATE())

select @@Identity as lotid

A:

I think it will work. Changing Rows[0][0] -> Rows[i][0]
for (int i = 0; i < 3 i++)
{
      da.Fill(ds);//this insert a row in a table which has identity column
      LotId = ds.Tables[1].Rows[i][0].ToString();//will now return required identityvalue
}

See if it works or not.
Update
Got your problem. Issue is that
LotId = ds.Tables[1].Rows[0][0].ToString(); will  always return the last most value of scope_identity as soon as scope is committed. Instead you can try @@Identity. Also check if you have AutoIncrement enabled with PK. Generally we use AutoIncrement Columns as PK.
e.g. courtsey : Guffa.
    create procedure proc_insertlot
    as
    set nocount on
declare @id as int
    insert into SomeTable (
      SomeField
    ) values (
      42
    )

    SET @Id=@@Identity
    SELECT @ID


Q:

How to draw a thermometer in an android activity?

I am creating a device management app. I want to show a thermometer in an activity and update the temp value with real time data. i got the real time data part, but i have no idea how to draw a thermometer. Are there any libraries i can use for my problem?

A:

There is no thermometer object in Android.
You will need to draw it yourself with a custom object and an onDraw method.
Or trying with multiple image and a relativelayout.


Q:

URLClassLoader and accessibility of package-private methods

I have a class Formula, located in package javaapplication4, which I load with a URLClassLoader. However, when I call it from another class Test1, located in the same package, I can't access its methods that have a default access modifier (I can access public methods).
I get the following exception:

java.lang.IllegalAccessException: Class javaapplication4.Test1 can not access a member of class javaapplication4.Formula with modifiers ""

How can I access package-private methods of a class loaded at runtime from the same package?
I suppose it is a problem with using a different class loader, but not sure why (I have set the parent of the URLClassLoader).
SSCCE reproducing the issue (Windows paths) - I suppose the issue is in the loadClass method:
public class Test1 {

    private static final Path TEMP_PATH = Paths.get("C:/temp/");

    public static void main(String[] args) throws Exception {
        String thisPackage = Test1.class.getPackage().getName();
        String className = thisPackage + ".Formula"; //javaapplication4.Formula
        String body = "package " + thisPackage + ";   "
                    + "public class Formula {         "
                    + "    double calculateFails() {  "
                    + "        return 123;            "
                    + "    }                          "
                    + "    public double calculate() {"
                    + "        return 123;            "
                    + "    }                          "
                    + "}                              ";

        compile(className, body, TEMP_PATH);
        Class<?> formulaClass = loadClass(className, TEMP_PATH);

        Method calculate = formulaClass.getDeclaredMethod("calculate");
        double value = (double) calculate.invoke(formulaClass.newInstance());
        //next line prints 123
        System.out.println("value = " + value);

        Method calculateFails = formulaClass.getDeclaredMethod("calculateFails");
        //next line throws exception:
        double valueFails = (double) calculateFails.invoke(formulaClass.newInstance());
        System.out.println("valueFails = " + valueFails);
    }

    private static Class<?> loadClass(String className, Path path) throws Exception {
        URLClassLoader loader = new URLClassLoader(new URL[]{path.toUri().toURL()}, Test1.class.getClassLoader());
        return loader.loadClass(className);
    }

    private static void compile(String className, String body, Path path) throws Exception {
        List<JavaSourceFromString> sourceCode = Arrays.asList(new JavaSourceFromString(className, body));

        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
        fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(path.toFile()));
        boolean ok = compiler.getTask(null, fileManager, null, null, null, sourceCode).call();

        System.out.println("compilation ok = " + ok);
    }

    public static class JavaSourceFromString extends SimpleJavaFileObject {
        final String code;

        JavaSourceFromString(String name, String code) {
            super(URI.create("string:///" + name.replace('.', '/') + JavaFileObject.Kind.SOURCE.extension),
                    JavaFileObject.Kind.SOURCE);
            this.code = code;
        }

        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return code;
        }
    }
}

A:

A class at runtime is identified by both its fully qualified name and its ClassLoader.
For example, when you test two Class<T> objects for equality, if they have the same canonical name but were loaded from different ClassLoaders, they won't be equal.
For two classes to belong to the same package (and in turn being able to access package-private methods), they need to be loaded from the same ClassLoader too, which is not the case here. In fact Test1 is loaded by the system classloader, while the Formula is loaded by the URLClassLoader created inside loadClass().
If you specify a parent loader for your URLClassLoader in order to make it load Test1, still two different loaders are used (you can check it by asserting loaders equality).
I don't think you can make the Formula class loaded by the same Test1 ClassLoader (you'd have to use a well-known path and put it on the CLASSPATH), but I found a way to do the opposite: loading another instance of Test1 in the ClassLoader used for loading the formula. This is the layout in pseudocode:
class Test1 {

  public static void main(String... args) {
    loadClass(formula);
  }

  static void loadClass(location) {
    ClassLoader loader = new ClassLoader();
    Class formula = loader.load(location);
    Class test1 = loader.load(Test1);
    // ...
    Method compute = test1.getMethod("compute");
    compute.invoke(test1, formula);
  }

  static void compute(formula) {
    print formula;
  }
}

Here is the pastebin. A couple of notes: I specifed a null parent for the URLClassLoader to avoid the issue listed above, and I manipulated strings to achieve the purpose - but don't know how robust this approach can be in other deployment scenarios. Also, the URLCLassLoader I used only searches in two directories to find class definitions, not all the entries listed in the CLASSPATH

A:

The answer is:
In the sun.reflect.Reflection package there is a method called isSameClassPackage (the actual signature is  private static boolean isSameClassPackage(ClassLoader arg0, String arg1, ClassLoader arg2, String arg3);). This method is responsible for deciding whether two classes belong to the same package or not.
The first check this method is doing that it compares arg0 and arg2, (the two classloaders) if they are different, it returns false.
So, if you use different classloaders for the two classes, it will not match.
EDIT:
The full call chain (on request) is:
Method.invoke()
Method.checkAccess() -- fallback to the real check
Method.slowCheckMemberAccess()   -- first thing to do to call
Reflection.ensureMemberAccess()  -- check some nulls, then
Reflection.verifyMemberAccess()  -- if public, it,'s OK, otherwise check further
Reflection.isSameClassPackage(Class, Class) -- get the class loaders of 2 classes
Reflection.isSameClassPackage(ClassLoader, String, ClassLoader, String)

A:

I found the explanation in the JVM specification 5.4.4 (emphasis mine):

A field or method R is accessible to a class or interface D if and only if any of the following conditions are true:

[...]
R is either protected or has default access (that is, neither public nor protected nor private), and is declared by a class in the same runtime package as D.

And the runtime package is defined in the specs #5.3:

The runtime package of a class or interface is determined by the package name and defining class loader of the class or interface.

Bottom line: this is the expected behaviour.


Q:

Proving that $\int_0^\infty\frac{J_{2a}(2x)~J_{2b}(2x)}{x^{2n+1}}~dx~=~\frac12\cdot\frac{(a+b-n-1)!~(2n)!}{(n+a+b)!~(n+a-b)!~(n-a+b)!}$

How could we prove that $$\int_0^\infty\frac{J_{2a}(2x)~J_{2b}(2x)}{x^{2n+1}}~dx~=~\frac12\cdot\frac{(a+b-n-1)!~(2n)!}{(n+a+b)!~(n+a-b)!~(n-a+b)!}$$ for $a+b>n>-\dfrac12$ ?

Inspired by this question, I sought to find $($a justification for$)$ the closed form expressions of
the following two integrals: $~\displaystyle\int_0^\infty\frac{J_A(x)}{x^N}~dx~$ and $~\displaystyle\int_0^\infty\frac{J_A(x)~J_B(x)}{x^N}~dx.~$ For the former,
we have $~\displaystyle\int_0^\infty\frac{J_{2k+1}(2x)}{x^{2n}}~dx~=~\frac12\cdot\frac{(k-n)!}{(k+n)!}~,~$ for $k>n>\dfrac14~,~$ which I was ultimately
able to “justify” $($sort of$)$ in a highly unorthodox manner, using a certain trigonometric integral  expression for the Bessel function, and then carelessly $($and shamelessly$)$ exchanging the order  of integration. Unfortunately, even such underhanded tricks have failed me when attempting  to approach the latter. Can anybody here help me ? Thank you !

A:

Using the product cited above, viz.
\begin{align}
J_{\mu}(x) \, J_{\nu}(x) &= \sum_{n=0}^{\infty} \frac{(-1)^{n} \, \Gamma(2n+\mu+\nu+1) \, \left(\frac{x}{2}\right)^{2n+\mu+\nu}}{n! \, \Gamma(\mu+\nu+n+1) \, \Gamma(\mu+n+1) \, \Gamma(\nu+n+1)} \\
\implies  \frac{J_{\mu}(\sqrt x) \, J_{\nu}(\sqrt x)}{x^{\mu/2+\nu/2}} &= \sum_{n=0}^{\infty} \frac{(-1)^{n} \, \Gamma(2n+\mu+\nu+1) \, x^n}{2^{2n+\mu+\nu} n! \, \Gamma(\mu+\nu+n+1) \, \Gamma(\mu+n+1) \, \Gamma(\nu+n+1)} \\
\end{align}
we can invoke Ramanujan's Master Theorem, to get
\begin{align}
\int_0^\infty \frac{J_{\mu}(\sqrt x) \, J_{\nu}(\sqrt x)}{x^{\mu/2+\nu/2}} x^{s-1}\,dx = \Gamma(s) \frac{\Gamma(-2s+\mu+\nu+1)}{2^{-2s+\mu+\nu}\, \Gamma(\mu+\nu-s+1) \, \Gamma(\mu-s+1) \, \Gamma(\nu-s+1)}
\end{align}
If $x=4 u^2 \implies dx = 8u\,du$, the LHS becomes
\begin{align}
2^{2s+1-\mu-\nu}\int_0^\infty J_{\mu}(2u) \, J_{\nu}(2u) u^{2s-\mu-\nu-1}\,du
\end{align}
Therefore,
\begin{align}
\int_0^\infty J_{\mu}(2u) \, J_{\nu}(2u) u^{2s-\mu-\nu-1}\,du = \frac{\Gamma(s) \Gamma(-2s+\mu+\nu+1)}{2\, \Gamma(\mu+\nu-s+1) \, \Gamma(\mu-s+1) \, \Gamma(\nu-s+1)} \\
\int_0^\infty J_{2\mu}(2u) \, J_{2\nu}(2u) u^{2s-2\mu-2\nu-1}\,du = \frac{\Gamma(s) \Gamma(-2s+2\mu+2\nu+1)}{2\, \Gamma(2\mu+2\nu-s+1) \, \Gamma(2\mu-s+1) \, \Gamma(2\nu-s+1)}
\end{align}
Set $s=\mu+\nu-n$.
\begin{align}
\int_0^\infty \frac{J_{2\mu}(2u) \, J_{2\nu}(2u)}{u^{2n+1}}\,du &=
\frac{\Gamma(\mu+\nu-n) \Gamma(2n+1)}{2\, \Gamma(\mu+\nu+n+1) \, \Gamma(-\mu+\nu+n+1) \, \Gamma(\mu-\nu+n+1)} \\
&= \frac{(\mu+\nu-n-1)!(2n)!}{2(\mu+\nu+n)!(-\mu+\nu+n)!(\mu-\nu+n)!}
\end{align}
This is your solution.

A:

To save from typing a result a highlight will be listed for now.

The integral in question is a reduction of the more general integral
\begin{align}
\int_{0}^{\infty} \frac{J_{\mu}(at) \, J_{\nu}(bt)}{t^{\lambda}} \, dt = \frac{b^{\nu} \Gamma\left( \frac{\mu + \nu - \lambda +1}{2}\right)}{2^{\lambda} \, a^{\nu - \lambda +1} \, \Gamma\left( \frac{\lambda + \mu - \nu +1}{2} \right) } \, {}_{2}F_{1}\left( \frac{\mu+\nu-\lambda+1}{2}, \frac{\nu-\lambda-\mu+1}{2}; \nu+1; \frac{b^{2}}{a^{2}} \right).
\end{align}
When $\mu \rightarrow 2 \mu$, $\nu \rightarrow 2 \nu$, $a=b=2$, $\lambda = 2n+1$ the result is obtained
A method to obtain the above listed result is to consider the integral as
\begin{align}
\int_{0}^{\infty} \frac{J_{\mu}(at) \, J_{\nu}(bt)}{t^{\lambda}} \, dt = \lim_{s \rightarrow 0} \, \int_{0}^{\infty} e^{-s t} \, t^{-\lambda} \, J_{\mu}(at) \, J_{\nu}(bt) \, dt
\end{align}
See G. N. Watson's Bessel function Book section 13.4, p.401

Edit:
The product of two Bessel functions, as required by this problem, is
\begin{align}
J_{\mu}(x) \, J_{\nu}(x) = \sum_{n=0}^{\infty} \frac{(-1)^{n} \, \Gamma(2n+\mu+\nu+1) \, \left(\frac{x}{2}\right)^{2n+\mu+\nu}}{n! \, \Gamma(\mu+\nu+n+1) \, \Gamma(\mu+n+1) \, \Gamma(\nu+n+1)}
\end{align}
When $x = 2t$ it is seen that
\begin{align}
\int_{0}^{\infty} e^{-st} \, t^{- \lambda} \, J_{\mu}(2t) \, J_{\nu}(2t) \, dx = \sum_{n=0}^{\infty} \frac{(-1)^{n} \, \Gamma(2n+\mu+\nu+1) \, \Gamma(2n+\mu+\nu-\lambda+1) \, \left(\frac{1}{s}\right)^{2n+\mu+\nu-\lambda+1}}{n! \, \Gamma(\mu+\nu+n+1) \, \Gamma(\mu+n+1) \, \Gamma(\nu+n+1)}
\end{align}
Reducing this series and a possible transformation of the resulting hypergeometric series along with the limiting value for $s$ will yield the desired result.

A:

Note: Here is an outline of an alternate proof, which could be helpful.
In section $21$ in Bessel Functions and Their Applications B.G. Korenev introduces the so-called discontinuous integrals of Weber-Sonin-Schafheitlin
\begin{align*}
\int_0^{\infty}\frac{J_\mu(at)J_\nu(bt)}{t^\lambda}\,dt
\end{align*}
He notes, that some special cases of these integrals were calculated by Weber; for all values of the parameters $\lambda,\mu,\nu$ such that this integral converges it has been calculated by Sonin; Schafheitlin in his investigations has noted that at $a=b$ this integral has a discontinuity.
Korenev provides in his book a summary of the main points of the proof and refers at the end of the section to volume II of H. Bateman's classic Higher Transcendental Function for more details.
The relevant part in volume II  is section $7.7.4$ The discontinuous integral of Weber and Schafheitlin. We find in

[H. Bateman] Volume II, Section $7.7.4$:
We shall now investigate the integral
  \begin{align*}
\int_0^{\infty}\frac{J_\mu(at)J_\nu(bt)}{t^\rho}\,dt
\end{align*}
  in which are $a,b$ are positive real. It turns out that even when the integral converges for all positive $a$ and $b$, its analytic expression is different, according as $a$ is smaller, equal to, or larger than $b$. The results are
\begin{align*}
\int_0^\infty&\frac{J_\mu(at)J_\nu(bt)}{t^\rho}\,dt\\
&=\frac{a^{\mu}\Gamma\left(\frac{1}{2}+\frac{1}{2}\nu+\frac{1}{2}\mu-\frac{1}{2}\rho\right)}
{2^\rho b^{\mu-\rho+1}\Gamma(\mu+1)
\Gamma\left(\frac{1}{2}+\frac{1}{2}\nu+\frac{1}{2}\rho-\frac{1}{2}\mu\right)}\tag{1}\\
&\quad\cdot {}_{2}F{_1}\left(\frac{1}{2}+\frac{1}{2}\nu+\frac{1}{2}\mu-\frac{1}{2}\rho,\frac{1}{2}+\frac{1}{2}\mu-\frac{1}{2}\nu-\frac{1}{2}\rho;\mu+1;\frac{a^2}{b^2}\right)\\
&\\
&\Re(\nu+\mu-\lambda+1)>0,\quad \Re(\rho)>-1,\quad0<a<b
\end{align*}
with a corresponding expression for $0<b<a$ [interchange $a$ and $b$] and
\begin{align*}
\int_0^\infty&\frac{J_\mu(at)J_\nu(at)}{t^\rho}\,dt\tag{2}\\
&=\frac{{\left(\frac{1}{2}a\right)}^{\rho-1}
\Gamma(\rho)
\Gamma\left(\frac{1}{2}+\frac{1}{2}\nu+\frac{1}{2}\mu-\frac{1}{2}\rho\right)
}{2
\Gamma\left(\frac{1}{2}+\frac{1}{2}\nu+\frac{1}{2}\rho-\frac{1}{2}\mu\right)
\Gamma\left(\frac{1}{2}+\frac{1}{2}\nu+\frac{1}{2}\rho+\frac{1}{2}\mu\right)
\Gamma\left(\frac{1}{2}-\frac{1}{2}\nu+\frac{1}{2}\rho+\frac{1}{2}\mu\right)
}\\
&\\
&\qquad\qquad\qquad\Re(\nu+\mu+1)>\Re(\rho)>0,\quad a>0
\end{align*}

Note, that substituting in (2)
\begin{align*}
a\rightarrow 2,\quad t\rightarrow x,\quad \mu\rightarrow2a,\quad \nu\rightarrow2b,\quad \rho\rightarrow2n+1
\end{align*}
we obtain
\begin{align*}
\int_0^\infty&\frac{J_{2a}(2x)J_{2b}(2x)}{x^{2n+1}}\,dx\tag{3}\\
&=\frac{1}{2}\frac{
\Gamma(2n+1)
\Gamma\left(b+a-n\right)
}{
\Gamma\left(b+n-a+1\right)
\Gamma\left(b+n+a+1\right)
\Gamma\left(-b+n+a+1\right)
}
\end{align*}
corresponding to OPs expression.
In order to proof the formulae above Bates continues as following

([Bates] adapted:) We use in the integrand of (1) a generalization of Neumann's formula,
  \begin{align*}
J_{\mu}(at)J_{\nu}(bt)=\frac{1}{\pi}(2t)^{\mu+\nu}&a^\mu b^\nu
\int_{-\frac{1}{2}\pi}^{\frac{1}{2}\pi}e^{i\theta(\mu-\nu)}\left(\frac{\cos \theta}{\lambda t}\right)^{\mu+\nu}
J_{\mu+\nu}(\lambda t) \,d\theta\tag{4}\\
&\\
\Re(\mu+\nu)>-1,&\quad\lambda=\left(2\cos\theta\left(a^2e^{i\theta}+b^2e^{-i\theta}\right)\right)^\frac{1}{2}
\end{align*}
  interchange the order of integration, evaluate the integral with respect to $t$ by
  \begin{align*}
\int_{0}^{\infty}J_\mu(at)t^{\rho -1}\,dt&=
2^{\rho -1}a^{-\rho}\frac{\Gamma\left(\frac{1}{2}\mu+\frac{1}{2}\rho\right)}{\Gamma\left(1+\frac{1}{2}\mu-\frac{1}{2}\rho\right)}
\tag{5}\\
&\\
-\Re (\mu)&<\Re (\rho)<3/2,\quad a>0
\end{align*}
  and obtain
  \begin{align*}
\int_0^{\infty}&\frac{J_{\mu}(at)J_{\nu}(bt)}{t^{\rho}}\,dt=
\frac{1}{\pi}a^{\mu}b^{\nu}2^{\frac{1}{2}\mu+\frac{1}{2}\nu-\frac{1}{2}\rho-\frac{1}{2}}
\frac{\Gamma\left(\frac{1}{2}\mu+\frac{1}{2}\nu-\frac{1}{2}\rho+\frac{1}{2}\right)}
{\Gamma\left(\frac{1}{2}\mu+\frac{1}{2}\nu+\frac{1}{2}\rho+\frac{1}{2}\right)}\\
&\qquad\cdot\int_{-\frac{1}{2}\pi}^{\frac{1}{2}\pi}e^{i\theta(\mu-\nu)}\left(\cos \theta\right)^{\frac{1}{2}(\mu+\nu+\rho-1)}
\left(a^2e^{i\theta}+b^2e^{-i\theta}\right)^{\frac{1}{2}(\rho-\mu-\nu-1)}\,d\theta
\end{align*}
  But the integrand on the right-hand side is expressible as a hypergeometric function ${}_2F_1$, compare volume I, 2.4(11)
  and we immediately obtain the expressions (1) and (2) according as $b>a$ or $b=a$.

Please note, it is more an outline of a proof since some details are omitted. But it's hopefully useful for further study.

Hint: When looking for an answer, I also found in chapter $4$, Bessel Functions and Confluent Hypergeometric Functions in Special Functions by J. Andrews, etal.

Exercise 15: Show that when $a=b$ in Exercise $14$, the result is
  \begin{align*}
 \int_0^{\infty}\frac{J_{\alpha-\beta}(at)-J_{\gamma-1}(at)}{t^{\gamma-\alpha-\beta}}\,dt
 &=\frac{(a/2)^{\gamma-\alpha-\beta-1}\Gamma(\gamma-\alpha-\beta)\Gamma(\alpha)}
 {2\Gamma(1-\beta)\Gamma(\gamma-\alpha)\Gamma(\gamma-\beta)}
\end{align*}
  provided that $\Re (\alpha)>0$ and $\Re( \gamma-\alpha-\beta) > 0$.
In Exercise $14$ which is a more general variant of the integral above there is a also reference pointing to Watson [1944] section 13.4, as we already now from the answer of @Leucippus. In fact the expression in Exercise $15$ is stated as formula (1) on p. $403$ in Watsons book.

So, it could be worthwile to read chapter $4$ about Bessel functions in J. Andrews's book. It consists of roughly $40$ pages, which provides all knowledge necessary to fully grasp Watson's proof.


Q:

JavaScript - Add New Row to Table Using AppendChild()

For context, I have the Bootstrap CDN linked, but i could not copy/paste here for some reason.
When I am running this code, the first submit creates a table row with the id='masterTable', but every time I click submit afterwards the program just writes onto the same table row instead of creating a new one.
I would like to create a new table row each time submit is clicked, but I am stumped here. Any ideas?
<!DOCTYPE html>

<link>
</link>

<select id="ddlViewBy">
<option value="0310">XXXX-10</option>
<option value="4610" selected="selected">XXXX-10</option>
<option value="4610">XXXX-10</option>
</select>

<form>

Hand Trucks
<input type="text" class="form-control" id="handtrucks" placeholder="Enter
number of Hand Trucks.">

  Furniture Pads
<input type="text" class="form-control" id="furniture" placeholder="Enter
number of Furniture Pads.">

<button type="submit" onClick='addLocation(); return false;' id='button'
class="btn btn-primary">Submit</button>
</form>

A:

Your problem is you are adding to
 element  without
.
And I suggest you to create a simple string of your html-code instead of adding so many variables like this:
let row = document.createElement('tr');
let html = '' + value + '	' + value1 + '	' + value2 + '	';
row.innerHTML = html;
masterList.appendChild(row);


Q:

How to make use Task.WaitAll with async method using C#

I have used Task.WaitAll inside an async method in my HomeController, but it is not waiting to complete  execution of the async methods. What did I do wrong here? Instead of waiting, it immediately goes to the next statement.
HomeController.cs:
private List<Task> taskList = new List<Task>();

public ActionResult Index()
{
    for (i=0; i<5; i++)
    {
        SendMessages();
    }

    Task.WaitAll(taskList.ToArray());
    // call demo method
}

private async Task SendMessages()
{
    var task = Task.Factory.StartNew(() => ProcessMessages()
    taskList.Add(task);
}

private async Task ProcessMessages()
{
    while (run for 10 minutes)
    {
        // data save
    }
}

I have added a Task into taskList and used Task.WaitAll(taskList.ToArray()); to wait for all tasks to complete, then call demo method. But instead of waiting and executing the whole loop, it immediately goes down after Task.WaitAll(taskList.ToArray()); and executes call demo method. Why is this?

A:

Task.Factory.StartNew should not be used to launch asynchronous operations, since it does not unwrap the returned Task, and instead returns a new Task that completes as soon as the asynchronous operation launches (or, more precisely, completes its synchronous part). You should use Task.Run instead.
Additionally, SendMessages should not be async. However, Index should be, allowing you to use the asynchronous WhenAll instead of the blocking WaitAll.
private List<Task> taskList = new List<Task>();

public async Task<ActionResult> Index()
{
     for (i = 0; i < 5; i++)
     {
         SendMessages();
     }

     await Task.WhenAll(taskList);
     // call demo method
}

private void SendMessages()
{
    var task = Task.Run(() => ProcessMessagesAsync());   // here
    taskList.Add(task);
}

private async Task ProcessMessagesAsync()
{
    while (run for 10 minutes)
    {
        // data save
    }
}


Q:

change background color on onlclick

I have these two buttons. I am wanting to change the background color from #3A1D13 to #4C291A when selected and then back to #3A1D13 once not selected.
Help would be greatly appreciated.
<input type='button' id='hideshow' class='background' value='About'>
<input type='button' id='hideshowcontact' class='background' value='Contact'>

A:

Your question is tagged Jquery, but you don't need JavaScript at all. You can achieve your result by using the CSS active psuedo-class:
If your CSS is defined as follows:
.background {
    background-color: #3A1D13;
}

Then, all you have to do is this:
.background:active {
    background-color: #4C291A;
}

However, that applies the color change for the active state to be global to all elements that have the background class. Alternatively, you could have done so by applying the active psuedo-class on the particular element:
Example, the about button:
#hideshow:active {
    background-color: #4C291A;
}

Note, it's a bit difficult to notice since your colors are visually similar. See this for a working version:
http://jsfiddle.net/eWNLq/1/


Q:

Which is the best way to call multiple method repeatedly in c# timer or thread?

Thread:
for (; ; )
{
    Thread newThread = new Thread(MainWindow.LumEnergyInformation);
    newThread.Start();
    InitializeComponent();
}

Timer:
Timer myTimer = new Timer();
myTimer.Elapsed += new ElapsedEventHandler(LumEnergyInformation);
myTimer.Interval = 10000; // in milliseconds
/myTimer.Start();

A:

In both cases, Thread or Timer, your methods will just be executed in different threads, in parallel with other threads.
The main difference is this:

Thread will use a dedicated thread for the task
Timer will use a thread taken from Thread Pool and the thread will be used for the task only when the method runs. Between one interval and the next one the same thread could be used by someone else.

Therefore all comes down to your use case: if your application uses a lot of threads Timer can be more efficient. If the method you are invoking takes a lot of time, there would be no benefits to use Timer instead of Thread as the thread would not be recycled.


Q:

Using magrittr and which

I want to rewrite the following code with pipes from magrittr:
max(diff(which(diff(runif(50)) > 0 )))

My straightforward approach would be:
library(magrittr)
runif(50) %>% diff > 0 %>% which %>% diff %>% max

But  this fails due to the (first) which:
runif(50) %>% diff > 0 %>% which

Error in which(.) : argument to 'which' is not logical
I am unsure why this error occurs and why piping to which seems to be different from piping to other functions as the output of "diff > 0" is a logical vector.
On a sidenote, would there be a way to pipe for the comparison, bluntly speaking
 runif(50) %>% diff %>% > 0

Thanks for your advice!

A:

Try:
runif(50) %>% diff %>% `>`(0) %>% which %>% diff %>% max

Edit: Should probably point out that those are backticks, not quotation marks.


Q:

Java upcasting and downcasting by interfaces

This is probably a dumb question but I need to know.
I have an interface as
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBAsync;

public interface AsyncClient extends AmazonDynamoDBAsync{

}

And I have a ClientCreator class which has the method
import com.company.clients.AsyncClient;
public class ClientCreator {
        public static AsyncClient getAsyncClient() throws FileNotFoundException, IllegalArgumentException, IOException{
            AmazonDynamoDBAsync client = new AmazonDynamoDBAsyncClient(getCredentials());
            client.setRegion(getRegion());
            return (AsyncClient)client;
        }
        .
        .
        .

Here AmazonDynamoDBAsyncClient implements AmazonDynamoDBAsync and AsyncClient extends AmazonDynamoDBAsync, but this code would not work and throws

com.amazonaws.services.dynamodbv2.AmazonDynamoDBAsyncClient cannot be
  cast to com.company.clients.AsyncClient

but why?

A:

Basically you've got the hierarchy like this:
         AmazonDynamoDBAsync
                  ^
                  |
     -----------------------------
     |                           |
AmazonDynamoDBAsyncClient   AsyncClient

And you are trying to cast AmazonDynamoDBAsyncClient instance to AsyncClient, which isn't possible. Those are siblings. Take it like this: "Apple" and "Banana" are both "Fruit", but an "Apple" is not a "Banana".


Q:

Add multiple new attributes by checking the existing ones

I am working on a reporting application that pulls info from different servers and displays them in a specific format. I am also making this completely responsive so the tables that I get look something like this:

    Date
    Description
    Result
    Range
    Comments

I want to know how I could add data-label to each depending on what width they have.
like
Date

I don't actually need the date field so I have hidden that entire field with CSS its just the description, result, range and comments.

A:

Pulling a list of all td elements in the document, and applying the appropriate labels when the widths-in-question are seen:

var tds = document.getElementsByTagName('td');

for ( var i = 0; i < tds.length; ++i )
  {
    var td = tds[i];
    var label = null;

    switch (td.getAttribute('width'))
    {
      case '30%':
        label = 'Date';
        break;
      case '40%':
        label = 'Description';
        break;
      case '17%':
        label = 'Result';
        break;
      case '15%':
        label = 'Range';
        break;
      case '8%':
        label = 'Comments';
        break;
    }

    if (label)
      {
        td.setAttribute('data-label', label);
      }
  }
td[data-label=Date] {
  color: red;
}

td[data-label=Description] {
  color: green;
}

td[data-label=Result] {
  color: purple;
}

td[data-label=Range] {
  color: blue;
}

td[data-label=Comments] {
  font-style: italic;
}

    Date
    Description
    Result
    Range
    Comments

    Blah
    Blah
    Blah
    Blah
    Blah


Q:

Convert String to a sequence of ints separated with a delimiter using streams

So, I have a List of words that consist of autogenerated symbols. For example: hqst. I convert each symbol of this word to unicode and concatenate it dividing by dot . like this: 104.113.115.116.
I write the next lambda:
.map(word -> {
    char[] symbols = word.toCharArray();
    StringBuilder newWord = new StringBuilder();

    for (int i = 0; i < symbols.length; i++) {
        newWord.append((int) symbols[i]).append(".");
        if (i == symbols.length - 1) {
            newWord = new StringBuilder(newWord.substring(0, i));
        }
    }
    return newWord.toString();
})

Is it possible rewrite this anonymous method using stream API?

A:

Yep. You can use String::chars to get an IntStream from the word, then map each int to a String and collect with a joining collector:
.map(word -> word.chars()
                 .mapToObj(Integer::toString)
                 .collect(Collectors.joining("."))
)


Q:

Any simple way to list the contents of a directory in a web server if the http server does not have directory listing enabled?

If directory listing is not enabled, in say IIS, apache or Njinx you can still access resources if the regular expression entered in the browser matches and item in the directory - i.e. index.html, mypic.jpg etc. So one could list the contents of a directory not set to list everything by just trying all different regular expressions and listing the ones that were valid matches. Is there an easier way to do it than this?

A:

Without help in some kind (by web server, administrative interfaces (ie WMI) or a web service running in the web) you won't probably be able to get a directory listing in a fast and reliable way. Is it your website? If so, I would go for a web service.


Q:

MacBook has 2 guest accounts, one with a password that I never set

My MacBook Air that I've owned for just days has its own guest account, with its own password. This happened to me once before back in 2013 on a MacBook Pro. Typically, I disable the guest account. However, I recently purchased an open-box MacBook Air from Best Buy. I noticed that sometimes, but not every time, a pixelated Guest account would appear next to my user account when logging in, as seen below:

Now most of you might tell me that if I have iCloud & Find My Mac enabled, then the Guest account is there by default. This I'm perfectly aware of, and when I enable Find My Mac, this is what I get:

Once again, we have a pixelated guest account which is password protected, and then the guest account enabled with Find My Mac (on the far right) which doesn't require a password.
What is going on here?

A:

If I purchased a open box computer, The first thing I would do is erase the entire internal drive and reinstall the operating system.
My preferred method, for erasing and reinstalling, is to use a flash drive. The instructions are given at How to create a bootable installer for macOS.
Once booted from the flash drive, I usually erase all previous partitions and create a single partition for the installation of macOS. This can be done by using Disk Utility application included on the flash drive. More information can be found at How to reinstall macOS. Look for the section "Decide whether to erase your startup disk".


Q:

Handling SOAP Web services in an iPhone application-the object oriented way

I am developing an app which requires interaction with a SOAP web service, to retreive and display data. Now in the application, multiple view controllers have the possibility of calling different methods, of the web service to retreive some data.
I tried to write a common class to handle all the web service related stuff, but was unsuccessfull. The problem I am facing is as mentioned below:
I call the common class method, which has web service handling methods, from a view controller with required parameters. The common class hits the web service, parses the data and returns me the result. I receive the result and use it in my view controller. The problem here is that view controller's execution doesn't wait for the completion of execution of common class's all the delegate methods. That is my view would for exapmle navigate, without waiting for the result from the common class.
Anyone solved this problem??Hoping to get a reply soon. Thanks.

A:

Create a protocol for your view controllers to conform to, for callbacks when the data is retrieved.  The view controller implementation will refresh display as appropriate.  You can present a spinner while waiting; it is best to use the status bar activity indicator to show that this is network activity.


Q:

How to remove accents and all chars <> a..z in sql-server?

I need to do the following modifications to a varchar(20) field:

substitute accents with normal letters (like è to e)
after (1) remove all the chars not in a..z

for example
'aèàç=.32s df'

must become
'aeacsdf'

are there special stored functions to achieve this easily?
UPDATE: please provide a T-SQL not CLR solution. This is the workaround I temporarly did because it temporarly suits my needs, anyway using a more elegant approach would be better.
CREATE FUNCTION sf_RemoveExtraChars (@NAME nvarchar(50))
RETURNS nvarchar(50)
AS
BEGIN
  declare @TempString nvarchar(100)
  set @TempString = @NAME
  set @TempString = LOWER(@TempString)
  set @TempString =  replace(@TempString,' ', '')
  set @TempString =  replace(@TempString,'à', 'a')
  set @TempString =  replace(@TempString,'è', 'e')
  set @TempString =  replace(@TempString,'é', 'e')
  set @TempString =  replace(@TempString,'ì', 'i')
  set @TempString =  replace(@TempString,'ò', 'o')
  set @TempString =  replace(@TempString,'ù', 'u')
  set @TempString =  replace(@TempString,'ç', 'c')
  set @TempString =  replace(@TempString,'''', '')
  set @TempString =  replace(@TempString,'`', '')
  set @TempString =  replace(@TempString,'-', '')
  return @TempString
END
GO

A:

The best way to achieve this is very simple and efficient :
SELECT 'àéêöhello!' Collate SQL_Latin1_General_CP1253_CI_AI

which outputs 'aeeohello!'
The string must not be unicode. If you have a nvarchar just cast it to varchar before using the collate.
Here is a function that answers the OP needs :
create function [dbo].[RemoveExtraChars] ( @p_OriginalString varchar(50) )
returns varchar(50) as
begin

  declare @i int = 1;  -- must start from 1, as SubString is 1-based
  declare @OriginalString varchar(100) = @p_OriginalString Collate SQL_Latin1_General_CP1253_CI_AI;
  declare @ModifiedString varchar(100) = '';

  while @i <= Len(@OriginalString)
  begin
    if SubString(@OriginalString, @i, 1) like '[a-Z]'
    begin
      set @ModifiedString = @ModifiedString + SubString(@OriginalString, @i, 1);
    end
    set @i = @i + 1;
  end

  return @ModifiedString

end

Then, the command:
select dbo.RemoveExtraChars('aèàç=.32s df')

outputs
aeacsdf

A:

What you are looking for is something to remove Diacritics from individual characters.  I'm afraid the solution you have is going to be almost as good as you can get, at least with pure SQL.  dotNet/CLR does provide a simple method for doing this, though.  Sorry, I know you are wanting to avoid another CLR solution, but Microsoft SQL Server doesn't provide a T-SQL equivalent for this.
If you're lucky, you have the collation set in your database as "SQL_Latin1_General_CP1_CI_AS" or any variant starting with "SQL_Latin1_General".  This is equivalent to Windows-1252 which is very well documented.  You'll be able to "translate" each character to an English equivalent by reviewing the characters and mapping an equivalent using a SQL CASE statement like you have been.
I do have one quick correction for your code, though.  You are going to want to use varchar in your variables and parameters.  It creates additional overhead performing data type conversion back and forth and has the potential for introducing unicode characters that only exist as unicode into the mix.  Plus, a security related reason specific to your situation can be found on Bruce Schneier's blog.
Update Some great information on Diacritics and Windows internationalization can be found on Michael S Kaplan's blog.

A:

    SELECT 'áéíóú' COLLATE Cyrillic_General_CI_AI

This will replace all accented chars...
result: aeiou
Hope this help you!


Q:

Continuous threads in C++

I want to make an application that listens for some kind of input constantly, without pauses (delaying the read, misses the message) and writing the message to a database (which in my case takes 60ms).
My idea is to have the listening function threaded (or not) in a while(1) loop, which adds to an array/vector of structs (in the below code it is a single variable int newValues) and then check if there is a message available and spawn a thread to deal with it. I also tried to spawn a thread from the listening function for every received message (which is the preferable method, but I don't know if I can spawn infinite threads) but both times the program terminates with: pure virtual method called. I found out that it means that a member of a destructed object is called, but this doesn't help me understand why the below code doesn't work:
#include <iostream>
#include <thread>

using namespace std;

int newValues;  //if this is under 20 then it should be displayed

void listen();
void available();

int main() {
    while (1) {
        //constantly listen
        //this works for a little longer if is called without a thread
        thread lis(listen);
        lis.detach();

        if (newValues < 20) {  //if needed display it
            thread ava(available);  //without disrupting the listening
            ava.detach();
        }
    }
    return 0;
}

void listen() {
    newValues = rand() % 100;
}

void available() {
    cout << newValues << endl;
}

The output from gdb is:
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/arm-linux-gnueabihf/libthread_db.so.1".
[New Thread 0x76bb2450 (LWP 19329)]
[New Thread 0x763b2450 (LWP 19330)]
[Thread 0x76bb2450 (LWP 19329) exited]
[Thread 0x763b2450 (LWP 19330) exited]
[New Thread 0x76bb2450 (LWP 19331)]
[Thread 0x76bb2450 (LWP 19331) exited]
[New Thread 0x763b2450 (LWP 19332)]
[Thread 0x763b2450 (LWP 19332) exited]
[New Thread 0x76bb2450 (LWP 19333)]
15
[New Thread 0x763b2450 (LWP 19334)]
[Thread 0x763b2450 (LWP 19334) exited]
[New Thread 0x75bb2450 (LWP 19335)]
pure virtual method called
terminate called without an active exception
[New Thread 0x763b2450 (LWP 19336)]
[New Thread 0x753b2450 (LWP 19337)]
pure virtual method called
terminate called recursively
[Thread 0x763b2450 (LWP 19336) exited]

Program received signal SIGABRT, Aborted.
[Switching to Thread 0x75bb2450 (LWP 19335)]
0x76bf3f50 in __GI_raise (sig=sig@entry=6)
    at ../nptl/sysdeps/unix/sysv/linux/raise.c:56
56      ../nptl/sysdeps/unix/sysv/linux/raise.c: No such file or directory.
(gdb) r
The program being debugged has been started already.
Start it from the beginning? (y or n) y

Starting program: /home/pi/smart_home/mw_0.1/RPi/nRF24/thread
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/arm-linux-gnueabihf/libthread_db.so.1".
[New Thread 0x76bb2450 (LWP 19341)]
[New Thread 0x763b2450 (LWP 19342)]
[Thread 0x76bb2450 (LWP 19341) exited]
[Thread 0x763b2450 (LWP 19342) exited]
[New Thread 0x76bb2450 (LWP 19343)]
pure virtual method called
terminate called without an active exception
[New Thread 0x763b2450 (LWP 19344)]
[New Thread 0x75bb2450 (LWP 19345)]
[Thread 0x763b2450 (LWP 19344) exited]

Program received signal SIGABRT, Aborted.
[Switching to Thread 0x76bb2450 (LWP 19343)]
0x76bf3f50 in __GI_raise (sig=sig@entry=6)
    at ../nptl/sysdeps/unix/sysv/linux/raise.c:56
56      ../nptl/sysdeps/unix/sysv/linux/raise.c: No such file or directory.

The output from the actual application:
[New Thread 0x75bb2450 (LWP 19686)]
pure virtual method called
terminate called without an active exception  // <- difference
[New Thread 0x753b2450 (LWP 19687)]
[New Thread 0x74bb2450 (LWP 19688)]
pure virtual method called
[Thread 0x753b2450 (LWP 19687) exited]

Program received signal SIGABRT, Aborted.
[Switching to Thread 0x75bb2450 (LWP 19686)]
0x76bf3f50 in __GI_raise (sig=sig@entry=6)
    at ../nptl/sysdeps/unix/sysv/linux/raise.c:56
56      ../nptl/sysdeps/unix/sysv/linux/raise.c: No such file or directory.

But the idea is the same and the code won't work on another machine.
How can I make this work?

A:

To your comment, you have a data race on newValues with infinite threads, which is undefined behavior. You need some kind of synchronization (a mutex or an atomic data type).


Q:

Checking php session by ajax

I'd like run INSERT query by ajax. That query need value from php session but js request doesn't see that value. Whay it's happend ? What should i do ?
Some code below:
JS:
$('div#content').on( "submit" , "form" , function ( event ){
        event.preventDefault();
        var href        = "ajaxRequest.php" + $(this).attr("action");
        var method      = $(this).attr("method");
        var values      = $(this).serializeArray();

        $.ajax({
            url         : href,
            data        : values,
            type        : method,
            dataType    : "html",
            cache       : false,
            success     : function ( content ){
                alert( content );
            }
        });

    });

PHP:
public function addBoard( $params = null )
        {
            $ID_user            =   $_SESSION[ 'user_id' ];
            $board_model        =   $params[ 'board_model' ];

            $query = "INSERT INTO `".prefix."boards` (
                        `ID_user` ,
                        `board_model`
                        )
                    VALUES (
                        '$ID_user', '$board_model');";

            if( $this->SQL->dbquery( $query ) )
                echo 'Added';
            else
                echo 'Failed';
        }

A:

write session_start(); at top of your PHP page.

A:

you may need to start session on top of page.
It seems here that you defined that function in ajax file but not called. So have you called that function in ajax file


Q:

Measuring an electrical signal without tapping wires

I came across a product which taps into a twisted pair differential signal without making physical contact with the conductors. Instead, the wires are untwisted for a few centimeters and clamped into cylindrical sensor in a parallel orientation with a small gap between them.

What physical principles is a device like this based on and how does it work?

A:

Consider this

simulate this circuit – Schematic created using CircuitLab


Q:

Regex - match any characters and allow any number of single spaces. Break match on a double space

I am looking to create a match for the following:

"Adam Lambert"
"Mr. Adam Lambert"
"adam@test.com"

But not match the following

"Adam  Lambert"
"Adam Lambert "

Rules:

Any alphanumeric character should be matches
A single space at any point should be matched.
Any number of single spaces can be matches
double spaces are not matched
a single space at the end of a string is not matched

EDIT
I also need to match the following. Sorry I missed this.
name:((\w+(?:\S\w+)*|\s(?:\w+\S)*)\S)*

I need to match to:

name:
name:A
name:Adam Lambert

The above regex matches from "name:Ad..." but it will not match "name:A"

A:

I would generalize a solution to matching a sequence of non-space characters followed by optional groups of non-space characters following a single space only, since your only hard criterion seems to be the number of spaces. For example:
^\S+(?: \S+)*$


Q:

Expected ArgumentError but got NoMethodError

When I call individual methods in the classes below, I was expecting ArgumentError, but I see:
class A
  def with_one_argument(&block)
    block.call
  end
end

A.new.with_one_argument
# => NoMethodError: undefined method `call' for nil:NilClass

But this acts as expected:
class B
  def with_one_argument(some_value)
    puts some_value
  end
end

B.new.with_one_argument
# => ArgumentError: wrong number of arguments (0 for 1)

Can anybody explain why (&block) is treated as special? In my understanding, if I do not provide a default value to an argument then ArgumentError is expected.

A:

Nothing complicated. The fact is simply that a block is not an argument. With A, if you pass a block, that would be referred to as block as a converted proc, otherwise block has the value nil. But in either case, block is the result of converting the passed block (which is neither an argument nor an object) to a proc (which is an object).


Q:

Network computers wake-up just after putting them to sleep

Since the day we deployed SBS 2011, network computers wake just after putting them to sleep and as far as we can see they never go in sleep mode again. I know that SBS 2011 deliver updates to clients automatically during the night - and that's great - but we don't like to see all machine awake in the morning and waste energy.
Is there something we can do to reduce the time the machine are kept awake?
Clients are Win 7 and Win 8.1 machines.
Thanks.

A:

On a test machine, if you set the sleep timeout, what happens when the machine reaches that timeout? Does it wake right back up?  Does it go to the lock screen?
I've had hardware in the past that would prevent the machine from sleeping.  In my case it was a batch of Logitech keyboards that had some media controls on them.  When the machine would attempt to go to sleep, there would be an event log error saying "Device x prevented the machine from entering sleep".
You can set the machines to wake up at a certain time for updates if you want using the task manager.  http://www.howtogeek.com/119028/how-to-make-your-pc-wake-from-sleep-automatically/  is an example.
I know this is going to sound "anti-green" but if you need to update machines in the middle of the night, then leaving them on is likely worth the cost of electricity.  If you have to perform updates during the day, you lose that productivity time for your users and it likely costs you more than you save.  OR  schedule updates for one night a week and have your users shut down ever night before they leave except for x day.  Or, setup WSUS to deploy updates and wait for the user to reboot/shutdown. Then you don't have to leave them on overnight as updates will be applied on shutdown.  (Just make sure you pre-flight those updates, nothing worse than coming in Monday morning and having everything broken cause MS was super helpful and updated a network driver and broke everything).


Q:

How do I create a randomly distributed boolean variable for a  that will change in the model?

I am writing a model with two breeds:
sexworkers and officers
where sexworkers possess a boolean variable that is randomly distributed at the setup, but then changes at the go according to the behavior of and interaction with officers.
I use sexworkers-own [ trust? ]
in the preamble, but then I am not sure how to distribute y/n of the variable randomly across the sexworkers population. Really appreciate any input!
Thank you so much!

A:

If I understand your question correctly, you're just wanting sexworkers to randomly choose between true and false for the trust? variable on setup. If that's right, then maybe one-of will do the trick for you- for an example, run this simple setup:
breed [ sexworkers sexworker ]
sexworkers-own [ trust? ]

to setup
  ca
  create-sexworkers 1000 [
    set trust? one-of [ true false ]
  ]
  print word "% Trusting: "  ( ( count sexworkers with [ trust? ] ) /
    count sexworkers * 100 )
  reset-ticks
end

If you're looking for some kind of uneven distribution you can do simple ones using the random or random-float primitives. For example, if I want 25% of the sexworkers to start with trust? = true, I can do something like:
to setup-2
  ca
  create-sexworkers 1000 [
    ifelse random-float 1 < 0.25 [
      set trust? true
    ] [
      set trust? false
    ]
  ]
  print word "% Trusting: "  ( ( count sexworkers with [ trust? ] ) /
    count sexworkers * 100 )
  reset-ticks
end

For specific distributions, have a look at the various random reporters
For weighted randomness, have a look at the rnd extension


Q:

Is there a way to be notified when ERC721 is deposited?

We are coding a contract that will work with ERC721 tokens, basically a Plasma Root Chain contract. We need this contract to do some work whenever it receives a new ERC721 token from a SafeTransferFrom.
Just like the function() external payable function is called only when ether is transferred to the contract, we would need the same functionality for ERC721, but we are not sure if it exists or is even possible to implement.
We know the function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) internal returns (bytes4) is called whenever a SafeTransferFrom is done correctly, however, what can be done to stop anyone from just calling that function without actually depositing an ERC721 token?

A:

If it is a genuine ERC-721 transfer transaction, then the msg.sender of the transaction will be the address of the ERC-721 contract. This transaction also contains data about which tokenId was just transferred to you. So you can call ownerOf(tokenId) on that contract, and if the address returned is your contract's address, then you can be confident that you just received an ERC721 token.


Q:

XSL: add a link to a substring within a string made of several TEI-XML elements

Since few days, I try to add a link to substring w[@type='verb'] within a string.
I am working on a TEI-XML transliteration of clay tablets, thus elements and @type of <w> contained in <l> are not always in the same order.
XSLT version 3.0:
<?xml version="1.0" encoding="UTF-8"?>

<xsl:template match="/">
 <xsl:apply-templates select="//div1"/>
</xsl:template>

<xsl:template match="//div1">

    <xsl:for-each select="descendant-or-self::lg/l[@n]">
       <xsl:variable name="verb1" select="w[@type='verb']"/>
       <xsl:variable name="href1" select="w[@type='verb']/@lemmaRef"/>
       <xsl:variable name="single-l" select="w[@type='coo'] | w[@type='noun'] | w[@type='verb'] | w[@type='num'] | w[@type='adv'] | w[@type='adj'] | g | name"/>

       <xsl:value-of select="$single-l"/>
       <xsl:value-of select="./@n"/>
     </xsl:for-each>

</xsl:template>

I need to add a link lemmaRef for each w[@type='verb'].
A sample of TEI — I removed @xml:id from element other than l for this example:
<lg>
    <l n="4b-5a" xml:id="ktu1-3_ii_l4b-5a">
       <w type="coo">w</w><space/>
       <w type="verb" lemmaRef="uga/verb.xsl#qry"><damage degree="medium" facs="definir"><supplied resp="KTU">t</supplied></damage>qry</w>
       <g>.</g>
       <w type="noun" lemmaRef="uga/noun.xsl#ġlm">ġlmm</w>
       <lb/><w>b</w><space/>
       <w type="noun" lemmaRef="uga/noun.xsl#št">št</w>
       <g>.</g>
       <w type="noun" lemmaRef="uga/noun.xsl#ġr">ġr</w>
       <g>.</g>
    </l>
 </lg>

I need to display:

w tqry . ġlmm št . ġr .4b-5a

"tqry" is a verb contained in <l>.
How can I do in XSLT to be able to display <xsl:value-of select="$verb1"/>. I tried replace of $single-l or to define a new variable of the previous XSLT code, but it doesn't work. I have tried also with key but I think I still have a problem of undertanding...
In advance, thank you for your kind advice.

A:

I don't think you should try to build a string and then to insert markup there, it seems it should be possible to simply process the child elements and then match on the lg/l[@n]/w[@type = 'verb'] to transform it to a HTML hyperlink:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="3.0">

  <xsl:output method="html" indent="yes" html-version="5"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="/">

        <title>Example</title>

      <xsl:apply-templates/>

  </xsl:template>

  <xsl:template match="div">

              <xsl:apply-templates select=".//lg/l[@n]"/>

  </xsl:template>

  <xsl:template match="lg/l[@n]">

          <xsl:apply-templates/>

              <xsl:value-of select="@n"/>

  </xsl:template>

  <xsl:template match="lg/l[@n]/w[@type = 'verb']">

          <xsl:apply-templates/>

  </xsl:template>

  <xsl:template match="space">
      <xsl:text> </xsl:text>
  </xsl:template>

</xsl:stylesheet>

This currently does not quite produce the wanted result but

w tqry.ġlmmb št.ġr.4b-5a

instead but if there is content from an element you don't need or want you can add an empty template for that so that it doesn't produce any output (e.g. <xsl:template match="lg/l[@n]/w[not(@type)]"/>).
I am not sure whether there is also important white space missing and what are the rules to insert it, you might need to explain that.
Online sample is at http://xsltfiddle.liberty-development.net/b4GWV5/1.


Q:

Do more objects appear on sky in time?

I would assume that, with light from more distant areas in space reaching the earth, we should be able to see more distant (and older) objects.
However there's lot of weird stuff regarding the space expansion that could eventually make the objects leaving us so fast the we'd never see them.
So, did we reach any boundary of what we can possibly see, or are we still working on more sensitive exploration devices?
I'll be grateful for some useful re-tag

A:

No, the expansion of the universe appears to be accelerating. Hence distant objects get more and more red-shifted. Our horizon is shrinking instead of expanding. At the end, only galaxies which are sufficiently bound by gravity remain visible; this could turn out to be the Virgo supercluster.
More reading about the accelerating universe on Wikipedia, and on National Geographic.
Scientific background to the according Nobel Prize in physics 2011.


Q:

Is it safe to swim naked in lakes in Northern Europe?

Is it safe to swim naked in lakes (rather smaller ones) in Northern Europe (north from Alps), when it comes to possible interactions with the fauna?
I wouldn't expect to meet fishes such as infamous Candiru in the Northern Europe, but are there any fishes or other animals, that could be possible dangerous to the most delicate body parts, making swimming without pants not a very good idea?

A:

As gerrit notes, swimming in lakes is common in Scandinavia, and there's not a lot of fauna in them that could even potentially be harmful.
Some lakes in southern Sweden apparently do have leeches, which can attach themselves to exposed human skin or, in some cases, to the insides of body cavities.  If you were planning to swim in a leech-infested lake (a questionable choice to begin with), I would suggest using swimwear and keeping your head out of the water just in case.  Fortunately (for swimmers), leech populations in Scandinavia have declined dramatically over the last century, mainly due to changes in agricultural practices, to the point where they're nowadays all but extinct in Finland and northern Sweden, and fairly rare even in the south.
The only other aquatic animals I can think of in Scandinavia that might be harmful to swimmers are pikes, which do occasionally bite humans (usually in the foot), mistaking them for prey.  Swimwear won't help you with that, but fortunately it's also a very rare occurrence, and in any case rarely if ever causes any permanent damage.
The same goes for other potentially dangerous wildlife that you might occasionally find in or on lakes, such as angry waterfowl defending their young.  For those, the best defense is basic common sense: don't get between a baby swan and its mom, don't climb on rocks full of seagull nests, and if something hisses or screeches at you, take the hint and leave it alone.
That said, there is at least one somewhat dangerous animal that you should watch out for when going naked outdoors in Scandinavia, although it's not found in water but on dry land: ticks, whose bites can spread Lyme disease and tick-borne encephalitis.  Fortunately, the infection risk is fairly small if the tick is prompty removed, and going swimming presents a good occasion to check your body for any unwanted hitch-hikers that might have attached themselves during the day.

A:

Swimming is a popular summer pas-time in Sweden and Finland.  In rural areas, it's still common for schools to have swimming lessons outside, in lakes.  I'm pretty sure there's no risk from fauna in Swedish lakes.
If you go too far north, you could risk hypothermia ;).


Q:

Python 3 - How to remove line/paragraph breaks

from docx import Document

alphaDic = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','!','?','.','~',',','(',')','$','-',':',';',"'",'/']

while docIndex < len(doc.paragraphs):
    firstSen = doc.paragraphs[docIndex].text
    rep_dic = {ord(k):None for k in alphaDic + [x.upper() for x in alphaDic]}
    translation = (firstSen.translate(rep_dic))
    removeSpaces = " ".join(translation.split())
    removeLineBreaks = removeSpaces.replace('\n','')
    doc.paragraphs[docIndex].text = removeLineBreaks

    docIndex +=1

I am attempting to remove line breaks from the document, but it doesn't work.
I am still getting
Hello

There

Rather than
Hello
There

A:

I think what you want to do is get rid of an empty paragraph. The following function could help, it deletes a certain paragraph that you don't want:

def delete_paragraph(paragraph):
    p = paragraph._element
    p.getparent().remove(p)
    p._p = p._element = None

Code by: Scanny*

In your code, you could check if translation is equal to '' or not, and if it is then call the delete_paragraph function, so your code would be like:
while docIndex < len(doc.paragraphs):
    firstSen = doc.paragraphs[docIndex].text
    rep_dic = {ord(k):None for k in alphaDic + [x.upper() for x in alphaDic]}
    translation = (firstSen.translate(rep_dic))
    if translation != '':
        doc.paragraphs[docIndex].text = translation
    else:
        delete_paragraph(doc.paragraphs[docIndex])
        docIndex -=1 # go one step back in the loop because of the deleted index

    docIndex +=1

*Reference- feature: Paragraph.delete()


Q:

WPF Controls disappearing in Windows 7?

We have a system built using WPF and have (until recently) been developing using Visual Studio 2008 SP1 and Windows XP SP3.
We have upgraded some of our development boxes to windows 7 and we have discovered we are getting some unexpected behaviour when running our applications. Some controls do not display at all.
Has anybody else experienced issues like these and if so, how can we make them work?
Thanks in advance.

A:

Just a guess I had some similar issues with controls (buttons in my case) that were using the DropShadowEffect. The solution was to switch from DropShadowEffect to DropShadowChrome.


Q:

retrieve event object from javascript event and detach the event afterwards

So I want to call a function and pass it parameters on a click event using vanilla javascript (which I've done) but I'm having a problem with detaching the event afterward. When the click event is fired I want to call a function and pass it parameters including the event object and then detach the event. I've tried a few things but the problem I'm running into is that the anonymous function can't be referenced after calling it so I can't pass it as a parameter to the event "unhandler". How can I capture the touch event while also passing parameters the the callback?
function bindClickExpandEvent(element, type, handler, obj) {
    if (element.addEventListener) {
        element.addEventListener(type, function (event) {
            handler(event, obj);
        }, false);
    } else {
        element.attachEvent('on' + type, function (event) {
            handler(event, obj);
        });
    }
}

function removeClickExpandEvent(elem, eventType, handler) {
    if (elem.removeEventListener)
        elem.removeEventListener(eventType, handler);
    if (elem.detachEvent)
        elem.detachEvent('on' + eventType, handler);
}

A:

If you always want to immediately detach the listener after the event has fired, you can do that directly from the handler where you do have a reference to it:
function bindClickExpandEventOnce(element, type, handler, obj) {
    function boundhandler(event) {
        removeClickExpandEvent(element, eventType, boundhandler);
        handler(event, obj);
    }
    if (element.addEventListener)
        element.addEventListener(type, boundhandler, false);
    else
        element.attachEvent('on' + type, boundhandler);
}


Q:

C++ Change output executable name in code

I have a question... Is it possible to somehow change output executable name in code? I mean something like
#ifdef COMPILE_DEBUG
...Name="Client_debug.exe"
#endif

Thanks in advance.

A:

No.  The C++ language doesn't provide any portable mechanism to do that.
Once you start talking about particular platforms, you change the executable name in the .vcxproj file (or whatever build system you are using) - which ends up changing options passed to the linker.
Some compilers have platform specific pragmas to pass options to the linker - they might be able to do this.  But at that point you have to edit your .vcxproj file to pass suitable #defines in - why not just change the output file?


Q:

Repeated element on AngularJS directive scope raising TypeError: Converting circular structure to JSON

I am getting a strange error that is breaking the idea that I had. Basically I want that a directive with access to two elements, a list of Charts and one specific Chart that it is contained in the former list. Considerating the AngularJS way of data binding and my lazyness I decided to pass 2 arrays, the first one would be the list of Charts and the second one could have zero elements or only one element (the selected to be the active).
So here is the directive declaration (datatable and dimensions are used for other things and are working fine):
app.directive("viscMiddleSection", function ($timeout) {
return {
    restrict: "AEC",
    scope: { chartarray: "=", datatable: "=", dimensionsinuse: "=", activechart: "=" },
    templateUrl: "components/middlesection/templates/middle_section.html",
...

In the service I have the two arrays:
app.service('metaDataService', function ($rootScope, $q, dataHtmlService) {
this.activeChartMetadata = [];
this.chartMetadatas = [];
...

And in the controller I get those arrays using getter methods that simply return the arrays citated before:
app.controller('GraphController', ['$scope', 'dataService', 'metaDataService',
function ($scope, dataService, metaDataService) {
    $scope.chartMetadatas = metaDataService.getChartMetadatas();
    $scope.activeChartMetadata = metaDataService.getActiveChartMetadata();
...

Finally I bind all in the html file:
<div visc-middle-section chartarray=chartMetadatas
  datatable=dataTable dimensionsinuse=dimensionsInUse activechart=activeChartMetadata></div>

When I try this way that I explained I got the following exception while rendering the template html file:

Error: [$interpolate:interr] Can't interpolate:       {{activechart}}
  TypeError: Converting circular structure to JSON

Strangely this error only occurs when I pass the chart's object reference to the directive, if I change the 'metaDataService.getActiveChartMetadata()' function to return a number or only the name of the selected chart everything works fine. What am I doing wrong here? I don't see any circular reference in my data, only a repeated object. In my head my scope is this way, without circular references:
scope: { chartarray: [ column_chart_obj, table_chart_obj, pie_chart_obj ], activechart:[pie_chart_obj], ...}
Can someone help me? I really don't want to pass the reference string, since this way I would have to find the chart inside the array of charts in every other directive instead of doing this only one time. Thanks and sorry about the English mistakes.

A:

Ops sorry for the later answer but I actually solved my own problem. While I was waiting for more answers here I decided to do a little refactor in my project and then I noticed that my graph object was storing a DOM-node (a graphic node used by D3 to draw the graphics). I changed it to let the directive send this node as a function parameter instead of setting it at its creation and plim plom problem solve.
So if you are having a problem like the mine, check if you are storing HTML-nodes inside of your object. I suspect that when AngularJS checks your object in the scope to see if it needs to update the directive, it finds an element that it is already inside of the directive to be updated, generating a circular reference and creating this kind of problem.


Q:

DEBUG log rotation in JAVA

In a production environnement (for example) we often use INFO log level because with DEBUG log the size become quickly huge.
I know that's it's possible with SLJ4J or LOG4J to configure log rotation to split files etc.
But most of the time, we only need DEBUG logs when an exception appear, so we can have more information (HTTP Request logs for example).
I'm wondering if it's possible to keep only (for example) 1 minute of DEBUG log and save it if an exception appear. (Main log file is always on level INFO)
For example, when a HttpRequestException occurs, we have a file saved with 1 Minute of DEBUG log HttpRequestException-10-02-2015-10:28:50.log in a specific folder
So we can easily see all exceptions in this folder
/Exceptions/
   - HttpRequestException-10-02-2015-10:28:50.log
   - NullPointerException-10-02-2015-10:29:51.log
   - IOException-10-02-2015-11:29:51.log

So... is it possible to do it with a tool like slf4j ?
And is DEBUG logging a huge performance problem on a production server?
Thanks

A:

I found a solution.
I use cyclicBufferTracker to tell appender to use the last x lines once trigerred
And I can use the evaluator attribute to configure the trigger (default trigger is when an ERROR occurs)
Email is ok for me, but if someone want to put it in files instead of email I think you can create a custom Appender instead of SMTPAppender
Like on this page : http://jira.qos.ch/browse/LOGBACK-207
Here is the actual code : (You will need javax.activation and javax.mail if you use email implementation) and if you use gmail like me you will need to allow low security app in gmail settings : Gmail less secure apps
<appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
   <smtpHost>smtp.gmail.com</smtpHost>
   <smtpPort>587</smtpPort>
   <asynchronousSending>false</asynchronousSending>
   <STARTTLS>true</STARTTLS>
   <username>GoogleUsername</username>
   <password>mypassword</password>
   <to>GoogleUsername@gmail.com</to>
   <from>GoogleUsername@gmail.com</from>
   <subject>Exception Alert</subject>
   <layout class="ch.qos.logback.classic.PatternLayout">
      <pattern>%date - %message%n</pattern>
   </layout>
   <cyclicBufferTracker class="ch.qos.logback.core.spi.CyclicBufferTracker">
      <bufferSize>50</bufferSize>
   </cyclicBufferTracker>
</appender>

Hope it will help


Q:

How to use spaces and angle brackets for TARGET in .pro file

I want to name my Qt application as

test <2>

So I write my .pro file as
TEMPLATE = app
TARGET = test\\\ \\\<2\\\>

QT = core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

SOURCES +=  main.cpp

But it fails when building:
11:14:31: Running steps for project asdf...
11:14:31: Configuration unchanged, skipping qmake step.
11:14:31: Starting: "/usr/bin/make"
/home/erik/Qt/5.11.1/gcc_64/bin/qmake -o Makefile ../asdf/asdf.pro -spec linux-g++ CONFIG+=debug CONFIG+=qml_debug
WARNING: DESTDIR: Cannot access directory '../build-asdf-Desktop_Qt_5_11_1_GCC_64bit-Debug/test/ /<2'
/bin/sh: 1: cannot open 2/: No such file
/bin/sh: 1: cannot open 2/: No such file
Makefile:254: recipe for target 'test/ //<2/>' failed
make: *** [test/ //<2/>] Error 2
11:14:31: The process "/usr/bin/make" exited with code 2.
Error while building/deploying project asdf (kit: Desktop Qt 5.11.1 GCC 64bit)
When executing step "Make"
11:14:31: Elapsed time: 00:00.

How should I escape the characters in TARGET?

A:

You shouldn't, and in case of qmake: you can't, since the resulting makefiles will be unusable. Most operating systems reserve those characters, and while a file with such a name may be representable in the filesystem - it can't be used in typical ways. See e.g. Filename:Reserved characters and words for an overview.
The titles of application windows (e.g. as seen here) have nothing to do with file names. You can set them to whatever you want using QWidget's windowTitle property.


Q:

C Pointer Write Error

 void fileNameProcess(char * inputName){
             int size =strlen(inputName);
             bool change=false;
             char * name=inputName;

             for(int i =0; i<size; i++){
                 char temp=* (name+i);
                 if(temp<0x10||temp>0x5b){
                     change=true;
                 }else if(0x19<temp<0x21){
                     change=true;
                 }else if(0x3a<temp<0x41){
                     change=true;
                 }
                 if(change){
                     //*(name+i)='_';
                     memset(name+i, '_', 1);
                     change=false;
                 }
             }

         }

it breaks when i try to set a character in a string (memeset), but i dont understand why it doesnt allow me to do that? why i can allow access to read it but couldnt modify it?
can anyone explain it in memory aspect. i guess it is because the string is passed into the function. but as long as i know the memeory location, i could set it right?
thanks
char * filename= strdup("try1.mat");
    writter.locate(filename);

in locate it assign filename to class memeber char* filepath

A:

This:
if(1 < variable < 2)

Probably doesn't do what you want. Use:
if(1 < variable && variable < 2)

edit
if(1 < variable < 2) evaluates like this:
if( (1 < variable) < 2)
if( (true) < 2)
//given true is often* assigned a value of 1 this will always be true and
if( (false) < 2)
//false is always zero this will also be true

*I don't think this is required by the standard so don't rely on it.

A:

Most probably you are giving a constant literal string as the input:
char * str = "test";
fileNameProcess(str);

If that is the case, try:
char * str = strdup("test");
fileNameProcess(str);

A:

I'm guessing that you're passing in a string literal to the function:
fileNameProcess( "myfile.dat");

String literals cannot be modified.
However, you could pass in an array that's initialized by a literal:
char fname[] = "myfile.dat";

fileNameProcess( fname);

As with any string handling routines, take care that when you modify the passed in string that you keep it properly terminated and don't write past the end of the buffer.


Q:

How do I count the number of running threads (pthreads)?

If I search for counting the number of threads an application has, all the answers involve external programs like top. I want to count the threads within the application itself.
I can't add code at the point of thread creation because it happens inside an immutable library.
I can't read /proc.
It's a C/pthreads program running on a few different Unices.

A:

If you can't read /proc you are a bit in trouble, unless your program communicate with another program which reads /proc
If you don't want to read /proc because of portability concerns, you might use a library which abstracts that a bit, like libproc does


Q:

Is it even possible to have a melee based class play a range style in Diablo 3?

In Diablo 1 and 2, you had the freedom to equip both ranged and melee weapons on your character. For example, I could equip a bow or a sword/shield on my paladin. Early in Diablo 3, you can equip a skill to both mouse buttons. This effectively relegates your weapon to a bunch of numbers, as you don't actually attack with it.
Is the only option to create a ranged monk or barbarian to fool the skill system?

A:

Barbarians and Monks cannot equip ranged weapons, so the answer is no.


Q:

How to allow non-root user to listen on privileged port?

I want syslog to run as a non-root user on my linux box. That makes it impossible for it to bind to port 514 - because that's a privileged port. Is there any way I can grant non-admin user "foo" the ability to listen on port 514?

A:

setcap 'cap_net_bind_service=+ep' /path/to/syslogd

Requires a not-ancient linux kernel (2.6.24 or later)

A:

You could configure rinetd (available in most, if not all, distribution's standard repositories) to listen on port 514 and forward connections to some other port (above 1024, say 1514). That way the non-privileged user process can listen on 1514 and rinetd will forward connections so it appears to be listening on 514.
This will only work for TCP connections though. If you need to support UDP (or anything else) this way as well as or instead of TCP, then you can use iptables translation rules to achieve the same effect.


Q:

Sort HashTable according to values(numeric) preferably descending order and maintain the key-value

I have the following key-value pairs in my HashTable.
    KEY : VALUES
    12345:45;
    23456:23;
    23445:34;
    12367:101;

    Output should be:
    12367:101;
    12345:45;
    23445:34;
    23456:23;

i.e. the output is in the descending order of the values.
ht_sort is my Hash table containing the key-value pairs.
//get the values from the hashtable as array objects.
Object[] arytf= ht_sort.values().toArray();

//Sort the array objects.
Arrays.sort(arytf);

But the problem is that I am unable to link back these sorted values to the hash to       get the keys.
I am not exactly sure how to go about doing this, I have checked the previous threads but couldnot make anything out of them. Looking for help on this.
Thanks.

A:

EDIT:
Duplicated values allowance solution:
List<Map.Entry<Integer, Integer>> sortMapValues2(Map<Integer, Integer> map){
    //Sort Map.Entry by value
    List<Map.Entry<Integer, Integer>> result = new ArrayList(map.entrySet());
    Collections.sort(result, new Comparator<Map.Entry<Integer, Integer>>(){
        public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
            return o2.getValue() - o1.getValue();
    }});

    return result;
}

You could get lots of articles by google "java collections framework".


Q:

What are the sensitivity analyses for propensity score matching-based estimation?

I'm interested in using Propensity Score Matching (PSM) to create matched control vs treatment sample and estimate the treatment effect. But the problem with PSM is that the sample is matched based on observed covariates.
What are the sensitivity analyses for PSM, to assess its robustness to unobserved factors? I know there is Rosenbaum Bound analysis and M-H bound (rbounds and mhbounds in STATA, respectively,), any others?

A:

there is also a simulation-based sensitivity analysis for matching estimators, which is described in Nannici (2007) and Ichino et al. (2008). In Stata, the program sensatt can perform this kind of analysis.
Moreover, you could imagine a binary unmeasured confounder and stratify on it as proposed by Greenland (1996) and discussed in the context of matching by Harding (2003). This idea can again be combined with simulation techniques, see e.g. Groenwold et al. (2010) or Liu et al. (2013). In general, the latter two papers provide a good overview about sensitivity analysis techniques.
Further approaches, which are not specific to matching but readily applicable to matching, are e.g. described in Arah et al. (2008), VanderWeele & Arah (2011), Blackwell (2013), Ding & VanderWeele (2016) and VanderWeele & Ding (2017).
If you want to work with a minimal set of assumptions, it might be interesting to have a look at the literature on non-parametric bounds for average treatment effects (e.g. Manski, 1990).
Here are doi references to most of the papers I mentioned:
https://doi.org/10.1086/379217
https://doi.org/10.1002/jae.998
https://doi.org/10.1093/ije/dyp332
https://doi.org/10.1007/s11121-012-0339-5
https://doi.org/10.1016/j.annepidem.2008.04.003
https://doi.org/10.1097/EDE.0b013e3181f74493
https://doi.org/10.1093/pan/mpt006
https://doi.org/10.7326/M16-2607


Q:

ng-hide to hide data when the submit button is pressed

I want to hide the date for:{{...}} data which is getting the date when the user submits their own date. I have tried using class="check-element animate-hide" ng-hide="checked" example from angularjs page. But it does not seem to work with the type="submit" for me.
how else can I implement this?
HTML:

      <button ng-hide="checked" class="btn btn-primary" type="submit">Fetch</button>

    </form>

 Data for:{{ date | date: 'MM/yyyy' }}

A:

Try something like that:

            <button ng-click="visible = false" class="btn btn-primary" type="submit">Fetch</button>

</form>

 Data for:{{ date | date: 'MM/yyyy' }}

And in your controller set the default value of visible to true
$scope.visible = true;


Q:

Glyph origins of the character 拜

I've seen somewhere that it was two hands together greeting someone. It makes some sense since the left part does look like 手, but the right part doesn't, and I don't remember any other characters that have it.
What's the real story about the character 拜?

A:

「拜」was originally「」, comprised of「手・扌」and「」.

「」(please read this in both meaning and sound as「禱」) depicts flowery adornments used in dances and religious prayer/rituals.
商甲佚32合集1439西周金番生簋蓋集成4326秦簡日甲61背　篆說文解字　今楷

The combination of「手」(hand) and「」(flowery adornments used in dances and religious prayer/rituals) indicated the meaning to conduct obeisance.
西周金沈子它簋蓋集成4330秦簡睡・秦153
In the character「」, the bottom part of「」was sometimes corrupted into something that looked like「手」.
秦簡日甲166
Similarly, the top part of「」, which is「卉」, was sometimes removed. This leads on to the modern form of「拜」.
東漢隸鄭固碑　今楷

References:

季旭昇《說文新證》
小學堂
國學大師

郭沫若《甲骨文合集》
中國社會科學院考古研究所《殷周金文集成》


Q:

Eclipse Maven Plugin Push to Repo

My team has decided to use GitHub with Maven to manage our repository.  I have experience with the Mercurial plugin for Eclipse and BitBucket, but this seems very different.
I managed to download Maven by Help-> Install new software -> Work with: Indigo -> General Purpose Tools -> m2e
So at this point I'd like to connect to the repository at GitHub and then push my content to the repo.
I can't find any tutorials on doing this.  Others seem to be having the same problem; like here!
Here's a screenshot of my Eclipse setup:

A:

You should install the Eclipse:EGit, to let the Eclipse integrate with the Github as a SCM. For further detail please look at the user guide.
If you would like to do an issue management together with your source code working set. You may use the Eclipse Mylyn to achieve your requirement. There is a Github Mylyn connector here. After you have installed it, during "Add Task Repository..." you will have the following: -

Github Gists
Github Issues
Github Pull Requests

During the committing the source code change set to the version control (SVN/Git/etc) you are able to link the issue from Mylyn connector to it for better management.
Please note, I'm using Maven, SVN as my SCM together with the Eclipse Mylyn with Redmine by using the Redmine Mylyn Connector. They provide me a good result as well.
I hope this may help.
Regards,
Charlee Ch.


Q:

What are the disadvantages of using Awesomium (with WPF)?

Well it is definitely way faster than the built-in Web-Browser component of .Net Framework.
But is Awesomium slower than HttpWebRequest? Are there any drawbacks?
Right now I'm choosing Awesomium over HttpWebRequest because Awesomium has scripting support which is just what I needed for interacting with HTML forms.
I understand it is possible to submit HTML forms with HttpWebRequest via POST, however my target HTML forms have some heavy loaded AJAX stuff that deals with the input elements along with a couple of javascript encryptions on the input data (which droved me nuts).
So my question is, are there any disadvantages of using Awesomium?
Thank you for your time.

A:

you may use awesomium to detect where and what to put into httpwebrequest. Like what you've said, awesomium is a third party program so it could take longer time than other library.


Q:

Extracting Netcdf climate data for multiple locations at different times using R?

I have daily sea surface temperature and air temperature data from 1980 to 2018. How do I extract values for multiple (up to 100) specific locations at different dates in one go to csv. Right now I can only extract one location at a time.
How can it be done in bulk in R?

A:

Here is some example code for R. I think there are many examples out there.
library(raster)
b <- brick("climfile.nc")
points <- shapefile("ptsfile.shp")
d <- extract(b, points)
write.csv(d, "file.csv", rownames=FALSE)


Q:

How can I add a custom .aspx into already compiled website?

We have a company product (asp.net website) that gets compiled and distributed to our clients.  I need to figure out a way to allow us to add in an ad hoc aspx webpage into the website (so it recognizes the master page, the forms authentication, assemblies, etc) without having to provide them with an un-compiled version of the website product.
Is this possible.  Is there a better method than having a special compiled version of the website on their server.
More detailed information:  The main product website is a Web Application in IIS7 and the custom ad hoc page is in a total separate folder on the server that gets added in as a virtual directory to the main product's website application.  This works fine when using an un-compiled version of the web application.

A:

With the way you have framed it, you are likely "hosed". But there is a workaround that might work for you. That would be to pull as much logic into libraries. This does not completely obfuscate the flow, but it does keep your code hidden from the client.
You can take this farther, if you wish. Using a custom extension, like .mspx (Microsoft did this), you can completely encapsulate the code. I would imagine you could add some type of build step that took your compiled application and worked the magic of the custom extension in. You then allow ASPX to be handled "normally". You would have to POC this idea, of course.
There might be a way, via config, to have the foldered page work, but I have not polayed in this direction. Would be worth an POC experiment.


Q:

Java8: Map to Map using RxJava

I know how to transform Map<X, Y> to Map<X, Z> using stream and it there was also a previous question about this.
But I want to learn how do it using RxJava.
And to be more specific:
//Input:
Map<String,String> in; // map from key to a string number, for example: "10"

//transform: in -> out

//Output:
Map<String,Integer> out; //map from the same key to Integer.parseInt(val) (invariant: val is a string number)

A:

You can use Observable.toMap.
I think this is a minimal example:
Map<String, String> test = new HashMap<String, String>() {

    {
        put("1", "1");
        put("2", "2");
    }
};
Map<String, Integer> res = Observable.from(test.entrySet()).toMap(e -> e.getKey(), e -> Integer.parseInt(e.getValue())).toBlocking().first();


Q:

SCNNode Rotation Multiple Axes

This Question was posted, but never answered.
Similar to This Question, I am trying to understand SCNNode.rotation as a 4D vector. The prior question utilizes an example that only manipulates 1 axis, i.e.,
SCNNode.rotation = (0, 0, 1, degToRad(45)) //Rotate about z-axis by 45 degrees

which makes sense; however, what if I wanted to rotate the X axis by 20 degrees, Y axis by 45 degrees and then Z axis by 78 degrees?
SCNNode.rotation = ??

I would provide code I've tried, but I don't understand conceptually the notion of a 4D rotation vector.

A:

Every node just has a transform with 4x4 matrix. So all the rotation operations are reflecting in the changing the transform.
In this case, if you change either of rotation, eulerAngles and orientation, you are supposed to get same value.
If rotating about three axises, I suggested using eulerAngles.
node.eulerAnges = SCNVector3(x:degToRad(20),y:degToRad(45), z:degToRad(78))
After you set this, go back and check to value of rotation:
SCNVector4(x: -0.16975601, y: 0.5943193, z: 0.786109, w: 1.448788)
This means there is an axis going through point(-0.16975601, 0.5943193, 0.786109) and origin (0,0,0), and node is rotating around it for  1.448788 (82 degree).