Q:

Rigorous definition of tangent space

I am studying manifolds, while my book offers a definition of tangent space I am having problems understanding it, so what is a rigorous definition of tangent space?

A:

There are several ways to define the tangent space. Here's one:
As the set of all derivations. A derivation at a point $p$ in a manifold $M$ is a linear map $X:C^{\infty}(M)\to\mathbb{R}$ which satisfies the product rule $$X(fg)=f(p)(Xg)+(Xf)g(p)$$ for all functions $f,g\in C^{\infty}(M)$. Then the tangent space $T_{p}M$ is the vector space of all derivations at $p$.
One can also define the tangent space in local coordinates, or via initial tangent vectors. Another good reference to look at is John M. Lee's Introduction to Smooth Manifolds, 2nd Edition. Chapter 3 in this book covers several definitions of the tangent space.


Q:

Iterate and Enumerate Key Value Pairs of Multiple Arrays in an Object

My question is in regards to the following function:
function loadConfigurations(configs){
  console.log(configs);
}

The 'configs' object that the loadConfigurations function receives, contains two properties --two arrays one called "assigned" the other called "unassigned".  And executing console.log(configs) outputs the following:
"Object{assigned: Array[5], unassigned: Array[1]}"

Now I want to enumerate the key-value pairs of each property in both the 'assigned' array and the 'unassigned array'.
The configs object is structured in the following way:
Sorry fellas.  This is the structure of the configs objects:
var configs = {
"config1":
        {
        "assigned": [
            {
                "name": "Admin Usersss",
                "value": "admin-user"
            },
            {
                "name": "MPR User",
                "value": "mpr-user"
            },
            {
                "name": "SAMHSA User",
                "value": "samhsa-user"
            }
         ],
        "unassigned": [
            {
                "name": "States User",
                "value": "states-user"
            },
            {
                "name": "All States User",
                "value": "all-states-user"
            },
            {
                "name": "Substance Abuse User",
                "value": "substance-abuse-user"
            }
         ]
        },
"config2":
        {
        "assigned": [
            {
                "name": "Admin User",
                "value": "admin-user"
            },
            {
                "name": "MPR User",
                "value": "mpr-user"
            },
            {
                "name": "SAMHSA User",
                "value": "samhsa-user"
            },
            {
                "name": "States User",
                "value": "states-user"
            },
            {
                "name": "All States User",
                "value": "all-states-user"
            }
        ],
        "unassigned": [
            {
                "name": "Substance Abuse User",
                "value": "substance-abuse-user"
            }
        ]
    },
    "config3":
    {
        "assigned": [
            {
                "name": "Admin User",
                "value": "admin-user"
            }
        ],
        "unassigned": [
            {
                "name": "States User",
                "value": "states-user"
            },
            {
                "name": "All States User",
                "value": "all-states-user"
            },
            {
                "name": "Substance Abuse User",
                "value": "substance-abuse-user"
            },
            {
                "name": "MPR User",
                "value": "mpr-user"
            },
            {
                "name": "SAMHSA User",
                "value": "samhsa-user"
            }
            ]
        }

How do I do this?
Thanks,
CM

A:

Given the data structure you've posted you can use Object.keys() to enumerate the keys of the parent object and then loop over the assigned and unassigned properties within that. Try this:
Object.keys(configs).forEach(function(key) {
    var config = configs[key];

    config.assigned.forEach(function(assigned) {
        console.log('A: ' + assigned.name + ', ' + assigned.value);
    });

    config.unassigned.forEach(function(assigned) {
        console.log('U: ' + assigned.name + ', ' + assigned.value);
    });
})

var configs = {
  "config1": {
    "assigned": [{
      "name": "Admin Usersss",
      "value": "admin-user"
    }, {
      "name": "MPR User",
      "value": "mpr-user"
    }, {
      "name": "SAMHSA User",
      "value": "samhsa-user"
    }],
    "unassigned": [{
      "name": "States User",
      "value": "states-user"
    }, {
      "name": "All States User",
      "value": "all-states-user"
    }, {
      "name": "Substance Abuse User",
      "value": "substance-abuse-user"
    }]
  },
  "config2": {
    "assigned": [{
      "name": "Admin User",
      "value": "admin-user"
    }, {
      "name": "MPR User",
      "value": "mpr-user"
    }, {
      "name": "SAMHSA User",
      "value": "samhsa-user"
    }, {
      "name": "States User",
      "value": "states-user"
    }, {
      "name": "All States User",
      "value": "all-states-user"
    }],
    "unassigned": [{
      "name": "Substance Abuse User",
      "value": "substance-abuse-user"
    }]
  },
  "config3": {
    "assigned": [{
      "name": "Admin User",
      "value": "admin-user"
    }],
    "unassigned": [{
      "name": "States User",
      "value": "states-user"
    }, {
      "name": "All States User",
      "value": "all-states-user"
    }, {
      "name": "Substance Abuse User",
      "value": "substance-abuse-user"
    }, {
      "name": "MPR User",
      "value": "mpr-user"
    }, {
      "name": "SAMHSA User",
      "value": "samhsa-user"
    }]
  }
}

Object.keys(configs).forEach(function(key) {
  var config = configs[key];
  config.assigned.forEach(function(assigned) {
    console.log(key + ' A: ' + assigned.name + ', ' + assigned.value);
  });
  config.unassigned.forEach(function(assigned) {
    console.log(key + ' U: ' + assigned.name + ', ' + assigned.value);
  });
})

Also note that (as pointed out by @adeneo in the comments on your question) if you're performing the same logic on both assigned and unassigned items then you can concatenate them together and iterate them once.
The above method would be required if the logic is different between properties.


Q:

Can two different versions of the same libs (with same name) exists in an application?

I have some scenario like this:
Product-> Platform-> mylibs(version-1)
Product-> mylibs(version-2)
i.e Product uses mylibs (version-2) directly. Product also uses platform (which is also a dynamic lib) and platform uses my libs (version-1).
The names of the libs used by product and platform are same. Only versions are different and both these versions are not compatible.
Is there a way with ".so" libs in linux that Platform can link to one version and product can link to another version of the same libs having the same name?

A:

Note, even changing the names of the libs won't be enough by default, as symbol names would conflict.
Your libs should use soname and versioned symbols, in which case they can even be called the same.
$ make
gcc -shared -fpic -Wl,-soname -Wl,libmylibs.so.1 -Wl,--default-symver -o libmylibs.so.1 mylibs1.c
gcc -shared -fpic -Wl,-soname -Wl,libmylibs.so.2 -Wl,--default-symver -o libmylibs.so.2 mylibs2.c
gcc -shared -fpic -Wl,-soname -Wl,libplatform.so.1  -Wl,--default-symver -Wl,--default-imported-symver -o libplatform.so.1 platform.c libmylibs.so.1
gcc  -Wl,-rpath-link -Wl,. -Wl,--default-imported-symver  -o program program.c libplatform.so.1 libmylibs.so.2
/usr/bin/ld: warning: libmylibs.so.1, needed by libplatform.so.1, may conflict with libmylibs.so.2
$ LD_LIBRARY_PATH=$PWD ldd ./program
    linux-vdso.so.1 =>  (0x00007fff1e3ff000)
    libplatform.so.1 => /tmp/so-4539442/libplatform.so.1 (0x00007f6dc3ba0000)
    libmylibs.so.2 => /tmp/so-4539442/libmylibs.so.2 (0x00007f6dc399f000)
    libc.so.6 => /lib/libc.so.6 (0x00007f6dc364c000)
    libmylibs.so.1 => /tmp/so-4539442/libmylibs.so.1 (0x00007f6dc344b000)
    /lib64/ld-linux-x86-64.so.2 (0x00007f6dc3da1000)
$ LD_LIBRARY_PATH=$PWD ./program
lib version 2, platform lib version 1


Q:

Cannot assign value of type 'Double' to type 'String?'

I am very new to swift. Whenever i try to run my code I get this error.

Cannot assign value of type 'Double' to type 'String?'

How do I go about fixing it? Thanks in advance
func getWaterVolumeLabelText() -> Double {
   let dnv: Double = dNTPsVolumeLabel.text?.doubleValue() ?? 0
        let fp: Double = forwardPrimerLabel.text?.doubleValue() ?? 0
        let rp: Double = reversePrimerLabel.text?.doubleValue() ?? 0
        let dp: Double = dnaPolymeraseLabel.text?.doubleValue() ?? 0
      //  let votd: Double = volumeOfTemplateDna.text.doubleValue() ?? 0
        let bv: Double = bufferVolumeLabel.text?.doubleValue() ?? 0

        waterVolumeLabel.text = (numberOfSamples.doubleValue() ) * (50.0 - dnv )// This is where the error shows.
        }

A:

You are assigning Double value to String type that's why it gives error. You can convert Double to String. Your updated code:
func getWaterVolumeLabelText() -> Double {
   let dnv: Double = dNTPsVolumeLabel.text?.doubleValue() ?? 0
        let fp: Double = forwardPrimerLabel.text?.doubleValue() ?? 0
        let rp: Double = reversePrimerLabel.text?.doubleValue() ?? 0
        let dp: Double = dnaPolymeraseLabel.text?.doubleValue() ?? 0
      //  let votd: Double = volumeOfTemplateDna.text.doubleValue() ?? 0
        let bv: Double = bufferVolumeLabel.text?.doubleValue() ?? 0

        let finalResult = (numberOfSamples.doubleValue() ) * (50.0 - dnv )
        waterVolumeLabel.text = String(finalResult)
        }


Q:

How to Update Graylog version in docker

I am new to graylog, I have installed graylog in docker and after installing it I observed 2 notifications one is related to Graylog Upgrade. Can someone tell me how to update it using docker commands?
Note: First in need to take backup of my data and then I need to update it to version 2.4.6.
Note 2: I have already referred the documentation in graylog.
http://docs.graylog.org/en/2.4/pages/upgrade.html
http://docs.graylog.org/en/2.4/pages/installation/docker.html
Graylog Installation process:
docker run --name mongo -d mongo:3
docker run --name elasticsearch \
    -e "http.host=0.0.0.0" -e "xpack.security.enabled=false" \
    -d docker.elastic.co/elasticsearch/elasticsearch:5.6.2
docker run --link mongo --link elasticsearch \
    -p 9000:9000 -p 12201:12201 -p 514:514 \
    -e GRAYLOG_WEB_ENDPOINT_URI="http://127.0.0.1:9000/api" \
    -d graylog/graylog:2.4.0-1

A:

First i have installed graylog with my own volumes
docker run --link mongo --link elasticsearch \
           -p 9000:9000 -p 12201:12201 -p 514:514 \
           -e GRAYLOG_WEB_ENDPOINT_URI="http://127.0.0.1:9000/api" \
           -d graylog/graylog:2.4.0-1

Now stop graylog using
docker stop [graylog Container ID]

Now remove container from docker
docker rm [graylog Container ID]

Now Remove docker image
docker rmi [graylog Image ID]

Now again install graylog by changing the graylog version
docker run --link mongo --link elasticsearch \
           -p 9000:9000 -p 12201:12201 -p 514:514 \
           -e GRAYLOG_WEB_ENDPOINT_URI="http://127.0.0.1:9000/api" \
           -d graylog/graylog:2.4.6-1

Note: Only remove graylog not mongoDB/Elasticsearch. Then you won't loose any data.


Q:

Get NamespacePrefix for a given Package Id (in org with LMA app)

Is there a way to get the Namespace Prefix of Managed Package where I just have the Id of? Maybe it is helpful that my code sits in the same org as the LMA app in with its sfLma__Package__c objects.

Something like SELECT NamespacePrefix FROM PackageLicense WHERE ...?
Or something using Tooling, Metadata or SOAP API?

Example code would be helpful.

A:

You can use the Tooling API to query SubscriberPackage, e.g.
$ force query -t "SELECT NamespacePrefix FROM SubscriberPackage WHERE Id = '033f40000001ZCXAA2'"
 NamespacePrefix
-----------------
 osfb
 (1 records)

Or if you have the Id of the version of the package, you can query InstalledSubscriberPackage, e.g.
$ force query -t "SELECT SubscriberPackage.NamespacePrefix FROM InstalledSubscriberPackage WHERE Id = '0A3540000004uhzCAA'"
 SubscriberPackage.NamespacePrefix
-----------------------------------
 osfb
 (1 records)


Q:

How do you set the PDF Print Dialog Presets (e.g. DuplexMode) in objective-c?

I am using UIGraphicsBeginPDFContextToFile to create a PDF in an iPad app. The file is encrypted using a password. I would like to set the PDF Print Dialog Presets in particular DuplexMode so that the document will default to duplex printing. I assume I should be using kCGPDFContextKeywords to set DuplexMode to DuplexFlipLongEdge.
Can someone provide an example of how this is done.

A:

It cannot be done using the standard iOS PDF API. The auxiliary dictionary keys are a fixed set that support only setting some document information and the password.
There is no support for setting the DuplexMode.


Q:

Working with binary in Python, Splitting numbers

I have a module that takes 2 X 8bit numbers in Decimal format, with a specific structure
each number must start with the same 4 bits  = 0011
followed be a varible 8 bits
followed by 4 bits that are ignored so set to 0000
So to caculate the 16bit number is simple enough
the varible number * 16 will shift it the 4 bits to the left, and adding 12288 = 0011|000000000000 will give me the desired result.
so if my input number is 19 for example
19 X 16 + 12288 = 12592 = 0011000100110000
the next step is to split it in to two X 8 bit numbers
00110001 | 00110000 = 49, 48
how in python can i go from 12592 to 49,48 efficiently.
Never worked in binary in a script so all a bit new.
Cheers

A:

To get the first 8 bits, just shift it to the right by 8 bits.
   0011000100110000 >> 8
==         00110001

To get the last 8 bits, mask it with 0b11111111, i.e. 255.
   0011000100110000
&  0000000011111111
-------------------
   0000000000110000

Code example:
>>> n = int("0011000100110000", 2)
>>> n
12592
>>> n >> 8, n & 255
(49, 48)

Alternatively, you could also just use divmod, but >> and & seem to be a bit faster.
>>> divmod(n, 256)
(49, 48)


Q:

Is there a category in which finite limits and directed colimits *don't* commute

Andrew Critch asks at the 20-questions seminar:
In Set and AbGrp (the categories of sets and abelian groups, respectively), finite limits commute with directed colimits. As an example, if you're working with sheaves of sets, you can take kernels (a type of limit) and stalks (a type of directed colimit) safely.
Is there an example of a category where they don't commute?
(Depending on how you choose to talk about topoi, this condition is sometimes an axiom, capturing the idea of "looking sufficiently like sets".)

A:

Consider the poset of closed subsets of $[0,1]$.  Let $a=\{0,1\}$ and $b(r)=[0,r]$ for $r<1$.  Then the (directed) colimit of the $b(r)$ is $b=[0,1]$, and the product (i.e., intersection) of $b$ and a is $a$.  However, the colimit of the products of the $b(r)$ with $a$ is $\{0\}$.


Q:

c++ sprintf function and fstream to create/check a text file

I am having some trouble with sprintf and fstream functions in order to create new text files for a POS program/check whether the file already exists. I don't know if i am doing something wrong because the same set of functions works fine in other places in my code...
This particular section of code is taking input from the user to create a details file, the name is made up of the first and last name details that were entered into the system. For some reason the new file is not being created. When I step through the program I can see that the custDetC variable is being filled with the correct data. I have also included the file existence check as it may or may not have something to do with the issue at hand...
Tony Mickel
    sprintf(custDetC,"%s%s.txt", firstName.c_str(), lastName.c_str());
    cout << custDetC << endl;

    FileEX = FileExists(custDetC);

    if (FileEX == true)
    {
        fopen_s(&custDetF,custDetC, "rt");

        fprintf(custDetF, "%s %s\n", firstName, lastName);
        fprintf(custDetF, "$d\n", phoneNo);
        fprintf(custDetF, "%s $s\n", unitHouseNum, street);
        fprintf(custDetF, "%s %s %d", suburb, state, postCode);

        fclose(custDetF);
    }
    else
    {
        char *buf = new char[100];
        GetCurrentPath(buf);
        cout << "file " << custDetC << " does not exist in " << buf << endl;
    }
}

bool FileExists(char* strFilename)
{
    bool flag = false;
    std::fstream fin;
    // _MAX_PATH is the maximum length allowed for a path
    char CurrentPath[_MAX_PATH];
    // use the function to get the path
    GetCurrentPath(CurrentPath);
    fin.open(strFilename, ios::in);

    if( fin.is_open() )
    {
        //cout << "file exists in " << CurrentPath << endl;
        flag = true;
    }
    else
    {
        //cout << "file does not exist in " << CurrentPath << endl;
        flag = false;
    }
    fin.close();

    return flag;
}

A:

You seem to be opening the file for reading, but you need to open it for writing.
Instead of "rt" use "wt" in fopen_s()


Q:

Java Annotations: Using @Target(ElementType=METHOD) causes NPE

I am new to Java and I have a Problem concerning Java Annotations.
Short: The code works just fine, when I set @Target to "TYPE" and place the Annotation above the "SynCheck"-class. As soon as I change @Target to "METHOD" (as seen in the source code) and place the Annotation over the "isValid"-method, it causes a NullPointerException and I cannot figure out, why.
Please have a look on the code. (It is kind of a email syntax validator).
Main.java:
package emailvalid;
import java.lang.annotation.Annotation;

public class Main {

    public static void main(String[] args) throws Exception {

        SynCheck validate = new SynCheck();

        Class<? extends SynCheck> c = validate.getClass();
        Annotation an = c.getAnnotation(InputVal.class);
        InputVal s = (InputVal)an;

        System.out.println(s.input());
        System.out.println("Syntax: " + SynCheck.isValid(s.input()));

    }
}

SynCheck.java:
package emailvalid;
import java.util.regex.Pattern;

public class SynCheck {
    @InputVal(input = "example@domain.org")
    public static boolean isValid(String checkAddr)
    {
        final Pattern regexevalpat = Pattern.compile(
        "^((?=.{1,63}$)[a-zA-Z0-9]+[a-zA-Z0-9\\.\\!\\#\\$\\%\\&\\’\\*\\+\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~\\-]{0,})@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z0-9-]+$");
        if (!regexevalpat.matcher(checkAddr).matches()) {
                return false;
            } else {
                return true;
            }
    }
}

InputVal.java:
package emailvalid;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface InputVal {

    String input();
}

What am I doing wrong?
Any help appreciated.
Thank you.

A:

Your code does not look for the annotation on the method. Only on the class.
 SynCheck validate = new SynCheck();
 Class<? extends SynCheck> c = validate.getClass();
 Annotation an = c.getAnnotation(InputVal.class);
 InputVal s = (InputVal)an;

That will only work if the InputVal annotation is on the SyncCheck class (as a type annotation).
When you move the annotation to the method the annotation will be null as it's no longer on the class...
If you want to put it on the method you need to change your code to:
 Class<? extends SynCheck> c = validate.getClass();
 Method m = c.getMethod("isValid");
 InputVal s = m.getAnnotation(InputVal.class);

A side comment is that you don't have to cast the annotation, you can retrieve it directly into the type it is.


Q:

Spring Data JPA. Repositories Inheritance, throws BeanCreationException, NullPointerException

So I started using Spring Data JPA, I find it very easy to use at first especially with simple POJO entities, I managed to perform simple CRUD operations with a single entity (Person), but as I dig deeper with my design(inheritance), I'm starting to have a hard time dealing with Spring JPA repositories when it comes to inheritance design.
Legend :
POJOs
Repositories
Sample class that uses those two above
Exceptions thrown
xml configuration
Person class (base, abstract class)
 @MappedSuperclass
 public abstract class Person {
       ..properties, getters and setters with hibernate annotations
}

Student class (child, extends Person)
 @Entity
 @Table(name = "STUDENT")
 public class Student extends Person {
        .. properties, getters and setters SPECIFIC for a student
 }

REPOSITORIES
PersonRepository (base, parent repository)
 public interface PersonRepository<T extends Person, ID extends Serializable> extends JpaRepository<T, ID> {
 }

StudentRepository (child, extends PersonRepository)
 public interface StudentRepository extends PersonRepository<Student, Integer>{
 }

Sample class
 @Service ("manager")
  public class Manager {

  @SuppressWarnings("rawtypes")
  @Resource (name = "personRepository")
  private PersonRepository personRepository;

  @SuppressWarnings("unchecked")
  public void savePerson(Person p) {

      personRepository.save(p);
  }
}

Exceptions thrown

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'manager': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personRepository': FactoryBean threw exception on object creation; nested exception is java.lang.NullPointerException
      at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:308)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
      at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
      at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
      at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
      at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
      at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
      at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
      at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
      at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
      at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)
      at edu.main.Main.main(Main.java:12)
  Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personRepository': FactoryBean threw exception on object creation; nested exception is java.lang.NullPointerException
      at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:175)
      at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:103)
      at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1512)
      at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:313)
      at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
      at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:446)
      at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:420)
      at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:545)
      at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:155)
      at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
      at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:305)
      ... 13 more
  Caused by: java.lang.NullPointerException
      at java.lang.Class.isAssignableFrom(Native Method)
      at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getMetadata(JpaEntityInformationSupport.java:58)
      at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:145)
      at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:83)
      at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:66)
      at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:146)
      at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:120)
      at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:39)
      at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:168)

xml Configuration
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:repository="http://www.springframework.org/schema/data/repository"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:tx="http://www.springframework.org/schema/tx"             xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
     http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context-4.0.xsd
     http://www.springframework.org/schema/tx
     http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
     http://www.springframework.org/schema/data/repository
     http://www.springframework.org/schema/data/repository/spring-repository.xsd
     http://www.springframework.org/schema/data/jpa
     http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

<context:annotation-config />
<context:component-scan base-package="edu.service" />
<jpa:repositories base-package="edu.repository" />
<tx:annotation-driven />

<context:property-placeholder
    location="classpath:properties/database.properties"
    ignore-unresolvable="false" />

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
</bean>

<bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan">
        <list>
            <value>edu.domain</value>
        </list>
    </property>
    <property name="persistenceUnitName" value="personPU"/>
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
    </property>
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.show_sql">false</prop>
        </props>
    </property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

I'm trying to to find a specific words to search for a similar problem, but no luck, what could be the problem that causes my repository to not have a repository bean(a NullPointerException/BeanCreationException)?. And another thing I want to add, and am I doing something wrong with my design pattern? should I reflect my POJOs inheritance pattern to my Repositories? I'm trying to make my PersonRepository perform operations on my POJO/Entites that are children of the Person class(abstract parent), thats why I came up with the idea of repository inheritance. My specific goal is, Persist/Perform CRUD on any objects that extends the Person using PersonRepository. Any help/suggestion/comments is greatly appreciated. Please. Thank you so much

A:

I believe the PersonRepository should be annotated with @NoRepositoryBean.
In my application I've done it this way:
Parent:
@NoRepositoryBean
public interface UserRepository<T> extends JpaRepository<T, Long> {
}

Child:
@Repository
public interface EmployeeRepository extends UserRepository<Employee> {
}

Hope it helps.


Q:

Will it soon be possible to render an Eevee animation in realtime (2.8 Beta)?

What I tried:

Most available tutorials
Some render / file format settings

The result: A 2 minutes long animation that plays fine in realtime takes a day or two to render on a GTX 1080.
There's no button to just "play out to a file".
My question is not "how", cause obviously there's no way right now. The question is: is it on the roadmap and will it come with the release of 2.80?
EDIT: Question was misunderstood - I have a complex scene in Eevee (not the default cube). It looks awesome and plays at close to 60FPS inside Blender. So if I would grab it with say an external video recorder, my scene "render" would be finished in 2 minutes (or as long as it plays). But using Blender's "render animation", still with Eevee and the same settings as the realtime window, it takes a day to render out to files. Can't I just "play it out"?

A:

I think what you are looking for is this!

A:

If I understand you correctly, the question is why it renders slower than it plays back when the render is the same image like the viewport.
That could have a number of reasons:
I'd compare this to the (much more stable) opengl render option from 2.7:
It also renders exactly what the viewport sees and still doesn't achieve the same framerate, probably a second or less per frame. The reason for that is that it is making an image out of every frame, it needs to store the data. Displaying a frame takes much less resources than saving it to your harddrive.
The second thing is:
Have you ever noticed that things like subsurface scattering in eevee tend to look a little weird while moving the viewport around? The reason for that is that it only renders lower quality reflections etc when moving it around. And then it starts to render better versions when the viewport stays still for a while (a little bit like the cycles preview). With a complex scene it will start to "downgrade" more materials while moving the viewport. When you render the animation out, it calculates high quality reflections every frame which takes much longer. That's why the viewport appears so much faster.
Depending on the length of your animation, the few seconds more per frame might add up. Just "playing out the animation" might be possible by just lowering the quality if that's what you want. Plus the processing after rendering the image might be badly optimized, you just don't realize it when using cycles because it takes long anyway. But rendering it in the exact same time as the playback is physically impossible as it needs to do more processing.


Q:

how to make a multiple node js chat like facebook?

well, i have read some tutorials and i have a chat in node js with express and socket io, it works well!!
so, the way it works is:
a user that opens the url in the port 3000 connects and now cant send messages, if another user connects in the same url and port now can see the new messages an he can send messages too.
i want to have multiple scenarios like this in the same app, to make something like facebook chat!!,
thanks!
this is the code i have:
server side:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){

res.sendFile(__dirname+'/index.html');

});

io.on('connection', function(socket){
console.log('a user connected');

socket.on('chat message', function(msg){
io.emit('chat message', msg);
});

 socket.on('disconnect', function(){
console.log('user disconnected');
});
});

http.listen(3000, function(){
console.log('listening on *:3000');
});

in client side javascript:
 var socket = io();
  $('form').submit(function(){

    socket.emit('chat message', {message: $('#m').val(), type_msg: 'chat_message'});

    $('#m').val('');
    return false;
  });

  socket.on('chat message', function(msg){

   switch(msg.type_msg){
       case "chat_message":
             $('#messages').append($('<li>').text(msg.message));
           break;

        case "user_is_typing":
            $('#status').val(msg.message);
            break;

        case "user_is_not_typing":
           $('#status').val(msg.message);
            break;
       }
      });

  $('#m').keypress(function(){

    socket.emit('chat message', {message: "User is typing! :D",type_msg: "user_is_writing"});
  });

  $('#m').keyup(function(){

    socket.emit('chat message', {message: "User in thinking...",type_msg: "user_is_typing"});
  });

A:

I see your code is almost the same as socket.io chat tutorial. First of all, if you want to have a Facebook-like chat, you must think about authenticating users, for which I recommend you to use passport. I recommend you to give a look to this example and, if you have further questions about implementing something like that in your web app, you will find helpful links at the bottom of the README.
Once you have passport implemented, you can use socket.io-passport module (my apologies for not providing a link, but I am not allowed to post more than 2 links with my newbie reputation) to identify which user is triggering each socket connection or, if you want to write a less dependant application, you can write your own logic. For example, you can pass the req.user._id to the client by writing something like this in your routes file:
res.render('yourtemplate.ejs', { userId : req.user._id });

On the client side, you can trigger a kind of handshake event using that id once the page is loaded:
var myId = '<%= userId %>';
socket.emit('handshake', myId);

And, on server side again, listen to that event and act properly:
var userSocket = [];
socket.on('handshake', function (user) {
  if (userSocket[user] === undefined) userSocket[user] = [];
  userSocket[user].push(socket.id);
}

Now you have a two-dimensional array which identifies all sockets used by every user. It allows you to send messages to a certain user:
socket.on('chat message', function (msg) {
  for (var i = 0 ; i < userSocket[msg.to].length ; i++ ) {
    io.to(userSocket[msg.to][i].emit('chat-message', msg);
  }
});

NOTE: As you can see, msg has become an object, not a string. It follows this structure:
{
  from : userId,
  to   : userId,
  text : The message itself
}

This is a very tight guideline, but I think it's enough to give you the idea of what you can do. Of course, you have to append the message to the according DOM element depending of who's sending the message, you have to delete the socket.id on userSocket when an user disconnects, and so on.
I hope it helps!
;)


Q:

Cross tabulation from column comparisons

I have a dataframe from which I would like to perform pairwise comparisons between values of each column. Ultimately I aim to get a cross tabulation of the comparisons, where each value represents the percentage of similarity between the samples in compared columns. For a replicate and what I have tried thus far:
a <- c(1:30)
b <- c(30:1)
c <- c(1:10,30:11)
data <- as.data.frame(matrix(c(a,b,c), ncol = 3, nrow = 30))

fr<-apply(combn(1:length(data), 2), 2, function(x) {
result <- as.data.frame(table(
    factor(sign(data[,x[1]] - data[,x[2]]), levels=c(0), labels=c("Fr"))
))
colnames(result)[1] <- paste(x, collapse="|")
return(result)
})
fr  # returns a list of each comparison, with its respective similarity count

a<-sapply(fr, unlist)   # My attempt to get a dataframe/matrix of the results
t(a)

    t(a); sapply(fr, unlist);  do.call(cbind, fr) # I get different arrangements, but none in the form:

     1|2      0
     1|3      10
     2|3      0

Once I get a dataframe in that format, it would become more straight forward to get a crosstab table,
     V.1    V.2    V.3
 V.1  -
 V.2  0    -
 V.3  10   0    -

This is what I am ultimately looking for, although the values in the cross-tab table would be #/nrow to obtain the respective percentage value. I am not sure if I am going about this the wrong way, but any input would be appreciated

A:

You can try:
 Cmbn <- combn(seq_along(data),2)
 nm1 <- apply(Cmbn, 2, paste, collapse="|")

 f1 <-  setNames(
           apply(Cmbn, 2, function(x) {
               x1 <- sign(data[,x[1]]- data[,x[2]])
               table(factor(x1, levels=0, labels="Fr")) #not sure why you wanted a label "Fr" as it didn't appear in the results
                           }),
                               nm1)

  f1
  #1|2 1|3 2|3
  #0  10   0

 names1 <- paste("V", 1:3, sep=".")
 m1 <- matrix(0, 3,3, dimnames=list(names1, names1))
 m1[paste(col(m1), row(m1), sep="|") %in% names(f1)] <- f1
 d1 <- as.data.frame(m1)
 d1[upper.tri(d1, diag=TRUE)] <- "-"
 d1
 #    V.1 V.2 V.3
 #V.1   -   -   -
 #V.2   0   -   -
 #V.3  10   0   -


Q:

PeriodicSync is not working in android kitkat and lollipop

I am performing sync in my application for every 12 hours ,earlier i tried in android 4.4 below versions sync adapter is working fine, but kitkat and above periodicsync is not even triggering please help me.
public static void configurePeriodicSync(Context context, int syncInterval, int flexTime) {
    Account account = getSyncAccount(context);
    String authority = context.getString(R.string.content_authority);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        // we can enable inexact timers in our periodic sync
        SyncRequest request = new SyncRequest.Builder().
                syncPeriodic(syncInterval, flexTime).
                setSyncAdapter(account, authority).build();
        ContentResolver.requestSync(request);
    } else {
        ContentResolver.addPeriodicSync(account,
                authority, new Bundle(), syncInterval);
    }
}

A:

I have solved this question,for kitkat and above we need to write separate code
code:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            SyncRequest.Builder b = (new SyncRequest.Builder()).syncPeriodic(syncInterval, flexTime);
            b.setSyncAdapter(account, authority);
            b.setExtras(new Bundle());
            ContentResolver.requestSync(b.build());
        } else {
            ContentResolver.addPeriodicSync(account, authority, new Bundle(),
                    syncInterval);


Q:

Component identification request

Just bought a bunch of transistors and one supposedly to be requested as a 2N7000 general purpose mosfets or J201 FETs... Finally unpacked everything and it came in this smaller than a SOIC8 pinout, micro-smd package.
Component marking says K27 0N.
It's very likely a lcd-set mosfet 2n7000, eventually a dual positive-negative pair of mosfets or a dual-in-packs according to some datasheets.
Couldn't find any datasheets on 6 pin mosfets.
Can you help me out finding a datasheet or pinout diagram? thank you.

A:

please follow the link to find datasheet.
http://html.alldatasheet.com/html-pdf/308586/WEITRON/2N7002KDW/296/1/2N7002KDW.html
K27 is SMD product type marking information


Q:

checking of the stream result?

I have two questions on the following simple code:
/*
test.cpp
© BS.
Example of creation of a class of a flow for which it is possible to assign the additional
characters interpreted as separators.
11/06/2013, Раздел 11.7
*/
//--------------------------------------------------------------------------------------------------
#include <iostream>
#include <sstream>
#include <algorithm>
#include <exception>
#include <string>
#include <vector>
using namespace std;
//--------------------------------------------------------------------------------------------------
class Punct_stream
// it is similar to istream flow, but the user can independently set separators.
{
private:
    istream& source; // source of chars
    istringstream buffer; // buffer for formatting
    string white; // whitespaces
    bool sensitive; // case sensitive
public:
    Punct_stream(istream& is): source(is), sensitive(true) {}
    void whitespace(const string& s) { white = s; }
    void add_white(char c) { white += c; }
    void case_sensitive(bool b) { sensitive = b; }
    bool is_case_sensitive() { return sensitive; }
    bool is_whitespace(char c);
    Punct_stream& operator >> (string& s);
    operator bool();
};
//--------------------------------------------------------------------------------------------------
bool Punct_stream::is_whitespace(char c)
// is the c a whitespace?
{
    for(int i = 0; i < white.size(); ++i) if(c == white[i]) return true;
    return false;
}
//--------------------------------------------------------------------------------------------------
Punct_stream::operator bool()
// check the input result
{
    return !(source.fail() || source.bad()) && source.good();
}
//--------------------------------------------------------------------------------------------------
Punct_stream& Punct_stream::operator >> (string& s){
    while(!(buffer >> s)){ // try to read the data from the buffer
        if(buffer.bad() || !source.good()) return *this;
        buffer.clear();

        string line;
        getline(source,line); // read the line from the source

        // if necessary we replace characters
        for(int i = 0; i < line.size(); ++i)
            if(is_whitespace(line[i])) line[i] = ' ';
            else if(!sensitive) line[i] = tolower(line[i]);
            buffer.str(line); // write a string line to the stream
    }
    return *this;
}
//==================================================================================================
int main()
// entry point
try{
    Punct_stream ps(cin);
    ps.whitespace(";:,.?!()\"{}<>/&$@#%^*|~");
    ps.case_sensitive(false);
    cout << "Enter the words, please: ";
    vector<string> vs;
    string word;
    while(ps >> word) vs.push_back(word); // enter words
    sort(vs.begin(), vs.end());
    // we delete counterparts
    for(int i = 0; i < vs.size(); ++i) if(i == 0 || vs[i] != vs[i-1]) cout << vs[i] << endl;
}
catch(exception& e){
    cerr << e.what() << endl;
    return 1;
}
catch(...){
    cerr << "Unknown exception." << endl;
    return 2;
}

The checking in the Punct_stream::operator bool() function is not clear for me:
return !(source.fail() || source.bad()) && source.good();

My questions:

Why author checked the 'fail' and the 'bad'? Why it wasn't restricted the 'good' check only? Unless the positive 'good' automatically doesn't imply, what 'fail' and 'bad' are set in 'false' value?
Besides, often in a code write such construction:cin >> x; while(cin){//...}

Why the author didn't write by analogy so:
Punct_stream::operator bool()
// check the input result
{
    // return !(source.fail() || source.bad()) && source.good();
        return source;
}

The alternative option shown by me doesn't work for me (Windows crashed), it would be desirable to understand why, what I missed?
Thank you.

A:

The istream object contains a bunch of bit flags that represent its internal status. Of them, the ones that interests you are:
eofbit  End-Of-File reached while performing an extracting operation on an input stream.
failbit The last input operation failed because of an error related to the internal logic of the operation itself.
badbit  Error due to the failure of an input/output operation on the stream buffer.
goodbit No error. Represents the absence of all the above (the value zero).

Their status is represented in the following table
                                                good()  eof()   fail()  bad()
goodbit No errors (zero value iostate)          true    false   false   false
eofbit  End-of-File reached on input operation  false   true    false   false
failbit Logical error on i/o operation          false   false   true    false
badbit  Read/writing error on i/o operation     false   false   true    true

Respectively, good() returns the goodbit, eof() checks the eofbit, fail() checks the failbit, and, surprisingly, bad() returns the badbit.
So depending on what you are doing, each function could be used in a different settings.
However, in your case, simply checking the trueness of the good bit would be enough, as it is true when the others are all false. Testing at the same time the failbit or the badbit is redundant.
source: http://www.cplusplus.com/reference/ios/ios/
EDIT:
Actually I'm not really sure why your alternative wouldn't work, as it works for me. What data did you exactly pass to the program?


Q:

Is there an infinite product for $\left(\frac{\eta(13\tau)}{\eta(\tau)}\right)^2$ analogous to the Rogers-Ramanujan identity?

Given
$$
\left(\frac{\eta(5\tau)}{\eta(\tau)}\right)^{6}\;\; =\;\; \frac{r^5}{1-11r^5-r^{10}},\;\;\;\;\;\text{with}\;\;r\; =\; q^{1/5} \prod_{n=1}^\infty \frac{(1-q^{5n-1})(1-q^{5n-4})}{(1-q^{5n-2})(1-q^{5n-3})}$$
where $\eta(\tau)$ is the Dedekind eta function,
$$\eta(\tau) = q^{1/24} \prod_{n=1}^\infty (1-q^n)$$
and $q = \exp(2\pi i\tau)$, is there an analogous identity for,
$$
\left(\frac{\eta(13\tau)}{\eta(\tau)}\right)^{2}\;\; =\;\; ???$$

A:

Yes. Michael Somos just today found the identity,
$$
\left(\frac{\eta(13\tau)}{\eta(\tau)}\right)^{2} = \frac{s}{s^2-3s-1}$$
where,
$$s=\frac{1}{q}\; \prod_{n=1}^\infty \frac{ (1-q^{13n-2})(1-q^{13n-5})(1-q^{13n-6})(1-q^{13n-7})(1-q^{13n-8})(1-q^{13n-11}) }{(1-q^{13n-1})(1-q^{13n-3})(1-q^{13n-4})(1-q^{13n-9})(1-q^{13n-10})(1-q^{13n-12})} $$
thus completing the family for $N = 2,3,5,7,13$.
Kindly see this MSE post for the other N. Does address Matt E and Loeffler's comments in that post? Is "s" a modular function?


Q:

Bioconductor vs CRAN

Today I've discovered that there is another repository except CPAN. This repository is Bioconductor. So far I've noticed that Bioconductor's installation process is slightly different compared to classic CRAN's install.packages(). Should I worry when I want to use some packages from Bioconductor? Is it possible to get into some dependencies problems (as when you are mixing e.g. ubuntu/debian repositories etc.) etc.? I'm asking because e.g. this says:

If you dont mind using bioconductor packages, then, You can use...

What is wrong with Bioconductor or potentially another repositories?

A:

BioConductor is very well structured, tested and operating. There is nothing wrong with it.  Please just read up on it yourself.
And please do understand there is practically no limit to the number of different repositories you can use.  'Base R' already knows about CRAN, BioConductor and OmegaHat (though I am unsure how active it currently is, it too has a proud 15 year history).
Lastly, you easily build / host / use your own repositories using drat.


Q:

Razor Tag Helper - Binding to a Collection

Using ASP.NET Core 2.2 I am trying to build a Tag Helper that will bind to a ModelExpression representing a collection of SelectListItems.  I then want to be able to access and iterate over the SelectListItems contained in the list.
In code terms, it looks something like this...
[HtmlTargetElement("check-box-list", Attributes = "asp-for)]
public class CheckboxListTagHelper : TagHelper
{
    // Where the model is an IEnumerable<SelectItemList>
    [HtmlAttributeName("asp-for")]
    public ModelExpression AspFor { get; set; }

    public override async Task ProcessAsync(
        TagHelperContext context, TagHelperOutput output)
    {
        // I want to be able to reference the IEnumerable<SelectListItem>
        // represented by the model
        var modelItems = AspFor.Model as IEnumerable<SelectListItem>; // WRONG!
        ...
    }
}

I assume I  need to use the ModelExpression.MetaData or the ModelExpression.ModelExpolorer properties, but I can't find any information that points me in the right direction.
An inelegant fix has been to supply the same model as an additional property:
[HtmlAttributeName("select-item-list")]
public IEnumerable<SelectListItem> SelectItemList { get; set; }

But this looks messy in the view:
<check-box-list
    asp-for="SelectedAuthorityLevels"
    checkbox-list="Model.SelectedAuthorityLevels" />

as you are binding to the same model property twice.
Any guidance would be much appreciated.

A:

The answer was, in the end, very easy - since I know the expression type, I can simply cast it as follows:
var selectList = AspFor.Model as IEnumerable<SelectListItem>;

if (selectList == null) {
   var msg = "CheckboxList tag helper attribute 'asp-for' must of type " +
      "IEnumerable<Microsoft.AspNetCore.Mvc.Rendering.SelectListItem>!";
   throw new Exception(msg);
}


Q:

HTML, PHP and javascript

I am new to php, html and javaScript.. I still do not understand the connection between the three. SO this may sound silly.
I know that php is a server side language. But that fact is not very clear to me since we can use php code inside html..
So my question is if i wrote the following, where does the  part runs on?? does that piece of code is sent to the client browser and execute it at client side? or execute on the server side and upload the result to the client side?
<!DOCTYPE html>
<html>
<body>

<?php
echo "My first PHP script!";
?>

</body>
</html>

A:

It is run on the server, the output html is sent to the client, and your browser displays it.


Q:

How to Display Multiple location in Google Map in Blackberry 5.0?

i m using GPS in my application. i had try lots of for display multiple location on map but till i m not getting any solution. if anybody have solution to overcame my this problem. i had try using this code.
please help me.
Thanx in advance.
        StringBuffer document = new StringBuffer();

        document.append("<location-document>");

        latVec.addElement("19.097971");
        longVec.addElement("72.864761");
        latVec.addElement("19.066985");
        longVec.addElement("72.848969");
        addressVec.addElement("abc");
        addressVec.addElement("wydj");

        for(int j=0;j<latVec.size();j++)
        {
            double latlong = Double.parseDouble(latVec.elementAt(j).toString());
            double lonlong = Double.parseDouble(longVec.elementAt(j).toString());

            int lat = (int)latlong*100000;
            int lon = (int)lonlong*100000;
            String addressString = addressVec.elementAt(j).toString();

            document.append("<location lon='"+ lon +"' lat='"+ lat +"'label='"+ addressString +"' description='"+ addressString +"' />");

        }

        document.append("</location-document>");

        String st = new String(document);

        Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, new MapsArguments(MapsArguments.ARG_LOCATION_DOCUMENT, st));

A:

package map;
import java.util.Vector;

import net.rim.blackberry.api.browser.Browser;
import net.rim.blackberry.api.browser.BrowserSession;
import net.rim.device.api.browser.field2.*;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.container.*;

public class NewBrowserFieldDemo extends UiApplication
{
    public static void main(String[] args)
    {
        BrowserFieldDemo app = new BrowserFieldDemo();
        app.enterEventDispatcher();
    }
    public NewBrowserFieldDemo()
    {
        pushScreen(new MultiplePoints());
    }
}

         class MultiplePoints extends MainScreen{
            String initial = "<!DOCTYPE html>\r\n" +
                    " \r\n" +
                    " \r\n" +
                    "  <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\" /> \r\n" +
                    "  <title>Google Maps Multiple Markers</title> \r\n" +
                    "  \r\n" +
                    " \r\n" +
                    "\r\n" +
                    "

\r\n" +
                    "\r\n" +
                    "  \r\n" +
                    "\r\n" +
                    "";
            String[] lt={"12.966085","12.944337","12.925599"};
          String[] lon={"77.533264","77.549400","77.594719"};
          String[] name={"vijyanagar","Banashankari","jaynagar"};
            MultiplePoints(){//StringBuffer html,Vector waypoints,LocationObj center){
                StringBuffer html=new StringBuffer();
                html.append(initial);
                for(int i=0 ; i<lt.length; i++){
                    //LocationObj source = (LocationObj)waypoints.elementAt(i);
                    //String point = "['"+source.getLabel()+"',"+source.getLatitude()+","+ source.getLongitude()+","+i+"],";
                    String point = "['"+name[i]+"',"+lt[i]+","+ lon[i]+","+i+"],";
                    //System.out.println("Point is"+point);
                    html.append(point);
                }
                html.append(second);
                centerPoint = "  center: new google.maps.LatLng("+lt[0]+","+lon[0]+"),";
                html.append(centerPoint);
                html.append(finalpart);
                //System.out.println("Plot is"+html.toString());
                BrowserFieldConfig _bfConfig = new BrowserFieldConfig();
              _bfConfig.setProperty(BrowserFieldConfig.NAVIGATION_MODE,BrowserFieldConfig.NAVIGATION_MODE_POINTER);
              _bfConfig.setProperty( BrowserFieldConfig.JAVASCRIPT_ENABLED, Boolean.TRUE );
             _bfConfig.setProperty(BrowserFieldConfig.USER_AGENT, "MyApplication 1.0");

              BrowserField myBrowserField = new BrowserField(_bfConfig);

              myBrowserField.displayContent(html.toString(), "http://localhost");
              HorizontalFieldManager horf=new HorizontalFieldManager(HORIZONTAL_SCROLL);
              horf.add(myBrowserField);
              add(horf);
            }
        }


Q:

How to move Odoo 9 from one server to another?

We have moved Odoo Server one to another local Ubuntu Server. I have backed up our database from the admin dashboard. I have a few questions.

Which files should I move to other servers?
Do we need install software like OpenERP, PostgreSQL in the new server?
Do we need install dependencies such as wkhtmltopdf?

A:

You need:

Backup you Database to restore it afterwards on your new server. The safest way is to do it within the Odoo Database Manager. If the restoration does not succeed, sometimes this happens, try to copy and restore it by hand with pg_dump and pg_restore, or retore it with psql and copy your filestore to the right destination.
Copy your Complete Instance (Odoo source code). This is at least all the Odoo modules you are using in your old server, including base modules and where the Odoo launcher is stored and your custom modules.
Copy your Service and Configuration File.
Install all the Odoo dependencies and the dependencies of all the modules you are using. These dependencies includes PostgreSQL and Wkhtmltopdf among others.
Note: Sometimes you need to keep the same versions of some dependencies. If something goes wrong make sure you have the same version or a compatible version installed


Q:

Why elseif condition doesn't work?

<?php

    $datetime=date("d-m-y");
    $date1=date("d")+1;
    $datetime1=date("$date1-m-y ");
    $date1=$date1+1;
    $datetime2=date("$date1-m-y ");
    $date1=$date1+1;
    $datetime3=date("$date1-m-y ");

    echo $_POST['date1'];
    echo $datetime1;

    if($_POST['date1']==$datetime1)
    {
        header("location:bus2.php");
    }

?>

here if condition doesn't work  even though echo $_POST['date1']; and echo $datetime1; shows the same result.

A:

The values are NOT the same:
$datetime1=date("$date1-m-y ");
                           ^--this space makes all the difference:

$_POST['date1'] = '14-02-2014';
$datetime1      = '14-02-2014 ';
                             ^--- spot the difference


Q:

Declare the nativeptr type

I'd like to know if it's possible in F# to declare the type:
nativeptr<unit>

This seems not possible (compiler complains with "A generic construct requires that the type 'unit' is an unmanaged type"). Is there a workaround I could use?
The ultimate goal is to declare my own blitDelegate for exposing the opcode Cpblk to some of my F# code.
Thanks.
Edit:
Here's what I've tried based on kvb's answer:
type blitDelegate<'T when 'T : unmanaged> = delegate of nativeptr<'T> * nativeptr<'T> * uint32 -> unit

let createBlitDelegate<'T when 'T : unmanaged>() =
    let dm = new DynamicMethod("blit",
                               typeof<System.Void>,
                               [| typeof<nativeptr<'T>>; typeof<nativeptr<'T>>; typeof<uint32> |])
    let ilGenerator = dm.GetILGenerator()
    ilGenerator.Emit(OpCodes.Ldarg_0)
    ilGenerator.Emit(OpCodes.Ldarg_1)
    ilGenerator.Emit(OpCodes.Ldarg_2)
    ilGenerator.Emit(OpCodes.Cpblk)
    ilGenerator.Emit(OpCodes.Ret)
    dm.CreateDelegate(typeof<blitDelegate<'T>>) :?> blitDelegate<'T>

let blit (blitDel:blitDelegate<'T>) dst src byteWidth = blitDel.Invoke(dst, src, byteWidth)

Then I call this code from a class member like that:
let dst = //get nativeint destination address
let src = //get nativeint source address

let bd = createBlitDelegate<'T>()

let tdst = NativePtr.ofNativeInt<'T> dst
let tsrc = NativePtr.ofNativeInt<'T> src

do blit bd tdst tsrc (uint32 size)
//Program.MemCpy.Invoke(dst.ToPointer(), dst.ToPointer(), uint32 size)

This results in a runtime error at blit (System.Security.VerificationException: Operation could destabilize the runtime.)
The commented code works well (and can be found here) but my point was to code it in F# (not C#).
The reason why I wanted to use at first a nativeptr<unit> is that it is actually the type of the two first arguments of MemCpy delegate (that matches void* type) and somewhat wanted to mimic it.
Edit2:
Based on kvb's edit, I modified my code to host the delegate creation in a type using static members (like the C# version) and it now works.
I don't use the version with the unmanaged constraint but this one, since I actually need to blit array of structs:
type blitDelegate = delegate of nativeint * nativeint * uint32 -> unit

A:

From your description, it's not clear to me why you'd like a nativeptr<unit>.  Essentially, nativeptr<'t> is just a thin wrapper over nativeint with some helpers for doing arithmetic on the pointer.  Since you're unlikely to have an array of units, I don't see how this actually helps you, though.  Perhaps if you show more of your code it will be easier to give a more satisfactory answer.
EDIT
I think you're doing almost everything right.  However, anonymously hosted DynamicMethods must be verifiable, and the cpblk opcode is never verifiable.  Try using a different constructor for DynamicMethod to host it on a type or module.


Q:

Android Fragment Tabs throwing error

I am trying to create 2 tabs and 2 different activities for 2 tabs. But throwing error during start activity.  Here is my code:
public class CashSales extends FragmentActivity {
    private FragmentTabHost mTabHost;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.cash_sales_tab);
        mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

        mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Simple"),
                CustomerAddActivity.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("Contacts"),
                ItemAddActivity.class, null);
    }
}

Here is my activity that will appear in one tab.
   public class CustomerAddActivity extends FragmentActivity {
        private EditText mName;
        private EditText mEmail1;
        private Integer mPkid;

        @Override
        protected void onCreate(Bundle bundle) {
            super.onCreate(bundle);
            setContentView(R.layout.activity_customer_add);

            mName = (EditText) findViewById(R.id.customer_add_name);
            mEmail1 = (EditText) findViewById(R.id.customer_add_email1);
            Button confirmButton = (Button) findViewById(R.id.customer_add_button);
'''''''''''''''''''''''''''
        }
    }

CatLog:
02-26 05:52:39.732: E/AndroidRuntime(25579): FATAL EXCEPTION: main
02-26 05:52:39.732: E/AndroidRuntime(25579): java.lang.ClassCastException: asia.wavelet.android.customer.CustomerAddActivity cannot be cast to android.support.v4.app.Fragment
02-26 05:52:39.732: E/AndroidRuntime(25579):    at android.support.v4.app.Fragment.instantiate(Fragment.java:394)
02-26 05:52:39.732: E/AndroidRuntime(25579):    at android.support.v4.app.FragmentTabHost.doTabChanged(FragmentTabHost.java:339)
02-26 05:52:39.732: E/AndroidRuntime(25579):    at android.support.v4.app.FragmentTabHost.onAttachedToWindow(FragmentTabHost.java:276)

A:

You are giving the addTab method an activity instead of a fragment here:
mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Simple"),
                CustomerAddActivity.class, null);
 mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("Contacts"),
                ItemAddActivity.class, null);

That's why the system is trying to cast the activity to a fragment and throwing a ClassCastException.


Q:

Routing DNS (Route 53) to an Elastic Beanstalk application without a loadbalancer

Can I route a dns I registered to an Elastic Beanstalk application without a load balancer?
If so - How? all of the examples show how to do this with a LB..

A:

Can I route a dns I registered to an Elastic Beanstalk application
  without a load balancer?

Yes, you can use Single instance type.

If so - How? all of the examples show how to do this with a LB..

By adding a CNAME which pointed to your EB URL in Route 53.


Q:

Who invented these key notions in Finance?

We often give credit to the origins of academic achievements. The Black-Scholes equation or the Gibbons Ross Shanken (GRS) test etc.
What about

Net Present Value (NPV),
Internal Rate of Return (IRR),
Duration of bonds,
Law of One Price (LOP),
Time value of money,
Stochastic Discount Factor (SDF) or pricing kernel?

These are fundamental things which are taught to undergraduates in one way or the other. But who first came up with these ideas?

A:

Net Present Value (NPV) as a soft concept existed probably even in antiquity but it was formalized and made popular by Irving Fisher in his book the Rate of Interest.
Internal rate of return is basically a special application of NPV. It was also first formally introduced in Fisher's book although he called it 'rate of return over costs'.
Duration of bonds was introduced by Canadian economist Frederick Macaulay, but the concept was later greatly expanded by none other than Fisher together with Weil.
Law of One Price I was not able to trace this idea back to any single person. According to this article:

The intellectual history of the concept can be traced back to economists active in France in the 1760-70’s, which applied the “law” to markets involved in international trade. Most of the modern literature also tends to discuss the “law” in that context.

But no exact names are mentioned. It might be that the original authors are unknown. As @Henry pointed out in his comment, these were most likely the French Physiocrats.
Time value of money this like the NPV, a vague notion that existed already in antiquity. You can find a lot of antique quotes that boil down to saying “time is money”, but more formally, it was introduced to the west by Martín de Azpilcueta of the School of Salamanca.
Stochastic Discount Factor - as in its modern mathematical representation can be traced back to the works of Harrison and Kreps (see 1), and Hansen et al (see  [2-5]). However, as pointed out in @Michael +1 comment, the concept can be already traced back all the way to Arrow-Debreu and Radner. Of course, on this subtopic, the list of sources is not exclusive.
1 Harrison, J. M., & Kreps, D. M. (1979). Martingales and arbitrage in multiperiod securities markets.
Journal of Economic Theory 20, 381-405.
[2] Hansen, L. P. (1982). Large sample properties of generalized method of moments estimators.
Econometrica, 50, 1029-1054.
[3] Hansen, L. P., & Jagannathan, R. (1991). Implications of Security Market Data for Models of Dynamic
Economies. Journal of Political Economy 99(2), 225-262.
[4] Hansen, L. P., & Richard, S. F. (1987). The role of conditioning information in deducing testable
restrictions implied by dynamic asset pricing models. Econometrica 55(3), 587-613.
[5] Hansen, L., & Singleton, K. (1983). Stochastic Consumption, Risk Aversion and the Temporal Behavior
of Asset Returns. Journal of Political Economy 91(2), 249-265.


Q:

Category with translation

Let $C$ be a category with a translation $\tau:C\rightarrow C$ (i.e, an equivalence of categories). I've been trying to show that if $C$ is additive then $\tau$ is an additive functor.
I tried to show that $\tau$ preserves direct sums but I've not been successful in this idea.
Thank you in advance if you can give me some idea of how solve it by this way or some hint in another direction.

A:

Any equivalence of categories preserves all limits and colimits that exist.


Q:

Para a Rotação no Eixo Z

Sou novo com os código c# e estou fazendo um movimento básico de rotação no eixo Z no unity 3d, mais estou tendo um problema para parar de rotacionar. O código inicial é esse:
using UnityEngine;
using Sysstem.Collections;

public class voa : MonoBehaviour{

int vel = 150;

// Use this for initialization
void Start (){

}

// Update is called once per frame

void Update () {

if (Input.GetButton("right)){

    transform.Rotate(0,0,vel * Time.deltaTime);

    }

    if (INput.GetButton ("left)){

    transform.Rotate (0,0,-vel * Time.deltaTime);

    }

  }

}

Qual seria a sequencia desse código, para que na hora que o objeto estiver em 80 grau (positivo ou negativo), mesmo apertando o botão das setas ele não passa desse ponto.

A:

O seu código tinha alguns errinhos de digitação e não funcionou aqui diretamente. Bom, tendo eles corrigidos, uma ideia que pode te ajudar é você simplesmente limitar a rotação antes de executá-la. Para isso, acumule o valor da rotação a cada quadro em que isso ocorrer e compare se o valor acumulado excede (tanto no "sentido" positivo como no sentido negativo) a sua rotação máxima. O código a seguir faz isso:
using UnityEngine;
using System.Collections;

public class voa : MonoBehaviour{

    int vel = 150;
    float acumulado = 0;
    public float limite_angular = 90;

    // Use this for initialization
    void Start (){

    }

    // Update is called once per frame

    void Update () {

        if(Input.GetButton ("Horizontal")) {

            float angulo = vel * Time.deltaTime * Input.GetAxisRaw("Horizontal");

            if( (acumulado + angulo) >= limite_angular || (acumulado + angulo) <= -limite_angular)
                angulo = 0;

            acumulado += angulo;
            transform.Rotate (0, 0, angulo);
        }

    }

}

Note que eu estou apenas fazendo essa acumulação no eixo Z (que é o que você usa no seu código original). Se precisar acumular nos três eixos, mude a variável de float para Vector3 e acumule em cada um deles. Note também que eu estou usando a variável "horizontal" ao invés de "right" e "left" (porque esse é o padrão da Unity - ao menos na versão mais recente). E finalmente, note também, que para ter o sinal (positivo ou negativo) basta multiplicar por GetAxisRaw (função que retorna -1 ou 1 para indicar o sentido da movimentação no eixo horizontal).
Ah, eu coloquei a variável limite_angular como pública, pois assim você pode alterar seu valor diretamente na janela do Inspector.


Q:

document.getElementById(...).style.display is blank

function test( id )
{
    alert( document.getElementById( id ).style.display );
}

What exactly does getElementById.style.display return? Is it an object, or a value? The alert shows nothing at all. I'm not using pure numbers for the id and it is unique.

A:

DOM methods like document.getElementById() create objects which point to- and contains certain details about- a specified HTMLElement or set of elements.
Unfortunately the .style property only knows about the style properties set using that same feature. In the example below, clicking what color? will not work until you have clicked change color.

<input type="button" onclick="whatColor();" value="what color?" />
<input type="button" onclick="changeColor();" value="change color" />

I recommend reading PKK's great page on getComputedStyle and currentStyle (IE, of course is different) http://www.quirksmode.org/dom/getstyles.html
At the end of the tutorial, there is a very decent function for your purposes, although frameworks such as jQuery do provide very convenient & powerful functions for styling page elements: http://api.jquery.com/css/


Q:

hibernate does not reconnect once the database is bounced

I've found that after we've bounced (stopped and started) our database (postgresql 8.3), our apps which use hibernate (3.2.6) fail to re-acquire connections, instead getting a SocketException with the message "broken pipe".
I believe we're configured to use the built in connection pooling.
how can i make hibernate re-acquire connections after a db restart without restarting the app?
p.

A:

What you want is a feature called connection testing provided by connection pools - the connection pool should run a quick query to verify that the connection it is about to hand out is not stale. Unfortunately DriverManagerConnectionProvider, Hibernate's default connection pooling class, does not support this feature. Hibernate team strongly discourages the use of this connection pool in production code.

Hibernate's own connection pooling
  algorithm is, however, quite
  rudimentary. It is intended to help
  you get started and is not intended
  for use in a production system, or
  even for performance testing. You
  should use a third party pool for best
  performance and stability.

My recommendation is that you switch to some other connection pool implementation. If you switch to C3P0 (which is shipped with Hibernate), connection testing can be configured as explained here. If you use Apache DBCP, it lets you set a validationQuery as explained here.


Q:

Truffle console - How can I get and print the value returned by a contract function?

This is an absolute newbie question. Given this simple Hello World contract:
pragma solidity ^0.4.4;

contract Greeter {

    function Greeter() {}

    function sayHello() returns(string) {
        return "hello";
    }
}

I deploy it and try to get the value from the sayHello() function:
$ truffle compile
$ truffle deploy
$ Greeter.deployed().then(function(instance){ return instance.sayHello()}).then(function(result){console.log(result);});

I was expecting to see "hello" in the output of the above statement but this is what I actually get:
{ tx: '0xa4333e052b00fdf00d9ad944862b592d091cfb4ff68d610e297cb52cfbf5ebfd',
  receipt:
   { transactionHash: '0xa4333e052b00fdf00d9ad944862b592d091cfb4ff68d610e297cb52cfbf5ebfd',
     transactionIndex: 0,
     blockHash: '0x40aca77673267ca149fe34a62c95b2869285d7819d21279d59fc0714c702314c',
     blockNumber: 64,
     gasUsed: 21867,
     cumulativeGasUsed: 21867,
     contractAddress: null,
     logs: [] },
  logs: [] }
undefined

That is to say, result is an object of this information instead of the "hello" string. Is there a way I can get the actual result of the function?

A:

What you get is the result of the transaction.
You can only get the return value of constant function. Do it like that :
function sayHello() constant returns(string) {
    return "hello";
}

An other solution is to use .call()
function saveData(uint _data) returns(bool) {
    data = _data;
    return true;
}

If you use .call(), the data will not be saved but you will get the return value. The typical case is to call the function with .call() the first time to see if the execution went good, and then call again the function without the .call().

A:

You can achieve the same result with
Greeter.deployed().then(function(instance) {return instance.sayHello.call()})


Q:

variable server performance using DelimiterBasedFrameDecoder

I have a server reading inbound newline-delimited strings. The pipeline looks like this:
    ...
    pipeline.addLast("framer",
        new DelimiterBasedFrameDecoder(65535, Delimiters.lineDelimiter()));

    // plain old strings
    pipeline.addLast("decoder", new StringDecoder());

    // callback to handler
    pipeline.addLast("handler", new ConnectorHandler(collector));
    ...

When I change the decoder to the following:
    pipeline.addLast("framer",
        new DelimiterBasedFrameDecoder(65535,
            new ChannelBuffer[] { ChannelBuffers.wrappedBuffer(
                new byte[] {'\n'})}));

I get a 3-4X increase in server speed. I don't understand why this would be the case. The inbound strings vary betweeen about 1K-4K in length, around 10K strings/sec. Looking at the source code, it appears that it cycles through all the delimiters to find the one yielding the minimum frame length -- by inspection, I don't see how looking for only one delimiter would result in such a performance gain over looking for two delimiters. I am tempted to try to write my own decoder but I would like to understand what's going on here. Any insight would be appreciated.

A:

thats exactly the case.. looking only for one is much more cheap.


Q:

Adding a piece of code to a page: Chrome Extension

Okay, here's what I want my Chrome Extension to do:
It's just a button in the corner, and when you click on it :O it adds a tag(don't want to give the idea away)right after the body tag. I don't want it so like the user gets to edit the html, I just want it so when you click the button it adds a tag, and I was wondering how I could achieve this. JavaScript, or is there something else I could use to get this done. Or is this even possible. Anyone have any idea?
So basically, if this is the html:
<DOCTYPE! html>

    <title>Some title</title>

Some content

Than when you click the button, this happens:
<DOCTYPE! html>

    <title>Some title</title>

     //or some other tag

Some content

A:

I, you should do a content script extension.  Content script code will run in the page, and can add a button wherever you like in the page.  You hang a click listener to it with .addEventListener (all DOM stuff, nothing Chrome extension specific), and so on.  Read about Chrome extensions Content Scripts here.
Your manifest.json should be like this:
{
  "name": "My Extension",
  "version": "0.1",
  "manifest_version": 2,
  "description": "A plain text description",
  "default_locale": "en",
  "content_scripts": [{
    "matches": ["http://*/*", "https://*/*"],
    "js": ["yourScript.js"]
  }],
}

It will inject yourScript.js in every page.  Depends on what are you trying to do, know that yourScript.js has some Content Security Policy limitations you can change.


Q:

Profiling Camel routes using JConsole

I have an application consisting of number of Camel routes; I would need to profile them using JConsole. I have noticed upon bringing up the JConsole and selecting the local JVM that is running these Camel routes; various MBeans under domain name org.apache.camel is displaying information about such as End points, Processors, Routes etc. Note: I did not setup any instructions given on the link Camel JMX
I would like to know how would these instructions differ in the information display in the later case?

A:

By default, JMX instrumentation agent is enabled in Camel which means that Camel runtime creates and registers MBean management objects with a MBeanServer instance in the VM. This allows Camel users instantly obtain insights into how Camel routes perform down to the individual processor's level.
The supported types of management objects are endpoint , route, service, and processor. Some of these management objects also expose lifecycle operations in addition to performance counter attributes.

The other link you referenced describes how to programmatically create listeners for JMX events...


Q:

How do you add Ionic 3 Ipad Styles

how to add Ionic platform specific styles for Ipad.
I have different styles for tablets and mobile displays.
Thanks

A:

You can do it in many ways:
Global style file: app.scss

It is used to declare any styles that will be used globally throughout
  the application

variables.scss

is used to modify the apps shared variables

Here is a great article about it:
This is the official doc about it.


Q:

Initializing Go AppEngine app with Cloud Datastore

in init() function for GAE's golang app, how can I set-up initial values for my application ?
How to read from Cloud Datastore in the init() function or immediately after applications start-up ? As I understand, server cannot write to the local filesystem and Cloud Datastore is the only option ?
I need some global variables and slices of data..

A:

Using static files
On AppEngine you don't have access to the file system of the host operating system, but you can access files of your web application (you have read-only permission, you can't change them and you can't create new files in the app's folder).
So the question is: can your application's code change the data that you want to read and use for initialization? Or is it fine if it is deployed "statically" with your app's code?
If you don't need to change it (or only when you redeploy your app), easiest is to store it as a "static" file as part of your webapp. You may refer to files of your app using relative paths, where the current or working directory is your app's root. E.g. if your app contains a data folder in its root (where app.yaml resides), and there is an init_values.txt file inside the data folder, you can refer to it with the path: data/init_values.txt.
One important note: not every file is readable by code, this depends on the app configuration. Quoting from Configuring with app.yaml / Static file handlers:

If you have data files that need to be read by the application code, the data files must be application files, and must not be matched by a static file pattern.

Using the Datastore
You can't use AppEngine services that require a Context outside of handlers (because the creation of a Context requires an *http.Request value). This by nature means you can't use them in package init() functions either.
Note that you can use them from cron jobs and tasks added to task queues, because tasks and cron jobs are executed by issuing HTTP GET requests.
You have to restructure your code so that your initialization (e.g. reading from the Datastore) gets called from a handler.
Example of achieving this with Once.Do():
var once = sync.Once{}

func MainHandler(w http.ResponseWriter, r *http.Request) {
    ctx := appengine.NewContext(r)
    once.Do(func() { mysetup(ctx) })
    // do your regular stuff here
}

func mysetup(ctx appengine.Context) {
    // This function is executed only once.
    // Read from Datastore and initialize your vars here.
}

"Utilizing" warmup requests
Yes, this may cause first requests to take considerably longer to serve. For this purpose (to avoid this) I recommend you to utilize Warmup requests. A warmup request is issued to a new instance before it goes "live", before it starts serving user requests. In your app.yaml config file you can enable warmup requests by adding -warmup to the inbound_services directive:
inbound_services:
  - warmup

This will cause the App Engine infrastructure to first issue a GET request to /_ah/warmup. You can register a handler to this URL and perform initialization tasks. As with any other request, you will have an http.Request in the warmup handler.
But please note that:

..you may encounter loading requests, even if warmup requests are enabled in your app.

Which means that in rare cases it may happen a new instance will not receive a warmup request, so its best to check initialization state in user handlers too.

Related questions:
How do I store the private key of my server in google app engine?
Fetching a URL From the init() func in Go on AppEngine
Environment variables specified on app.yaml but it's not fetching on main.go


Q:

Algorithm suggestion for Matrix in JavaScript

Not sure if the title is appropriate, please edit as you wish :-)
I have a series of html/css which create a layout described below.
Every cell is a div with a numbered class in the html (cell_1, cell_2, and so on).
When the page load cell numbered 1 is highlighted in the first grid.
A User can navigate among cell using the keyboard arrows key. When pressing ENTER user can jump to another grid at position 1.
Navigation is allowed only to certain cells accordingly to current cell location (cell highlighted) with some logic (described below).
The logic for each grid is described below..where
n= do nothing
bar= do nothing
y-2= means move to cell 2

My question is: instead to use a series of hard-coded if or case statements for each grid,
could you please suggested me smart way to have reusable logic (Matrix or similar possible in js)?
Please provide a short example or a link to some resource if is possible.
Any alternative ways to solve this approach are very welcome thanks.

  EXAMPLE LOGIC:
    grid type: 5x
    +--------+------+-------+
    +        +  2   +    4  +
    +   1    +------+-------+
    +        +  3   +    5  +
    +--------+------+-------+
    cell  up     down    left   right
      1   n      bar     n      y-2
      2   n      y-3     y-1    y-4
      3   y-2    bar     y-1    y-5
      4   n      y-5     y-2    n
      5   y-4    bar     y-3    n

    grid type: 7x
    +--------+------+-------+-------+
    +   1    +      3       +   6   +
    +------- +------+-------+-------+
    +   2    +  4   +   5   +   7   +
    +--------+------+-------+-------+
    cell  up     down    left   right
      1   n      y-2     n      y-3
      2   y-1    bar     n      y-4
      3   n      y-4     y-1    y-6
      4   y-3    bar     y-2    y-5
      5   y-3    bar     y-4    y-7
      6   n      y-7     y-3    n
      7   y-6    bar     y-5    n

    ///////////////////////
    grid type: 4x
    +--------+------+-------+-------+
    +        +      +       +       +
    +   1    +  2   +   3   +   4   +
    +        +      +       +       +
    +--------+------+-------+-------+
    cell  up     down    left   right
      1   n      bar     n      y-2
      2   n      bar     y-1    y-3
      3   n      bar     y-2    y-4
      4   n      bar     y-3    n

A:

Here is solution which doesn't use any additional data structure, pseudo-code:

top_x, top_y, width, height = get the boundries of clicked element
case direction:
left:
new_x = top_x - w from left boundries (where (border_width + paddigns) < w< the smallest box width)
right: ...
...
use document.elementFromPoint using new_x and new_y to find the correct div to light it up. If the div didn't changed, goto @2.

PS. The easiest way would be just use properly tags like old-fashioned <table>.
PS2. Of course, don't use "goto" instruction :)

A:

There will be a limit to how reusable you can design this.  If you want each grid to be different, you're going to have to separately define each grid with all of its connectivity.  Given that, though, it's not very hard to abstract.

Each grid contains a series of cells.
Each cell has some value for up, down, left, right.

So put this into an object containing other objects, for example:
var gridType5 = {
    cells = {
        1: { up: "n", down: "bar", left: "n", right: "2" }, // easier without the "y-", but we can add it if you want
        2: { up: "n", down: "3", left: "1", right: "4" },
        3: { up: "2", down: "bar", left: "1", right: "5" },
        4: { up: "n", down: "5", left: "2", right: "n" },
        5: { up: "4", down: "bar", left: "3", right: "n" }
    }
};

var grids = {
    5: gridType5,
    4: gridType4,
    7: gridType7
};

Then, given whatever cell and grid the user is in, you only have one movement logic:
function checkMove(currentGrid, currentCell, keypress) {
    var value = grids[currentGrid].cells[currentCell].keypress;
    if (value == "bar" || value == "n") {
        return value;
    }
    return grids[currentGrid].cells[value];
}

That's the basic idea.  You can modify the logic, e.g. if you truly don't need the "bar" or "n" values, you can change modify your abstraction:

Each grid contains a series of cells.
Each cell has a set of neighbors.

Which would make your cells look like:
        2: { neighbors: {down: 3, right: 4}},

and your checkMove look like:
function checkMove(currentGrid, currentCell, keypress) {
    var newCell = grids[currentGrid].cells[currentCell].neighbors[keypress];
    if (newCell) {
        return grids[currentGrid].cells[newCell];
    }
}


Q:

Select records virtually between a range of data

How can I select records between a range of date? For example, suppose that the start date is 9/1/2019 and the finish date is 9/5/2019. Then I want to select virtually records as follow:
My problem is that there is no table which saved the records.
Date    |Some Data
--------|---------
9/1/2019|Some Data
9/2/2019|Some Data
9/3/2019|Some Data
9/4/2019|Some Data
9/5/2019|Some Data

A:

You can try this below option with Recursive CTE-
DECLARE @start_date DATE= '2019-09-01', @end_date DATE= '2019-09-05';

WITH cte
AS
(
    SELECT @start_date AS date_, 'Some Data' AS Val

    UNION ALL

    SELECT CAST(DATEADD(day, 1, date_) AS DATE), 'Some Data' AS Val
    FROM cte
    WHERE date_ < @end_date
)

SELECT *
FROM cte OPTION(MAXRECURSION 0);

Output is-
date_       Val
2019-09-01  Some Data
2019-09-02  Some Data
2019-09-03  Some Data
2019-09-04  Some Data
2019-09-05  Some Data


Q:

Why does C# is keyword return true for double, but false for float even though casting to float works?

Motivation:  I have a method that returns a dynamic datatype.  The value is coming from a database and I know that the value will either be a float, double, or string.  I don't want to use the value if it is a string, so I wrote the following code:
if (value is float)
{
    myVariable = (float)value;
}

My expectation was that this code would execute whether the actual type of value was double or float because of the following snippet from the documentation of the 'is' keyword:

An is expression evaluates to true if the provided expression is non-null,and the provided object can be cast to the provided type without causing an exception to be thrown.

Found here: is (C# Reference)
However, when the type is double, (value is float) returns false and the assignment does not execute.  But, I changed my code to this:
if (value is double)
{
    myVariable = (float)value;
}

and it works fine when the type of value is double - even though according to the documentation I shouldn't be able to cast to a float because (value is float) returns false.
My Question: Why does (value is float) return false in the case where value is a double (which can be cast to a float without exception)?
EDIT - Short program demonstrating
class Program
{
    static void Main(string[] args)
    {
        dynamic d = 1.0;
        Console.WriteLine(d is double);
        Console.WriteLine(d is float);
        float f = (float)d;
        Console.WriteLine(f);
        Console.ReadKey();
    }
}

A:

Right, this is because the type is dynamic. That basically means the meaning of the float cast depends on the execution-time type of the value.
The is operator is checking whether float and double are the same type - and they're not, which is why it's returning false.
However, there is an explicit conversion from double to float, which is why the cast is working. I wouldn't use that MSDN C# reference to work out the finer details of how the language behaves - the language specification is normally a better bet.


Q:

Update to Android SDK Tools 23.0.5 and avd doesn't start

I am running on Windows 8.1 x64, developing Android apps using ADT Bundle. Previously (before updating the Android SDK Tools) the AVD was working very correctly and after the update, it says the following error while starting the AVD
emulator: ERROR: x86 emulation currently requires hardware acceleration!
Please ensure Intel HAXM is properly installed and usable.
CPU acceleration status: HAX kernel module is not installed!

I tried to delete the avd, avd-folder from the windows user-specific folder and re-created the similar avd but no progress.
How can I run the avd again? (after the SDK update)

A:

Create emulator in CPU/ABI in ARM, this error only exist for Intel processor.
If you want to create AVD CPU/ABI in Intel gor for this process,
Make sure you have instaled HAXM installer on your SDK Manager.
After you download it make sure you run the setup located in: {SDK_FOLDER}\extras\intel\Hardware_Accelerated_Execution_Manager\intelhaxm.exe
If you get the error "VT not supported" during the installation disable Hyper-V on windows features. You can execute this command dism.exe /Online /Disable-Feature:Microsoft-Hyper-V. You will also need "Virtualization Technology" to be enabled on your BIOS

A:

I've run into the same problem here and in my research I was able to find a documentation on the android  developer site that helped me out with this.

Start the Android SDK Manager, select Extras and then select Intel Hardware Accelerated Execution Manager.
After the download completes, run [sdk]/extras/intel/Hardware_Accelerated_Execution_Manager/IntelHAXM.exe
Follow the on-screen instructions to complete installation.
After installation completes, confirm that the virtualization driver is operating correctly by opening a command prompt window and running the following command:
sc query intelhaxm

You should see:
 SERVICE_NAME: intelhaxm
   ...
   STATE              : 4  RUNNING
   ...

Refer to this documentation here: Using the Emulator - Configuring VM Acceleration on Windows
Hope it helps.


Q:

Moving a UIbutton to a random position with timer

I am making a simple app in Objective C where every time a button is clicked, the button changes location on the screen. The first time the button is clicked, a timer begins.
The issue is every second the timer goes down, the button returns to its original position. How do I make it so that the timer does not effect the button moving?
Here is my code in my ViewController.m file:
Note: I cannot figure this out at all. I will probably need someone to really spell it out for me to tell me what to do. Thanks!
Note: My UIButton is "blackDot"
-(IBAction) mainClickButton{

int xmin = ([blackDot frame].size.width)/2;
int ymin = ([blackDot frame].size.height)/2;

int x = xmin + arc4random_uniform(self.view.frame.size.width - blackDot.frame.size.width);
int y = ymin + arc4random_uniform(self.view.frame.size.height - blackDot.frame.size.height);

[blackDot setCenter:CGPointMake(x, y)];

if (timerBeginInt < 1) {

    [timerLabel setText:@"Time : 0:10"];
    [self.view addSubview:timerLabel];
    currMinute=0;
    currSeconds=10;
    [self start];

}

timerBeginInt = timerBeginInt + 1;

}

-(void)start
{
    timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];

}
-(void)timerFired
{
    if((currMinute>0 || currSeconds>=0) && currMinute>=0)
    {
        if(currSeconds==0)
        {
            currMinute-=1;
            currSeconds=59;
        }
        else if(currSeconds>0)
        {
            currSeconds-=1;
        }
        if(currMinute>-1)
            [timerLabel setText:[NSString stringWithFormat:@"%@%d%@%02d",@"Time : ",currMinute,@":",currSeconds]];
    }
    else
    {
        [timer invalidate];
        timerBeginInt = 0;
    }
}

Any help is appreciated! Thanks!

A:

LodgeApps.
i copy your code, run it with my own Xcode,and i find your problem which confuses you.
short solution is here:
open your storyboard or xib file,keep this off.

if you want to keep Autolayout on,
[self.view removeConstraints:blackDot.constraints];

NSLayoutConstraint* leftConstraint = [NSLayoutConstraint constraintWithItem:blackDot attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0f constant:x];

NSLayoutConstraint* topConstraint = [NSLayoutConstraint constraintWithItem:blackDot attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0f constant:y];

leftConstraint.active = YES;
topConstraint.active = YES;

replace the setCenter
for deeper reason:
with autolayout property on,you can not change the frame of IBOutlet,every attempt to modify frame or center is illegal.You can only change the constraints to move the IBOutlet.
what confuses me:
According to the code,click the button,the button will move at once.but it won't.Because method like setCenter or setFrame won't work in the Autolayout.
Autolayout needs constraints to put the UI(IBOutlets) in the right place.If you keep Autolayout on,and then you do not make constraints on IBs,anything could happens which i can't explain.


Q:

flash media server: can i record video/audio from a running swf?

i have flash media server installed and i wrote some flash games using action script 3.
is there a way for me to allow the users to record their plays so they'll be able to watch it later from my fms server?

A:

From within the game you could approximate their actions but I don't believe that you can actually make a video of all the frames. I know there are apps out there that do that but they don't run within the swf.
But if you really wanted to you could just put a blanket click listener on the stage, record the position of the mouse and the time that it was clicked and any other state that would be necessary. As long as there's no randomness in the game this would work for a replay. If there is randomness you'll have to store the random number generator seed as well so that you can make sure that the randomness is the same each time.
I hope that helps direct you down some useful paths.


Q:

rxjs: Chaining Async Requests

I'm new to rxjs, and I need to call 3 async requests, which started out as promises, and put the reurned objects into an array in the order in which they were called. Here's what a I have (partly based on this question):
let observeFront = Observable.fromPromise(this.requestAsync(frontSlice, "front"));
let observeMiddle = Observable.fromPromise(this.requestAsync(midSlice, "middle"));
let observeEnd = Observable.fromPromise(this.requestAsync(endSlice, "end"));

let observeCombined = Observable.concat(observeFront, observeMiddle, observeEnd);

observeCombined.subscribe(data => {
  // this logs only one object - need all 3 in proper order
  console.log(data);
  this.resultsEmitter.emit(data)
});

observeFront.subscribe(response => {
  // logs the correct object
  console.log("front result:", response);
});

observeMiddle.subscribe(response => {
  // correct
  console.log("middle result:", response);
});

observeEnd.subscribe(response => {
  // correct
  console.log("end result:", response);
});

How can I emit the result only when I have [frontOb, middleObj, endObj] ?

A:

As @Eric suggested you can use forkJoin() instead of concat():
let observeFront = Observable.fromPromise(this.requestAsync(frontSlice, "front"));
let observeMiddle = Observable.fromPromise(this.requestAsync(midSlice, "middle"));
let observeEnd = Observable.fromPromise(this.requestAsync(endSlice, "end"));

let observeJoined = Observable.forkJoin(observeFront, observeMiddle, observeEnd);

observeJoined.subscribe(data => {
  console.log(data); // => [frontOb, middleObj, endObj]
  this.resultsEmitter.emit(data)
});