Q: Mixing objects and rows, carrying muliples objects. How going from row datasets to datasets of objects (a Dataset where + mean: "join")? The following question is rather long. It depicts this:

*

*I have a row dataset made of primitive types a1, a2...a10, b1, b2...b8, c1..c4, d1.

*They are hiding objects A, B, C accompanied sometimes with others primitives attributes not in a class: d1, for example.

*I could return instead of a Dataset<Row> a Dataset<E> where E would be a class having for members the A, B, C objects and the attribute d1.

*But I want to avoid this, if I can, yet, and see how much I can approach a solution where I would return a dataset of joined objects [and attributes] : Dataset<A+B+C+d1>
(where the + sign means that objects are linked together by a join).
If it's possible, is it really manageable?

My code uses mostly Dataset<Row>.
For example, I have a method that builds a (French) city description:
/**
* Obtenir un Dataset des communes.
* @param session Session Spark.
* @param anneeCOG Année du Code Officiel Géographique de référence.
* @param verifications Vérifications demandées.
* @return Dataset des communes.
* @throws TechniqueException si un incident survient.
*/
public Dataset<Row> rowCommunes(SparkSession session, int anneeCOG, Verification... verifications) throws TechniqueException {
  String nomStore = "communes_par_codeCommune";

  Dataset<Row> communes = loadFromStore(session, "{0}_{1,number,#0}", nomStore, anneeCOG, verifications);

  if (communes != null) {
     return communes;
  }

  LOGGER.info("Constitution du dataset des communes depuis pour le Code Officiel Géographique (COG) de l'année {}...", anneeCOG);

  Dataset<Row> c = loadAndRenameCommmunesCSV(session, anneeCOG, false, verifications);
  Dataset<Row> s = this.datasetSirenCommunaux.rowSirenCommunes(session, anneeCOG, TriSirenCommunaux.CODE_COMMUNE);

  Column condition1 = c.col("codeCommune").equalTo(s.col("codeCommune"));
  Column condition2 = c.col("codeCommuneParente").equalTo(s.col("codeCommune"));

  verifications("jonction communes et siren par codeCommune", c, null, s, condition1, verifications, SHOW_REJETS, COMPTAGES_ET_STATISTIQUES);
  Dataset<Row> join1 = c.join(s, condition1)
     .drop(s.col("codeCommune"))
     .drop(s.col("nomCommune"))
     .drop(s.col("codeRegion"))
     .drop(s.col("codeDepartement"));

  verifications("jonction communes et siren par codeCommune, join1", c, null, null, null, verifications);

  verifications("jonction communes et siren par codeCommuneParente", c, null, s, condition2, verifications, SHOW_REJETS, COMPTAGES_ET_STATISTIQUES);
  Dataset<Row> join2 = c.join(s, condition2)
     .drop(s.col("codeCommune"))
     .drop(s.col("nomCommune"))
     .drop(s.col("codeRegion"))
     .drop(s.col("codeDepartement"));

  verifications("jonction communes et siren par codeCommuneParente, join2", c, null, null, null, verifications);

  communes = join1.union(join2);

  // La strate communale doit concorder avec celle des comptes individuels des communes.
  communes = communes.withColumn("strateCommune",
     when(s.col("populationTotale").between(0, 249), lit(1))       // communes de moins de 250 hab
     .when(s.col("populationTotale").between(250, 499), lit(2))     // communes de 250 à 500 hab
     .when(s.col("populationTotale").between(500, 1999), lit(3))    // communes de 500 à 2 000 hab
     .when(s.col("populationTotale").between(2000, 3499), lit(4))   // communes de 2 000 à 3 500 hab
     .when(s.col("populationTotale").between(3500, 4999), lit(5))   // communes de 3 500 à 5 000 hab
     .when(s.col("populationTotale").between(5000, 9999), lit(6))   // communes de 5 000 à 10 000 hab
     .when(s.col("populationTotale").between(10000, 19999), lit(7)) // communes de 10 000 à 20 000 hab
     .when(s.col("populationTotale").between(20000, 49999), lit(8)) // communes de 20 000 à 50 000 hab
     .when(s.col("populationTotale").between(50000, 99999), lit(9)) // communes de 50 000 à 100 000 hab
     .otherwise(lit(10)));                                          // communes de plus de 100 000 hab

  // Obtenir les contours des communes.
  // "(requête SQL) contours" est la forme de substitution pour Spark. cf https://stackoverflow.com/questions/38376307/create-spark-dataframe-from-sql-query
  String format = "(select insee as codecommuneosm, nom as nomcommuneosm, surf_ha as surface2, st_x(st_centroid(geom)) as longitude, st_y(st_centroid(geom)) as latitude from communes_{0,number,#0}) contours";
  String sql = MessageFormat.format(format, anneeCOG);

  Dataset<Row> contours = sql(session, sql).load();
  contours = contours.withColumn("surface", col("surface2").cast(DoubleType)).drop(col("surface2"))
     .orderBy("codecommuneosm");

  Column conditionJoinContours = col("codeCommune").equalTo(col("codecommuneosm"));

  verifications("jonction communes et contours communaux OSM (centroïde, surface)", communes, null, contours, conditionJoinContours, verifications, SHOW_REJETS, COMPTAGES_ET_STATISTIQUES);
  communes = communes.join(contours, conditionJoinContours, "left_outer")
     .drop(col("codecommuneosm")).drop(col("nomcommuneosm"));
  verifications("jonction communes et contours communaux OSM (centroïde, surface)", communes, null, null, null, verifications);

  // Associer à chaque commune son code intercommunalité, si elle en a un (les communes-communautés peuvent ne pas en avoir).
  Dataset<Row> perimetres = this.datasetPerimetres.rowPerimetres(session, anneeCOG, EPCIPerimetreDataset.TriPerimetresEPCI.CODE_COMMUNE_MEMBRE).selectExpr("sirenCommuneMembre", "sirenGroupement as codeEPCI", "nomGroupement as nomEPCI");
  Column conditionJoinPerimetres = communes.col("sirenCommune").equalTo(perimetres.col("sirenCommuneMembre"));

  verifications("jonction communes et périmètres", communes, null, perimetres, conditionJoinPerimetres, verifications, SHOW_REJETS, COMPTAGES_ET_STATISTIQUES);
  communes = communes.join(perimetres, conditionJoinPerimetres, "left");

  // Y associer les départements.
  communes = this.datasetDepartements.withDepartement(session, "codeDepartementRetabli", communes, "codeDepartement", null, true, anneeCOG)
     .drop("codeRegionDepartement")
     .drop("codeDepartementRetabli");

  communes = communes.repartition(col("codeDepartement"))
     .sortWithinPartitions(col("codeCommune"))
     .persist(); // Important : améliore les performances.

  saveToStore(communes, new String[] {"codeDepartement"}, "{0}_{1,number,#0}", nomStore, anneeCOG);
  LOGGER.info("Le dataset des communes du Code Officiel Géographique de l'année {} est prêt et stocké.", anneeCOG);

  return communes;
}

Sometimes, it's useful if I convert these rows to a Commune object, because business objects, at least on server side, can have methods that bring them some kind of intelligence (limited to looking at themselves or to the objects of their package).
For example, the Commune object has this method to help detecting it has the same name than another one when an article can be found in its name.
/**
* Déterminer si notre commune a le même nom que celle en paramètre.
* @param nomCandidat Nom de commune : il peut contenir une charnière.
* @return true si c'est le cas.
*/
public boolean hasMemeNom(String nomCandidat) {
  // Si le nom soumis vaut null, répondre non.
  if (nomCandidat == null) {
     return false;
  }

  // Faire une comparaison directe de nom de commune tout d'abord, car l'emploi du collator est très coûteux.
  if (nomCandidat.equalsIgnoreCase(this.nomCommune)) {
     return true;
  }

  // Puis, rechercher avec les différentes charnières.
  if (nomCandidat.equalsIgnoreCase(nomAvecType(false, PrefixageNomCommune.AUCUN))) {
     return true;
  }

  if (nomCandidat.equalsIgnoreCase(nomAvecType(false, PrefixageNomCommune.A))) {
     return true;
  }

  if (nomCandidat.equalsIgnoreCase(nomAvecType(false, PrefixageNomCommune.POUR))) {
     return true;
  }

  // En cas d'échec, reprendre ces tests, mais avec le collator, plus lent, mais qui passera outre les caractères accentués.
  if (collator.equals(nomCandidat, this.nomCommune)) {
     return true;
  }

  if (collator.equals(nomCandidat, nomAvecType(false, PrefixageNomCommune.AUCUN))) {
     return true;
  }

  if (collator.equals(nomCandidat, nomAvecType(false, PrefixageNomCommune.A))) {
     return true;
  }

  if (collator.equals(nomCandidat, nomAvecType(false, PrefixageNomCommune.POUR))) {
     return true;
  }

  return false;
}

To do that conversion from a Dataset<Row> to a Dataset<Commune>, I wrote this function, which works, but troubles me because it looks clumsy to me:
/**
* Obtenir un Dataset des communes (comme objets communes, incluant les données siren communaux).
* @param session Session Spark.
* @param anneeCOG Année du Code Officiel Géographique de référence.
* @return Dataset des communes.
* @throws TechniqueException si un incident survient.
*/
public Dataset<Commune> obtenirCommunes(SparkSession session, int anneeCOG) throws TechniqueException {
  Dataset<Row> communes = rowCommunes(session, anneeCOG);

  return communes
     .select(communes.col("typeCommune"), communes.col("codeCommune"), communes.col("codeRegion"), communes.col("codeDepartement"),
         communes.col("arrondissement"), communes.col("typeNomEtCharniere"), communes.col("nomMajuscules"), communes.col("nomCommune"),
         communes.col("codeCanton"), communes.col("codeCommuneParente"), communes.col("sirenCommune"), communes.col("populationTotale").alias("population"),
         communes.col("strateCommune"), communes.col("codeEPCI"), communes.col("surface"), communes.col("longitude"), communes.col("latitude"),
         communes.col("nomDepartement"), communes.col("nomEPCI"))
     .as(Encoders.bean(Commune.class))
     .cache();
}

However, my main problem is:
The Commune object (or rows) is almost never used (or returned) alone in most datasets, after that.
Often a Commune will come with some employment data associated, or with financial information linked. Or sometimes, a calculation method can associate only one or two raw (primitive) data values to a city, if they make sense.
So, until today, what happened?

*

*I was starting with a Dataset<Row> of let's say 20 columns.

*if I was doing some joins, calculations, enrichments, etc.: that dataset reached 40 or 50 columns sometimes,

*

*Let's say that a record was: a1, a2...a10, b1, b2...b8, c1..c4, d1 of rows columns having primitive types.

*then I was extracting from that record, through the mean of Encoders.bean(...) method, the various business objects it was hiding, depending on my needs.

*

*From a record, I could extract A from a1, a2...a10 or C from c1...c4.

It worked (and it's working) but I'm not really proud of this manner of doing things.
I would enjoy more starting with a plain Dataset<Commune> dataset, hiding completely the row phase to the users of my API, then being able to return to them, depending of their needs:

*

*a dataset containing Commune and Employment business object together, or Commune and Accounting.

*a dataset containing Commune, but with also few row values of columns "d1", "h1" and "k1" (if some calculation was needed to provide a specific information for that city, for some exceptional purpose/case that don't lead to changing the whole business object description, but only at this time to return an extra column value aside that city description).
It means that I will encounter cases where I would like to return a dataset showing per "record":
A, B (concrete objects coming together)
or
A, C
or even sometimes A,B,C.
Or what I'm fearing the most:
A, C, d1 (two concrete objects, plus... a primitive value).
Can you give me some ideas about how treating such problems before I start great moves?

Warning: this problem isn't a simple one. It could even not have a clear solution.

*

*Starting from row records made of primitive types a1, a2...a10, b1, b2...b8, c1..c4, d1, I am able to extract A, B, C objects from them, if I agree to do up to n additional transformations for n different objects types I can find in my attributes.

*But I wonder about approaching the most I can the situation where, given the + sign would mean: join, I had a dataset :
Dataset<A+B+C>
and even: Dataset<A+B+C+d1>, where d1 would still be a primitive type not in an object.

*If this could be achieved, it could cause troubles.
What is a Dataset<A+B+C+d1>.foreach?
A A, B or C object?
How would you manage it after that?
I'm living in a magma of attributes yet, and I wonder if I can improve my datasets to new ones using objects. Objects that are tied together to describe a single record.

This question could have the solution of creating an E object having for members A, B or C objects and the d1 primitive attribute, and returning a Dataset<E>.
But this I want to avoid the most I can, at this time. And try to find what I can do else, first.


Q: How to find and remove optgroup and option in select? I've this select structure:
<select id="select-service" class="required span4" multiple="">
        <optgroup label="Capelli">
              <option selected="false" value="14">Colore capelli</option
        </optgroup>
        <optgroup label="Nessuna categoria">
              <option selected="false" value="13">Taglio capelli</option>
              <option selected="false" value="15">Mesh</option>
        </optgroup>
</select>

Now my goal is remove all option in select, so I've made this code:
$('#select-service')
  .find('option')
  .remove()
  .end();

but the problem's that this code remove only the option not the optgroup, how I can remove in one step option and optgroup?

A: You could simply pass two, comma-separated, selectors to the find() method:
$('#select-service').find('optgroup, option').remove();

You could also just remove all children elements for the same result:
$('#select-service').children().remove();
// or:
$('#select-service > *').remove();

The most concise approach would be to just remove the element using the .empty() method:
$('#select-service').empty();

A: The simplest way
$('#select-service optgroup').remove()

Since optgroup is the parent of option it will remove it as well.

A: Like this:
$('#select-service')
.find('optgroup')
.remove();

This will not only remove your optgroup, but all contents within it, meaning your option will also be removed.


Q: Include assets in Twig Extension with Symfony2 I want to include asset with some script file in Twig extension. E.g. I want to declare twig function {{ init_project() }}, but when I writing in my twig function '<script type="text/javascript" src="{{ asset('bundles/mybundle/js/script.js') }}"></script>', it dont work, it return 404 error in debug panel of browser. So how I can do this?

A: Look at the 'asset' twig function :
You can find it in \Symfony\Bundle\TwigBundle\Extensions\AssetsExtension
public function getAssetUrl($path, $packageName = null, $absolute = false, $version = null)
    {
        $url = $this->container->get('templating.helper.assets')->getUrl($path, $packageName, $version);

        if (!$absolute) {
            return $url;
        }

        return $this->ensureUrlIsAbsolute($url);
    }

Instead of calling '{{asset}}' in your extension, just call the public function getAssetUrl()


Q: Selecting the second child of an ancestor with XPath I need to fetch some text from a HTML page. I'm trying to avoid relying on tag names or classes, because they will change.
Starting from an element that contains the text "Hello", I'm looking for the text stored in the grandparent's second element.
<...>
  <...>
    <...>
      Hello
    </...>
  </..>
  <...>       <!-- UNCLE -->
    <...>
      World   <!-- I need this! -->
    </...>
  <...>
</...>

I tried fetching the element UNCLE using XPath, with: //*[text()=="Hello")]/../..[2], but it doesn't work. It seems that [] cannot be applied to ..?
How can I fetch the second child of a node's grandparent?
Are there better ways to retrieve the text I'm looking for, instead of a similar XPath query and document.evaluate?

A: Try this:
//*[*[1][*[normalize-space()='Hello']]]/*[2]/*

It will select the element that contains "World".
It's testing the value of the descendant in the first child and then selecting the descendant of the second child.


Q: Correct way for thread safe indexing operator in c++ I want to have thread safe indexing operator and I came with the following code which seems to work.
Can you see any problems with it except for bounds checking?
Is there a better way to do the same thing (with overloading indexing operator, not with get/set functions)?
class A
{
public:

A()
{
    for (auto i = 0; i < 100; ++i)
    {
        v[i] = i + 1;
    }
};

    class Proxy
    {
        int* val;
        A* parent;
    public:
        Proxy(int& a, A* p) : parent(p)
        {
            parent->z.lock();
            val = &a;
        };

        ~Proxy()
        {
            parent->z.unlock();
        }

        int operator=(int a)
        {
            *val = a;
            return a;
        };

        operator int() const
        {
            return *val;
        };
    };

int operator[](int i) const
{
    z.lock();
    int r = v[i];
    z.unlock();
    return r;
}

Proxy operator[](int i)
{
    return Proxy(v[i], this);
}

int v[100];
Z z; // some locking mechanism, not important

};

A: Since the locking mechanism isn't specified I'd assume it uses a normal mutex in which case the obvious problem is this:
A a;
a[0] = a[1];

Put differently, it is very easy to dead-lock the program. This problem is avoided with recursive mutexes.
The other obvious problem is that the code depends on copy-elision which is not guaranteed to always happen. If the copy is not elided upon return the temporary will release the lock and the copy will release it again which normally is undefined behavior. In addition, access to the member is unguarded and will potentially introduce data races. To avoid this problem you should define a move constructor and make sure that the moved from state doesn't try to release the mutex, e.g.:
A::Proxy::Proxy(Proxy&& other)
    : val(other.val)
    , parent(other.parent) {
    other.parent = 0;
}
A::Proxy::~Proxy() {
    if (parent){
        parent->unlock();
    }
}

The not so obvious issue is that it is unlikely to result in an efficient implementation.


Q: Differentiate between Table Views I have three table views inside a view controller (going to show/hide table views to display a list of options in different contexts)
Just wondering what the best way is to distinguish between different table views that are using the same delegate.
Thanks

A: Use three separate instance variables in your view controller to store the table views. Then in the delegate methods you can do something like this:
if (tableView == myFirstTableView) {
    // Do whatever you need for table view 1.
} else if (tableView == mySecondTableView) {
    // Do whatever you need for table view 2.
}


Q: Use VisualBasic DLLs in Java I have to access VBA-code of Office applications from my Java application, I found THIS that says I can access VBA-code through VisualBasic DLLs using JNI. I don't want to use a COM-bridge if not necessary, I'd rather go with a DLL-solution.
I created a VisualBasic Class Library in Visual Studio 2013 (a simple example to test if it works):
Public Class Test1
    Public Function box()
        MsgBox("boxtest!")
    End Function
End Class

I built is as a release and put this in my Java project:
public class Test1 {
    static{
        System.loadLibrary("Test1");
    }
    public native void box();
}

The function is being called by new Test1().box();.
I receive the following exception: Exception in thread "main" java.lang.UnsatisfiedLinkError: test.Test1.box()V
I also used JNA to access the DLL but after hours of trying I couldn't get it to work (I also read that it can't be used with VisualBasic DLLs).
I set the Native Library Folder of my src Folder to to folder containing the DLL.
question: Can I use VisualBasic DLLs in Java, if yes, with JNA or JNI (or both) and if so what did I do wrong, how can I access the function properly? (I guess the rest with returning and parameters is easy then...)
Thank you very much in advance and merry christmas to you all! :)

A: No idea why it cannot find your library.  From what I remember of JNI, it does not appear that you've done the JNI setup for calling a native routine, but the error message just says it cannot find it.  You might try figuring out if the library load statement worked.
A DLL is a library following certain rules and conventions; I am not aware of any great difference between a "Visual Basic DLL" and any other kind.  At some level they need to be the same, because Windows programs don't distinguish among DLLs written with different languages, afaik, and I've done VB enough to know that I haven't seen documentation that says "this can be used from VB but not from other languages" etc.
Getting JNI/JNA stuff to work is tricky and tedious.  The normal stuff that a language runtime tells you, especially a Java runtime, are not there for you in this case.  You must painstakingly go through every line of whatever documentation you have, every parameter you are passing, every use of value versus reference, etc.
I once got things to work with the GitHub library here.
Good luck.

A: I have not found an answer how to call VB DLLs directly from Java but after some days of research I found out that you are able to call VB DLLs with the help of a C++ wrapper.
It may be possible to call VB DLL methods with JNI but there is no documentation on how to do it.
You find a lot about how to create C++ libraries that are able to communicate with JNI in the JNI specifications from Oracle.
In this special case (control Office Applications with Java) I suggest to write the code to access the Office Application in C++ and create a DLL.
The basic approach on creating a C++ DLL that may interact with JNI is:

*

*Think of names for the methods you want to create in C++ and a .dll-name [NAME].dll

*Create a Java class for the DLL, loading the library:
static{
  System.loadLibrary([NAME].dll);
}

The Native Library path has to be set (in Eclipse, right-click on the folder containing your class and click Build-Path).

*Include the method names public native void [methodname]();.

*Compile the .java file using javac.exe (or let for example Eclipse do the work).

*Create a C++ header-file using javah.exe with -jni parameter.

*Create a new project in Visual Studio (Visual C++ MFC DLL).

*Copy the created header-file (your Java Project), the jni.h (JDK) and the jni_md.h (JDK)

*Include all three header-files in your Visual C++-project header-file [Project-Name].h

*Include the created header-file and the jni.h-file in [Project-name].cpp.

*Write desired code in your [Project-name].cpp.

*Build the DLL, put it inside your defined path for Native Libraries (see italic in 2.).

*Run and be happy!
Sorry for any mistakes!
An example with Visual Basic-DLL and JNI can be found 1HERE and somewhere else, google "classle" and "JNI" (can't post 2 links).


Q: Customize List's cells in DashCode I have my site created with Dashcode and I am using the List object but I don't like the default blue background when a cell is selected.
How can I customize this? For example change it to grey or white, etc.
(As far as i know, everything is customizable in Dashcode, is just sometimes you have to do it using code and not Dashcode UI.)
Thanks in advance.

A: Answer to my self:
looking at main.css I found something like:
.listRowTemplate_template.selected {
    background-color: rgb(56, 0, 217);
}

Which is the color I want to change ;)

A: Which would have been my answer, shall i vote you up? ;-)
It is easy to forget that when in Dashcode it is "just" JavaScript, CSS and HTML and so many problems will often succumb to those type of solutions such as you have done.


Q: Enable JPA 2nd level cache in Spring Data JPA repository I try to enable JPA 2nd level cache for Spring Data JPA. I enabled cache in persistence.xml:
<persistence-unit name="ds-default">
    <jta-data-source>SAMPLE_DATASOURCE</jta-data-source>
    <shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
    <properties>
        <property name="hibernate.cache.use_second_level_cache" value="true" />
        <property name="hibernate.cache.use_query_cache" value="true" />
        <property name="hibernate.show_sql" value="true" />
        <property name="hibernate.cache.region.factory_class" value="org.jboss.as.jpa.hibernate5.infinispan.InfinispanRegionFactory" />
    </properties>
</persistence-unit>

In my repository I provided query hints for the cache as well:
public interface SampleRepository extends JpaRepository<SampleEntity, String> {

    @Override
    @QueryHints(value = {
            @QueryHint(name = "org.hibernate.cacheable", value = "true")
    })
    List<SampleEntity> findAll();
}

I expect that the result of findAll query should be cached and that I should see only one select query in the logs. However, I see it more than once which leads me to the conclusion that cache is not configured correctly. What am I missing?
I do not want to use the Spring Cache mechanism (I do not use Spring Boot etc.).

A: I can give you some steps to check and follow and a sample project in github:

*

*Check in persistence.xml
<persistence-unit name="testPersistenceUnit" transaction-type="JTA">
...
        <shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
       <properties>
...
        <property name="hibernate.cache.use_second_level_cache" value="true"/>
        <property name="hibernate.cache.use_query_cache" value="true"/>
        <property name="hibernate.cache.region_prefix" value="hibernate.test"/><!-- Optional -->
         <!-- Use Infinispan second level cache provider -->
        <property name="hibernate.cache.region.factory_class" value="org.infinispan.hibernate.cache.v53.InfinispanRegionFactory"/>

            <!-- Optional: Initialize a caches (for standalone mode / test purpouse) -->
            <property name="hibernate.cache.infinispan.cfg"
                      value="META-INF/infinispan-configs-local.xml"/>
...
       </properties>
</persistence>

PS: "org.infinispan.hibernate.cache.v53.InfinispanRegionFactory" package depends on your maven dependencies and Hibernate version.

*If you want to use JCache interceptors. Add to beans.xml:
<interceptors>
    <class>org.infinispan.jcache.annotation.InjectedCacheResultInterceptor</class>
    <class>org.infinispan.jcache.annotation.InjectedCachePutInterceptor</class>
    <class>org.infinispan.jcache.annotation.InjectedCacheRemoveEntryInterceptor</class>
    <class>org.infinispan.jcache.annotation.InjectedCacheRemoveAllInterceptor</class>
</interceptors>

PS. Take in mind, that Infinispan have a variant without "Injected" in the name of the Interceptors for environments where the cache manager is not injected in a managed environment.

*Check that your cache is configured (in your application server) or your cdi producer. Eg.
@ApplicationScoped
public class CacheConfigProducer {
@Produces
public Configuration defaultCacheConfiguration() {
return new ConfigurationBuilder().simpleCache(false).customInterceptors().addInterceptor()
    .interceptor(new TestInfinispanCacheInterceptor()).position(Position.FIRST).expiration().lifespan(60000l)
    .build();
}
}

*Add to your repository your hints like you are adding:
@Eager public interface CacheableReadWriteRepository extends ReadWriteRepository<CacheableEntity, Integer>{

    @QueryHints(value = { @QueryHint(name = org.hibernate.jpa.QueryHints.HINT_CACHEABLE, value = "true")})
    List<CacheableEntity> findByValue(Integer value);
}

*Take care to add @Cacheable to your entity

You have this project with Spring Data JPA and CDI integration (spring-data-jpa with cdi). It has tests with JCache, Hibernate 2nd level cache and query cache.
I hope it helps.


Q: Generic types in array with Google HTTP Client Library I have base http response which looks like:
{
"data" : [],
"total" : 0,
"hasMore" : false
}

In data can be any object - Users, FeedItems and etc.
So i want create base class something like
public class BaseDataReponse<T> {

@Key
public List<T> data;

@Key
public Integer total;

@Key
public Boolean hasMore;

}

I can do so in Retrofit for Android library.
But i can't understand how to do this in Google HTTP Client Library.


Q: Im not sure what functions to use when sorting a dictionary Im not sure what functions to use to sort a dictionary which gets added to as the programme runs, the format of the dictionary is (name:score,name:score ..... )
print(" AZ : print out the scores of the selected class alphabteically \n HL : print out the scores of the selected class highest to lowest \n AV : print out the scores of the selected class with there average scores highest to lowest")
    choice = input("How would you like the data to be presented? (AZ/HL/AV)")

while True:
if choice.lower() == 'az':
  for entry in sorted(diction1.items(), key=lambda t:t[0]):
  print(diction1)
  break
elif choice.lower()=='hl':
  for entry in sorted(diction1.items(), key=lambda t:t[1]):
  print(diction1)
  break
elif choice.lower() == 'av':
  print(diction1)
  break
else:
  print("invalid entry")
  break

A: A dictionary is unordered.
You can sort the data for output.
>>> data = {'b': 2, 'a': 3, 'c': 1}
>>> for key, value in sorted(data.items(), key=lambda x: x[0]):
...     print('{}: {}'.format(key, value))
...
a: 3
b: 2
c: 1
>>> for key, value in sorted(data.items(), key=lambda x: x[1]):
...     print('{}: {}'.format(key, value))
...
c: 1
b: 2
a: 3

Using an OrderedDict is not an option here, because you don't want to maintain order, but want to sort with different criteria.


Q: C Programming: fgets() function is not reading the values that I think it should I am trying to open and read a .txt file that simply contains a 2 digit number from 00 to 99.
Currently the file contains the following numbers: 05
When I read the first two values with fgets(), I instead get 48 and 53, and I've noticed whatever number I put in there, the number that fgets() grabs is 48 higher.  While I could just subtract 48 from the number like I am doing now, I would like to figure out what I am doing wrong so that I don't have to do that.  Here is the relevant section of my code:
char buff[3];
FILE *fp;
fp = fopen("savedata/save.txt","r");
fgets(buff, 3, fp);
SampleLevelIndex = (buff[0]-48)*10 + buff[1]-48;
fclose(fp);

A: Your file contain the characters '0' and '5'. Note that the ASCII code for '0' is 48.
You are reading the values of the bytes, not the number represented. If you had an 'A' in the file, you would have the byte 65.
Your approach works for manually converting numeric characters into a number (although you might one some extra checking, it will break if it doesn't contain two numbers). Or you could use a function like atoi() which converts a numeric string into the number.


Q: Connect to gitlab production postgresql database with psycopg2? I am trying to connect to GitLab production (installed with omnibus package) postgresql database with psycopg2.
My configuration is like below:
onn = psycopg2.connect(database="gitlabhq_production", user="gitlab-psql", host="/var/opt/gitlab/postgresql", port="5432")

It gives the following error:
FATAL:  Peer authentication failed for user "gitlab-psql"

I can connect to the postgresql server on command line with:
sudo -u gitlab-psql -i bash /opt/gitlab/embedded/bin/psql --port 5432 -h /var/opt/gitlab/postgresql -d gitlabhq_production

Does anyone know what will be the correct parameters to pass into?

A: Peer authentication works by checking the user the process is running as. In your command line example you switch to gitlab-psql using sudo.
There are two ways to fix this:

*

*Assign a password to the gitlab-psql postgres user (not the system user!) and use that to connect via python. Setting the password is just another query you need to run as a superuser like so:
sudo -u postgres psql -c "ALTER USER gitlab-psql WITH PASSWORD 'ReplaceThisWithYourLongAndSecurePassword';"

*Run your python script as gitlab-psql like so:
sudo -u gitlab-psql python /path/to/your/script.py


Q: GCC regular expressions How do I use regular expressions in GNU G++ / GCC for matching, searching and replacing substrings? E.g. could you provide any tutorial on regex_t and others?
Googling for above an hour gave me no understandable tutorial or manual.

A: I strongly suggest using the Boost C++ regex library. If you are developing serious C++, Boost is definitely something you must take into account.
The library supports both Perl and POSIX regular expression syntax. I personally prefer Perl regular expressions since I believe they are more intuitive and easier to get right.
http://www.boost.org/doc/libs/1_46_0/libs/regex/doc/html/boost_regex/syntax.html
But if you don't have any knowledge of this fine library, I suggest you start here:
http://www.boost.org/doc/libs/1_46_0/libs/regex/doc/html/index.html

A: I found the answer here:
#include <regex.h>
#include <stdio.h>

int main()
{
  int r;
  regex_t reg;

  if (r = regcomp(&reg, "\\b[A-Z]\\w*\\b", REG_NOSUB | REG_EXTENDED))
  {
    char errbuf[1024];

    regerror(r, &reg, errbuf, sizeof(errbuf));
    printf("error: %s\n", errbuf);

    return 1;
  }

  char* argv[] = { "Moo", "foo", "OlOlo", "ZaooZA~!" };

  for (int i = 0; i < sizeof(argv) / sizeof(char*); i++)
  {
    if (regexec(&reg, argv[i], 0, NULL, 0) == REG_NOMATCH)
      continue;

    printf("matched: %s\n", argv[i]);
  }

  return 0;
}

The code above will provide us with
matched: Moo
matched: OlOlo
matched: ZaooZA~!

A: Manuals should be easy enough to find: POSIX regular expression functions. If you don't understand that, I would really recommend trying to brush up on your C and C++ skills.
Note that actually replacing a substring once you have a match is a completely different problem, one that the regex functions won't help you with.


Q: Hibernate - automatic and generic way to check if a defined unique key constraint exists? Imagine a City to Postalcode relation mapping. (For simplicity using no foreign-keys)
<class name="CityToPostalcode" table="city_to_postalcode" catalog="database">
    <id name="id" type="java.lang.Integer">
        <column name="id" />
        <generator class="identity" />
    </id>
    <property name="city" type="String">
        <column name="city" not-null="true"/>
    </property>
    <property name="postalcode" type="Integer">
        <column name="postalcode" not-null="true"/>
    </property>
    <properties name="businessKey" unique="true">
        <property name="city"/>
        <property name="postalcode"/>
    </properties>
</class>

Is there a function in the framework to check if the unique key "businessKey" for a given combination is unique (also for single-column unique constraints)?
Maybe in combination of mapping "businessKey" to a class? (Similar to usage of composite-id)
It is just so much redundance to write the code for each table to check its business-key, if it definetly could be done automatic.

A: there is natural Id which automaticly creates a unique constraint on schema creation and can be used to query for it more efficiently. in xml
<natural-id>
    <property name="name"/>
    <property name="org"/>
</natural-id>

naturalids use the second level cache more efficient and from H4.1 on loading by naturalid uses the first level cache and can save roundtrips. Other than that natural ids are just like normal properties. you could however write a generic natural id checker

*

*create a new object with the properties set

*access through the sessionfactory the classmetadata of the object

*iterate the natural id properties and use them to get the values from your object and set them on the using(propertyname, propertyvalue)

*if something is found copy the data, else just save the object you just created


Q: Read TIFF ICC profile using Twelvemonkeys ImageIO I need to extract the embedded ICC profile from TIFF files. I can read the IIOMetadata and my IDE shows the ifd field containing the ICC profile (tag ID 34675). But how can I read it to a ICC_Profile object?
ImageInputStream input = ImageIO.createImageInputStream(file);

try {
    ImageReader reader = ImageIO.getImageReaders(input).next();
    if (reader == null) {
        throw new IllegalArgumentException("No image reader for file: " + file);
    }

    try {
        reader.setInput(input);
        IIOMetadata metadata = reader.getImageMetadata(0);
        // metadata contains a field "ifd" containing the ICC profile
        // How to extract it?

    } finally {
        reader.dispose();
    }

} finally {
    input.close();
}

A: You can use the function getProfile() of the ICCProfile class.
Usage:
int profileId = ...;
ICCProfile iccp = new ICCProfile(profileId, input);
ICC_Profile icc_p = iccp.getProfile();

In accordance to the code at google result #1 for twelvemonkeys icc_profile.

A: Found a solution. For this Twelvemonkeys package imageio-metadata is needed in version 3.4. Older version does not contain TIFFEntry class.
 /**
 * Extract ICC profile from an image file.
 *
 * @param file image file
 * @return ICC profile
 * @throws IOException on file errors
 */
protected ICC_Profile extractICCProfile(File file) throws IOException {

    ICC_Profile profile;

    try (ImageInputStream input = ImageIO.createImageInputStream(file)) {
        ImageReader reader = ImageIO.getImageReaders(input).next();
        if (reader == null) {
            throw new IllegalArgumentException("No image reader for file: " + file);
        }

        try {
            reader.setInput(input);
            TIFFImageMetadata metadata = (TIFFImageMetadata) reader.getImageMetadata(0);
            TIFFEntry entry = (TIFFEntry) metadata.getTIFFField(TIFF.TAG_ICC_PROFILE);
            byte[] iccBytes = (byte[]) entry.getValue();
            profile = ICC_Profile.getInstance(iccBytes);
        } finally {
            reader.dispose();
        }
    }

    return profile;
}


Q: How to use a 3D stl viewer on Ruby on Rails I found this javascript plugin that allows to visualize STL files in 3D:
https://www.viewstl.com/plugin/
The example works very well, the problem is that I can not find how to put that into a rails template. I took all the javascript files to my assets/javascript, then I added the respective '// = require' in aplication.js, I took the small script with the div:

and put them in my template but it does not work. Watching the console of my browser I found the following error: ReferenceError: importScripts is not defined. I saw that it has to do with web workers and that an importScripts only works inside them but this problem does not appear in the test.html so I guess something I'm doing wrong when putting them in rails that blocks or prevents the correct operation of importScripts.
I apologize for my lack of fluency in English.
Help :(


Q: Server Side Hooks on Bitbucket I'm new to creating git hooks. I've successfully created a local git hook but I am having a hard time figuring out how to install a server side hook on Bitbucket.
I've tried using a plugin called External Hooks and making a External Pre Receive Hook, but that results in my push to Bitbucket being rejected with:
remote: Hook external-pre-receive-hook blocked the push
 ! [remote rejected] master -> master (pre-receive hook declined).
I've tried putting the hook in the .git folder on the server. But there's not a .git folder that I can find. I did find ApplicationData/Bitbucket/bin/git-hooks. I tried putting a pre-receive hook file in there but that was not successful. It did not prevent a push to the repo but the file also did not execute.
The hook/file that I'm using is as simple as can be so I don't think thats the problem. It has this text:
#!/bin/sh
#

echo 'hi there soldier'

A: I found out where to add a pre-receive or post-receive hook on a repository basis by adding a file to the Bitbucket server. In the Atlassian folder, it is in ApplicationData\Bitbucket\shared\data\repositories\[repository#]\hooks\.
Bitbucket keeps track of repos internally using numbers and not names so in the above replace [repository#] with the repo number. That can be found out this way.
Put the pre-receive hook in the pre-receive.d folder. Put the post-receive hook in the post-receive.d folder.
The names of the hooks/files should begin with a number. That determines what order the hooks are 'activated'. Begin the numbers with at least 21 because the default hook in the folder begins with 20. You want your hook to be activated after the one shipped with Bitbucket server. So a file name for a pre-receive hook could be 21_pre_receive.
Don't change the default hooks that are in the folder because they are needed to help Bitbucket work.
More information can be found here.


Q: How can I get the maximum amount of the total amounts for different products in a month in Postgresql? I've just begun using Postgresql recently. I have a table named 'sales'.
create table sales
    (
        cust    varchar(20),
        prod    varchar(20),
        day integer,
        month   integer,
        year    integer,
        state   char(2),
        quant   integer
    )

insert into sales values ('Bloom', 'Pepsi', 2, 12, 2001, 'NY', 4232);
insert into sales values ('Knuth', 'Bread', 23, 5, 2005, 'PA', 4167);
insert into sales values ('Emily', 'Pepsi', 22, 1, 2006, 'CT', 4404);
insert into sales values ('Emily', 'Fruits', 11, 1, 2000, 'NJ', 4369);
insert into sales values ('Helen', 'Milk', 7, 11, 2006, 'CT', 210);
...

There are 500 rows, 10 distinct products and 5 distinct customers in total.
It looks like this:

Now I need to , find the most “popular” and least “popular” products (those products with most and least total sales quantities) and the corresponding total sales quantities (i.e., SUMs) for each of the 12 months (regardless of the year).
The result should be like this:

Now I can only write query like this:
select month,
       prod,
       sum(quant)
from sales
group by month,prod
order by month,prod;

And it gives me the result like this:

Now I need to pick up the maximum value for each month. For example, the biggest value in the first 10 sums of month 1, and so on...
I also need to get the minimum value of the sums (regardless of the year). And combine them horizontally... I have no idea about this...

A: Note: for a TLDR, skip to the end.
Your problem is a very interesting textbook case as it involves multiple facets of Postgres.
I often find it very helpful to decompose the problem into multiple subproblems before joining them together for the final result set.
In your case, I see two subproblems: finding the most popular product for each month, and finding the least popular product for each month.
Let's start with the most popular products:
WITH months AS (
  SELECT generate_series AS month
  FROM generate_series(1, 12)
)
SELECT DISTINCT ON (month)
  month,
  prod,
  SUM(quant)
FROM months
LEFT JOIN sales USING (month)
GROUP BY month, prod
ORDER BY month, sum DESC;

Explanations:

*

*WITH is a common table
expression,
which acts as a temporary table (for the duration of the query) and
helps clarify the query. If you find it confusing, you could also opt
for a subquery.

*generate_series(1, 12) is a Postgres function which generate a series of integers, in this case from 1 to 12.

*the LEFT JOIN allows us to associate each sale to the corresponding month. If no sale can be found for a given month, a row is returned with the month and the joined columns with NULL values. More information on joins can be found here. In your case, using LEFT JOIN is important, as using INNER JOIN would exclude products that have never been sold (which in that case should be the least popular product).

*GROUP BY is used to sum over the quantities.

*at this stage, you should -potentially- have multiple products for any given month. We only want to keep those with the most quantities for each month. DISTINCT ON is especially useful for that purpose. Given a column, it allows us to keep the first iteration of each value. It is therefore important to ORDER the sales by sum first, as only the first one will be selected. We want the bigger numbers first, so DESC (for descending order) should be used.

We can now repeat the process for the least popular products:
WITH months AS (
  SELECT generate_series AS month
  FROM generate_series(1, 12)
)
SELECT DISTINCT ON (month)
  month,
  prod,
  SUM(quant)
FROM months
LEFT JOIN sales USING (month)
GROUP BY month, prod
ORDER BY month, sum;

Conclusion (and TLDR):
Now we need to merge the two queries into one final query.
WITH months AS (
  SELECT generate_series AS month
  FROM generate_series(1, 12)
), agg_sales AS (
  SELECT
    month,
    prod,
    SUM(quant)
  FROM months
  LEFT JOIN sales USING (month)
  GROUP BY month, prod
), most_popular AS (
  SELECT DISTINCT ON (month)
    month,
    prod,
    sum
  FROM agg_sales
  ORDER BY month, sum DESC
), least_popular AS (
  SELECT DISTINCT ON (month)
    month,
    prod,
    sum
  FROM agg_sales
  ORDER BY month, sum
)
SELECT
  most_popular.month,
  most_popular.prod AS most_popular_prod,
  most_popular.sum AS most_pop_total_q,
  least_popular.prod AS least_popular_prod,
  least_popular.sum AS least_pop_total_q
FROM most_popular
  JOIN least_popular USING (month);

Note that I used an intermediate agg_sales CTE to try and make the query a bit clearer and avoid repeating the same operation twice, although it shouldn't be a problem for Postgres' optimizer.
I hope you find my answer satisfactory. Do not hesitate to comment otherwise!
EDIT: although this solution should work as is, I would suggest storing your dates as a single column of type TIMESTAMPTZ. It is often much easier to manipulate dates using that type and it is always good practice in case you need to analyze and audit your database further down the line.
You can get the month of any date by simply using EXTRACT(MONTH FROM date).


Q: Using Breeze With Web Api And Angular js i want to select item from drop down list and then i will see selected customer data in input
then iwant to edit inputs and then save them in database by breez js and web api
I have Web Api Controller like This :
[BreezeController]
    public class ZzaController : ApiController
    {
        readonly EFContextProvider<ZzaDbContext> _contextProvider =
            new EFContextProvider<ZzaDbContext>();

        // ~/breeze/Zza/Metadata
        [HttpGet]
        public string Metadata()
        {
            return _contextProvider.Metadata();
        }

        // ~/breeze/Zza/Customers
        [HttpGet]
        public IQueryable<Customer> Customers()
        {
            var customers = _contextProvider.Context.Customers;
            return customers;
        }

        // ~/breeze/Zza/SaveChanges
        [HttpPost]
        public SaveResult SaveChanges(JObject saveBundle)
        {
            return _contextProvider.SaveChanges(saveBundle);
        }
    }

Angular Service Like This :
var services = function (http) {
    breeze.config.initializeAdapterInstance("modelLibrary", "backingStore");
    this.getBybreeze = function (successed) {

        var dataService = new breeze.DataService({
            serviceName: 'breeze/Zza',
            hasServerMetadata: false
        });
        var manager = new breeze.EntityManager(
        {
            dataService: dataService
        });
        var entityQuery = breeze.EntityQuery;
        return entityQuery.from('Customers').using(manager).execute().then(successed).catch();

    }
    this.saveByBreeze  =function () {

        var dataService = new breeze.DataService({
            serviceName: 'breeze/Zza',
            hasServerMetadata: false
        });
        var manager = new breeze.EntityManager(
        {
            dataService: dataService
        });
        manager.saveChanges().fail(function (error) { alert("Failed save to server: " + error.message); });

    }
}

services.$inject = ["$http"];
app.service("TestService", services);

And Angular Controler Like This :
var controller = function (scope, testService, ngTableParams, filter, upload, notification) {
    var self = this;
    self.title = "Test";
    self.customers = [];
    self.selected = "";
    self.selectedFirstName="";
    self.selectedLastName="";
    testService.getBybreeze(function (data) {
        self.customers = data.results;
    });
    self.selectedCustomer = function () {
        angular.forEach(self.customers, function (item) {
            if (item.Id === self.selected) {
                self.selectedFirstName = item.FirstName;
                self.selectedLastName = item.LastName;
            }
        });
    }
    self.save = function () {
        testService.saveByBreeze();
    }
}
controller.$inject = ["$scope", "TestService", "NgTableParams", "$filter", "Upload", "Notification"];
app.controller("TestController", controller)

View :

            Customers:

            <select class=" form-control" ng-change="self.selectedCustomer()" name="Id" ng-model="self.selected" ng-options="item.Id as item.FullName for item in self.customers"></select>

        <fieldset data-bind="with: currentCustomer">
            <legend>Customer:</legend>
            Name:

            <input class="form-control" id="customerName" value="{{self.selectedFirstName}}" />
            Tell:

            <input id="customerPhone" class="form-control" value="{{self.selectedLastName}}"  />

            <button class=" btn btn-default" id="saveButton" ng-click="self.save()">Save</button>
        </fieldset>

I think EveryThing Is ok
but when I save it,nothing Saved

A: Your code creates a new empty EntityManager with each query and save operation.  Instead, you should create a single EntityManager in your TestService, and use it for all query and save operations.
var services = function (http) {
    breeze.config.initializeAdapterInstance("modelLibrary", "backingStore");
    var dataService = new breeze.DataService({
        serviceName: 'breeze/Zza',
        hasServerMetadata: false
    });
    var manager = new breeze.EntityManager(
    {
        dataService: dataService
    });

    this.getBybreeze = function (successed) {
        var entityQuery = breeze.EntityQuery;
        return entityQuery.from('Customers').using(manager).execute().then(successed);
    }

    this.saveByBreeze = function () {
        manager.saveChanges().catch(function (error) { alert("Failed save to server: " + error.message); });
    }
}

services.$inject = ["$http"];
app.service("TestService", services);


Q: Regex replace total string I have and XML file with items that contain this string:
<field name="itemid">xx</field>
Where xx = a number from 50 to 250.
I need to remove the entire string from the whole file.
How would I do this with a Regex replace?

A: you can use this:
str = str.replace(/<.*>/g,'');

See an example for match here

var str = "<field name='itemid'>xx</field>";
str = str.replace(/<.*>/g, 'replaced');
console.log(str)

Explanation:

*

*< matches the character < literally

*.* matches any character (except newline)

*

*Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]

*> matches the character > literally

*g modifier: global. All matches (don't return on first match)

If you want to be more restrictive you can do this:
str = str.replace(/<field name\=\"\w*\">\d*<\/field>/g, '');

See an example for match here

var str = '<field name="test">200</field>';
str = str.replace(/<field name\=\"\w*\">\d*<\/field>/g, 'replaced');
console.log(str)

Explanation:

*

*<field name matches the characters

*\= matches the character = literally

*\" matches the character " literally

*\w* match any word character [a-zA-Z0-9_]

*

*Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]

*\" matches the character " literally

*> matches the character > literally

*\d* match a digit [0-9]
      -  Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]

*< matches the character < literally

*\/ matches the character / literally

*field> matches the characters field> literally (case sensitive)

*g modifier: global. All matches (don't return on first match)

A: When you replace a tag especially XML tag you must be sure that you capture everything from opening to closing tag. In this case RegExp should look back.
var re = /<(\S+)[^>]*>.*<\/\1>/g;
var m ='some text <ab id="aa">aa
qq
 aa</ab>test test
paragraph
'.replace(re,'');
console.log(m);//some text test test

\1 matches (\S+)
\S+ one or more non-white-space characters


Q: Soft delete in sails.js I'm trying to implement soft delete on a model in a sails.js project by I override the delete action in the respective controller to just update a boolean attribute called isDeleted.
The problem I'm facing is that, I need to override the find action for the respective controller so that it'll ignore the "deleted" records but I need to keep the rest of the original functionality. To do this I'm simply copying the code of the original find action into the override, but it depends on the actionUtil module, and, when doing the require for that module, no matter how I change the route it never manages to find the module.
So, this is what my controller looks like:
var actionUtil = require('/sails/lib/hooks/blueprints/actionUtil'),
_ = require('lodash');

module.exports = {

find: function(req, res){

    // Look up the model
    var Model = actionUtil.parseModel(req);

    if ( actionUtil.parsePk(req) ) {
        return require('./findOne')(req,res);
    }

    // Lookup for records that match the specified criteria
    var query = Model.find()
    .where( actionUtil.parseCriteria(req) )
    .limit( actionUtil.parseLimit(req) )
    .skip( actionUtil.parseSkip(req) )
    .sort( actionUtil.parseSort(req) );

    // TODO: .populateEach(req.options);
    query = actionUtil.populateEach(query, req);

    query.exec(function found(err, matchingRecords) {
        if (err) return res.serverError(err);

        // Only `.watch()` for new instances of the model if
        // `autoWatch` is enabled.
        if (req._sails.hooks.pubsub && req.isSocket) {
            Model.subscribe(req, matchingRecords);

            if (req.options.autoWatch)
                { Model.watch(req); }

            // Also subscribe to instances of all associated models
            _.each(matchingRecords, function (record) {
                actionUtil.subscribeDeep(req, record);
            });
        }

        res.ok(matchingRecords);
    });

},//End .find

destroy: function(req,res){

    console.log("Parametro: " + req.param('id') );
    Vendedor.update({ id_vendedor: req.param('id') }, { isDeleted: true })
    .exec(function (err, goal)
    {
        if (err)
            return res.status(400).json(err);

        return res.json(goal[0]);
    });

}
};

But, when starting the server I get an error, saying that the module actionUtil couldn't be found. Does anyone know how I could do this?


Q: Joining Tables For Find the Playlists without any track of the genres “Latin”, “Rock” or “Pop” I have a basic problem about create a query for Find the Playlists without any track of the genres “Latin”, “Rock” or “Pop”. I am really struggling with Joins some exercises I can do well but with this I can figure out.
I tried This:
SELECT p.PlaylistId as Playlist, p.Name
FROM Playlist p INNER JOIN PlaylistTrack pt ON p.PlaylistId = pt.PlaylistId
INNER JOIN Track t ON pt.TrackId = t.TrackId
JOIN Genre g ON g.GenreId = t.GenreId
WHERE g.Name <> "Latin " AND "Rock" AND "Pop"

My Output are returning 1 value: AC/DC, and null values when I use LEFT JOIN.
This is my DDL:
CREATE TABLE Genre (GenreId int PRIMARY KEY, `Name` CHAR(255) );
CREATE TABLE MediaType ( MediaTypeId int PRIMARY KEY, `Name` CHAR(30) );
CREATE TABLE Artist(ArtistId INT PRIMARY KEY, `Name` CHAR(255) ); -- LONG CHAR????
CREATE TABLE Album(AlbumId INT PRIMARY KEY, Title CHAR(120), ArtistId INT );
CREATE TABLE Track( TrackId int PRIMARY KEY, `Name` CHAR(255), AlbumId INT,
 MediaTypeId INT, GenreId INT, Composer CHAR(220), Milliseconds int, Bytes INT, UnitPrice decimal(8,2)); -- UnitPrice number
CREATE TABLE Playlist(PlaylistId int PRIMARY KEY, `Name` CHAR(30));

If you are more interested and want to test this database that I build check this link, is a little dirty and need to be improve but commenting some rows will work.

As I Said: My Output are returning 1 value: AC/DC, and null values when I use LEFT JOIN.

This is the expected value:

PlaylistId
Name

2,
Movies

5
TV Shows

6
Audiobooks

7
Audiobooks

8
Movies

9
Music Videos

10
TV Shows

11
Classical

12
Classical 101 - Deep Cuts

13
Classical 101 - Next Step

14
Classical 101 - The Basics

15
On-The-Go 1

I thought that this question was really easy. I dont understand why I can't figure out, can someone help me?

A: SELECT *
FROM Playlist
WHERE NOT EXISTS ( SELECT NULL
                   FROM PlaylistTrack
                   INNER JOIN Track USING (TrackId)
                   INNER JOIN Genre USING (GenreId)
                   WHERE Playlist.PlaylistId = PlaylistTrack.PlaylistId
                     AND Genre.Name IN ('Latin', 'Rock', 'Pop') )


Q: How to compress (resize?) >60k images on mac? There are >60k images 10KB-1MB size and i need them all weighing <80KB, how do i go about this? Can't open so many images with preview. I guess there is a solution for this in terminal

A: First install ImageMagick and GNU Parallel with homebrew:
brew install imagemagick
brew install parallel

Then go to the directory where the images are and create an output directory:
cd where/the/images/are
mkdir output

Now run ImageMagick from GNU Parallel
find . -name "*.jpg" -print0 | parallel -0 magick {} -define jpeg:extent=80kb output/{}


Q: ASP.net Recover JavaScript Created Attribute from PostBack I've create a control that derivates from a TextBox. On that class is added an call for a Javascript code that, when the content of the text changes, it adds a attribute called "post" with value "true" to the control. I wish to collect that value.
So far i have this:
ASP
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="CWEB.Web.UI.USR.DefPage" %>
<%@ Register TagPrefix="Controls" Namespace="CWEB.Web.Controls" Assembly="Web" %>
<html>
<head>
    <script type="text/javascript">
        function SetPost(element){if(!element.hasAttribute('post')){z=document.createAttribute('post');z.value='true';element.setAttributeNode(z);}else{element.setAttribute('post','true');}}
    </script>
</head>
<body>
    <Controls:TextBox runat="server" ID="abc" />
</body>
</html>

CodeBehind (and TextBox derivated class)
using SysWeb = global::System.Web.UI;
using CtrWeb = global::CWEB.Web.Controls;
namespace CWEB.Web
{
    internal static class Binder
    {
        internal const string PostableKey = "post";
        internal const string AuxFieldKey = "_ck";
        internal static bool GetCheck(string ck) { return (ck != null && ck != "" && (ck == global::CWEB.Data.Fields.Boolean.ValueTrue || ck.Contains("t") || ck.Contains("v"))); }

        private static bool GetCheckInput(CtrWeb.Controls.Generic.FieldControl Control, ref bool Found)
        {
            if (Control == null || Control.Page == null) { Found = false; }
            else
            {
                string value = Control.Page.Request.Form[Control.ClientID + CtrWeb.Binder.AuxFieldKey]; //If then it's child is null, it means it's unchecked.
                Found = (value != null && value != "");
                return ((Found) ? (value == "1" || value == "on" || value.Contains("t")) : false);
            }
            return false;
        }

        internal static bool GetCheck(CtrWeb.Controls.Generic.FieldControl Control, bool OutSideInput, string ViewStateKey = CtrWeb.Binder.CheckAttribute)
        {
            string value = Control.Page.Request.Form[Control.UniqueID]; //If the main control exists then it's child shal too.
            if (value == null || value == "") { return CtrWeb.Binder.GetCheck((string)Control.GetViewState()[ViewStateKey]); }
            else if (OutSideInput)
            {
                bool Found = false;
                return CtrWeb.Binder.GetCheckInput(Control, ref Found);
            } else { return CtrWeb.Binder.GetCheck((string)Control.GetAttributes()[ViewStateKey]); }
        }

        internal static void SetCheck(CtrWeb.Controls.Generic.FieldControl Control, bool OutSideInput, string ViewStateKey = CtrWeb.Binder.CheckAttribute)
        {
            bool FValue = CtrWeb.Binder.GetCheck(Control, OutSideInput, ViewStateKey: ViewStateKey);
            Control.GetViewState()[ViewStateKey] = ((FValue) ? "true" : "false");
        }
    }

    namespace Controls
    {
        public interface FieldControl
        {
            string ClientID { get; }
            string UniqueID { get; }
            SysWeb.Page Page { get; }
            SysWeb.AttributeCollection GetAttributes();
            SysWeb.StateBag GetViewState();
        }

        public class TextBox : SysWeb.WebControls.TextBox, CtrWeb.FieldControl
        {
            public bool Postable
            {
                get { return CtrWeb.Binder.GetCheck(this, false, ViewStateKey: CtrWeb.Binder.PostableKey); }
                set { CtrWeb.Binder.SetCheck(this, false, ViewStateKey: CtrWeb.Binder.PostableKey); }
            }

            protected override void LoadViewState(object savedState)
            {
                this.BaseLoadViewState(savedState);
                this.Postable = CtrWeb.Binder.GetCheck(this, false, ViewStateKey: CtrWeb.Binder.PostableKey);
            }

            protected override void OnInit(global::System.EventArgs e)
            {
                if (!this.Page.IsPostBack)
                {
                    this.Attributes.Add("onchange", "SetPost(this)");
                    this.Attributes.Add(MdWeb.Binder.PostableKey, "false");
                }
                base.OnInit(e);
            }
        }
    }

    namespace UI.USR
    {
        public class DefPage : SysWeb.Page { protected CtrWeb.TextBox abc; }
    }
}

Some codes were not copied here because they have nothing to do with the issue.

A: In order for that data to be posted to the server, you have to store it in a form value.
HTML elements in their entirety aren't posted to the server.  Only the key/value pairs of form elements are.  (WebForms is trying to trick you into thinking that the whole page is posted to the server, but it's a lie.)
Add a hidden form field to the page, something as simple as this:
<asp:Hidden id="someHiddenField" />

Then in the JavaScript, set the value of that field:
document.getElementById('<%= someHiddenField.ClientID %>').value = 'true';

Then when the page posts back to the server, the 'true' value will be in that hidden field:
someHiddenField.Value

A: asp:Hidden doesn't exist. only form elements can actually postback data. The server side will take the postback data and load it into the form element provided that the runat=server is set.
in markup or html:
<input type="hidden" runat="server" ID="txtHiddenDestControl" />

javascript:
document.getElementById('<%= txtHiddenDestControl.ClientID %>').value = '1';

code behind:
string postedVal = txtHiddenDestControl.Value.ToString();


Q: Failing to upload a local aar file to artifactory using gradle I have a simple problem which I have not been able to solve. I have downloaded an external .aar file that I want to upload to our in house Artifactory. But I havent been able to solve the problem at all. Here is my build.gradle file
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'digital.wup:android-maven-publish:3.6.2'
    }
}
apply plugin: 'maven'
apply plugin: 'maven-publish'
apply plugin: 'digital.wup.android-maven-publish'

group 'com.hello'

def version = '3.1'
def groupA = 'com.hello'
def artifactA = 'world'
def intermediateDirName = 'outputs/aar'

def aarFileLocation = "${buildDir}/${intermediateDirName}/${artifactName}-${datadogVersion}.aar"

configurations {
    aarLocal
}

dependencies {

   aarLocal files('world-3.1.aar')

}

task copyFromLocal(type: Copy) {
    from configurations.aarLocal
    into "$buildDir/$intermediateDirName"
}

publishToMavenLocal.dependsOn copyFromLocal
publish.dependsOn copyFromLocal

publishing {
  publications {
    publishAarToArtifactory(MavenPublication) {
        groupId groupName
        artifactId artifactName
        version datadogVersion
        artifact "${buildDir}/${intermediateDirName}/${artifactName}-${version}.aar"
    }
  }
}

publishToMavenLocal works w/o any problems but the publish task gets skipped
Following is the error message I get Skipping task ':publish' as it has no actions. Any help?
Basically uploading a local aar to artifactory is all that i am trying to achieve.
NOTE : The repo credentials are in our CI/CD system for artifactory.

A: Both publishToMavenLocal and publish are aggregate tasks without actions. They are used to trigger a bunch of publishPubNamePublicationToMavenLocal tasks and publishPubNamePublicationToRepoNameRepository tasks respectively.
$ ./gradlew publishToMavenLocal --info
...
> Task :publishMavenPublicationToMavenLocal
...
> Task :publishToMavenLocal
Skipping task ':publishToMavenLocal' as it has no actions.
:publishToMavenLocal (Thread[Execution worker for ':',5,main]) completed. Took 0.0 secs.

$ ./gradlew publish --info
...
> Task :publishMavenPublicationToMavenRepository
...
> Task :publish
Skipping task ':publish' as it has no actions.
:publish (Thread[Execution worker for ':',5,main]) completed. Took 0.0 secs.

Reference: https://docs.gradle.org/current/userguide/publishing_maven.html#publishing_maven:tasks


Q: Best way of writing subroutines in 6502 Assembler? I'm new to assemblers, so here is a simple question:
My custom subroutines change the X, Y, and A registers. They manipulate these to produce the desired results. Is it a good idea to push these values to the stack when the routine starts and restore them before RTS?
I mean, this way I can write routines which can be called from anywhere without messing up the "state" or affecting other routines. But is it OK to use the stack this way? Or is there a better way to do this?

A:
But is it OK to use the stack this way? Or is there a better way to do this?

Absolutely; BASIC does it all the time, as do many routines in the kernal.
But, there is no right answer to this, it comes down to at least speed, portability, and style.

*

*If you use the stack a lot, there are some speed considerations.  Your typical pha txa pha tya pha at the start, and then the reverse (pla tay pla tax pla) eats up 3 bytes of your stack, and adds in some cycle time due to the 2 x 5 operations

*You could use zero page, but that takes away some portability between different machines; VIC-20, C64, C128, the free zero page addresses may not be the same across platforms.  And your routine can't be called "more than once" without exiting first (e.g. no recursion) because if it is called while it is active, it will overwrite zero page with new values.  But, you don't need to use zero page...

*...because you can just create your own memory locations as part of your code:
myroutine = *
    ; do some stuff..
    rts

mymem =*
    .byt 0, 0, 0

*the downside to this is that your routine can only be called "once", otherwise subsequent calls will overwrite your storage areas (e.g. no recursion allowed!!, same problem as before!)

*You could write your own mini-stack
  put_registers =*
     sei ; turn off interrupts so we make this atomic
     sty temp
     ldy index
     sta a_reg,y
     stx x_reg,y
     lda temp
     sta y_reg,y
     inc index
     cli
     rts

  get_registers =*
     sei ; turn off interrupts so we make this atomic
     dec index
     ldy index
     lda y_reg,y
     sta temp
     lda a_reg,y
     ldx x_reg,y
     ldy temp
     cli
     rts

  a_reg .buf 256
  x_reg .buf 256
  y_reg .buf 256
  index .byt 0
  temp  .byt 0

*This has the added benefit that you now have 3 virtual stacks (one for each of .A, .X, .Y), but at a cost (not exactly a quick routine).  And because we are using SEI and CLI, you may need to re-think this if doing it from an interrupt handler.  But this also keeps the "true" stack clean and more than triples your available space.


Q: Running multpe containers without composer? Hey all I have three containers that I am currently running in compose
version: '2'

services:

  web:
    restart: always
    build:
      context: ./
      dockerfile: deploy-1w/web.dockerfile
    ports:
      - "9000:9000"
    links:
      - redis:redis
    volumes:
      - /usr/src/app
      - /usr/src/app/source/static
    env_file:
      - .env
    environment:
      - 'DEBUG=true'
      - 'DOCKER_COMPOSE_MODE=true'
      - 'APP_ENV=local'

  nginx:
    restart: always
    build:
      context: ./
      dockerfile: deploy-1w/nginx.dockerfile
    ports:
      - "80:80"
    volumes:
      - /www/static
    volumes_from:
      - web
    env_file:
      - .env
    links:
      - web:web
    environment:
      - "BACKEND_ADDR=web:9000"
      - 'DOCKER_COMPOSE_MODE=true'
      - 'APP_ENV=local'

  redis:
    restart: always
    build:
      context: ./
      dockerfile: deploy-1w/cache.dockerfile
    ports:
      - "6379:6379"
    volumes:
      - ./redisdata:/data

I am trying to run these without using compose (more for debugging purposes and understanding of what composer is actually DOING more than anything) but due to the links etc i am not able to get them running (nginx is using proxy pass and looking for an upstream of web)
Here's the Dockerfile for web
FROM python:2-onbuild

WORKDIR /usr/src/app/

RUN cp -rf /usr/src/app/src/* /usr/src/app/

# build dependencies
RUN apt-get update && apt-get install -y git-core rubygems ruby-dev gettext nano  \
    && wget nodejs.org/dist/v6.10.0/node-v6.10.0-linux-x64.tar.gz                 \
    && tar -C /usr/local --strip-components 1 -xzf node-v6.10.0-linux-x64.tar.gz

RUN pip install -r requirements.txt

RUN apt-get install nodejs-legacy -y                                              \
    && gem install sass compass                                                   \
    && npm install -g grunt-cli bower

# Bad command?
#RUN npm install -g

RUN npm install grunt@0.4.5 -g --save-dev                                         \
    && npm install                                                                \
    && bower install --allow-root

RUN grunt buildcss                                                                \
    && grunt buildjs --force

# Add the local settings file
COPY ./deploy-1w/config/local_settings.py /usr/src/app/source/source/local_settings.py

# copy the bootstrap script
COPY ./deploy-1w/web-bootstrap.sh  /usr/local/bin/web-bootstrap.sh
RUN chmod 775 /usr/local/bin/web-bootstrap.sh

WORKDIR /usr/src/app/source

# run bootstrap script
CMD ["/usr/local/bin/web-bootstrap.sh"]

Nginx
FROM tutum/nginx

# backend web address
ENV BACKEND_ADDR 0.0.0.0:0

# build dependencies
RUN apt-get update && apt-get install -y gettext

# copy config template
COPY ./deploy-1w/config/nginx.conf /etc/nginx/nginx.conf.template

# copy static file to use as a health check
COPY ./deploy-1w/config/nginx-health-check /var/www/html/public/health-check

# copy the bootstrap script
COPY ./deploy-1w/nginx-bootstrap.sh  /usr/local/bin/nginx-bootstrap.sh
RUN chmod 775 /usr/local/bin/nginx-bootstrap.sh

# run bootstrap script
CMD ["/usr/local/bin/nginx-bootstrap.sh"]

and Redis
FROM debian:jessie

ENV REDIS_MAJOR_MINOR_VERSION 4.0
ENV REDIS_VERSION 4.0.10
ENV REDIS_TARBALL_SHA1 d2738d9b93a3220eecc83e89a7c28593b58e4909
ENV BACKEND_ADDR 0.0.0.0:0

RUN apt-get -q update && \
  DEBIAN_FRONTEND=noninteractive apt-get -qy --no-install-recommends install \
    build-essential \
    curl && \
  curl -O http://download.redis.io/releases/redis-$REDIS_VERSION.tar.gz && \
  [ $(shasum redis-$REDIS_VERSION.tar.gz | awk '{ print $1 }') = $REDIS_TARBALL_SHA1 ] && \
  tar zxf redis-$REDIS_VERSION.tar.gz && \
  cd redis-$REDIS_VERSION && \
  make -j$(nproc) && \
  cd src && \
  cp \
    redis-benchmark \
    redis-check-aof \
    redis-check-rdb \
    redis-cli \
    redis-sentinel \
    redis-server \
    /usr/local/bin && \
  cd ../.. && \
  rm -rf redis-$REDIS_VERSION redis-$REDIS_VERSION.tar.gz /tmp/* /var/tmp/* && \
  apt-get -qy purge build-essential curl && \
  apt-get -qy clean autoclean autoremove && \
  rm -rf /var/lib/{apt,dpkg,cache,log}/

COPY ./deploy-1w/config/redis.conf /etc/redis.conf

VOLUME /var/lib/redis

CMD ["/usr/local/bin/redis-server", "/etc/redis.conf"]

I am literally trying to do what i'm doing in composer... without composer...
What i'm doing is this, and it's failing
docker build -t redis-test -f deploy-1w/cache.dockerfile .
docker build -t nginx-test -f deploy-1w/nginx.dockerfile .
docker build -t web-test -f deploy-1w/web.dockerfile .

docker network create test-network

docker run -d -it -p --network test-network '6379:6379' redis-test
docker run -d -it -p --network test-network '9000:9000' --link $(docker ps -a | grep redis-test |awk '{print$1}') web-test
docker run -d -it -p --network test-network '80:80' -e 'BACKEND_ADDR=web:9000' --link $(docker ps -a | grep web-test |awk '{print$1}') nginx-test

The above give me an error...
bash-4.4$ docker logs bc28bcd28653
nginx: [emerg] host not found in upstream "web" in /etc/nginx/nginx.conf:35

Here's the pertinent part of the nginx conf
location / {
  proxy_pass http://${BACKEND_ADDR};    <-- Line 35
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

A: I use to have so many issues with docker and nginx because I didn't understand everything very well.
So here is my recommendation:
Quick fix :
Add
nginx:
    restart: always
    ....
    depends_on:
        - web

Explanation :
Nginx with upstream can be useful but if the upstream doesn't exist, then nginx will never start.
And in the docker case, you have to say that web should run before nginx using depends_on parameter.
But after upgrading my stack to docker swarm, I discovered that depends_on can't be used anymore across multiple instances
for a reason I don't remember.
So I wanted to start nginx even if my web server is not running and the easy way to do it is to use variable
in nginx like this :
      set $server_1 web;
      proxy_pass http://$server_1:8080;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header HOST $host;
      proxy_set_header X-NginX-Proxy true;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

I definitly advise you to use the last docker-compose version because you have so much better feature.
Also, using link is quite deprecated, I recommend you to create an internal network using docker network command.
It's very useful to add or remove an instance to it and you save time and maintainability.
Running multiple containers without composer
You need to use docker run command for each container
docker run -d --name web -p 9000:9000 ....
docker run -d --name nginx -p 80:80 ....


Q: Copy data from excel to excel with openpyxl Couldn't find answers I can understand. So I've decided to ask.
I'm learning Python. And now I'm trying to solve a problem with collecting data from active spreadsheet in one excel file and paste it to another excel file. The first file contains table and a few cells with information to the right of it. I'm trying to fully copy the spreadsheet data.
import openpyxl, os
from openpyxl.cell import get_column_letter

os.chdir('D:\\Python')
wb = openpyxl.load_workbook('auto.xlsx')
ws = wb.active

# Create new workbook and chose active worksheet.
wbNew = openpyxl.Workbook()
wsNew = wbNew.active

# Loop through all cells (rows, then columns) in the first file
# and fill in the second one.
for allObj in ws['A1':get_column_letter(ws.max_column) + str(ws.max_row)]:
    for cellObj in allObj:
        for allNewObj in wsNew:
            for newCellObj in allNewObj:
               wsNew[cellObj.coordinate].value = cellObj.value
wbNew.save('example.xlsx')

Finally it works.


Q: Are usings guarding for all eventualities? I've found the following passage.
using (TextWriter w1 = new StringWriter(...))
using (XmlWriter w2 = new XmlTextWriter(w1))
using (StringReader r1 = new StringReader(...))
using (XmlTextReader r2 = new XmlTextReader(r1))
{
  _xslt.Transform(r2, w2);
  ...
  FileOperations.LockFiles();

  w1.Close();
  w2.Close();
  r1.Close();
  r2.Close();
}

My suggestion is (besides renaming, of course) that we could remove the last four statements, since those are declared using using and will be closed and disposed properly when the framework feels like it.
However, one of the developers questioned me and asked a very disturbing question. "Are you entirely sure?". Then I got chicken feet and postponed the answer. Is there anything I could be missing?

A: Yes, the using blocks will always dispose the objects, no matter what. (Well, short of events like a power outage...)
Also, the disposing of the objects is very predictable, that will always happen at the end of the using block. (Once the objects are disposed, they are removed from the finalizer queue and are just regular managed objects that can be garbage collected, which happens when the garbage collector finds it convenient.)
In contrast, the Close calls will only be called if there are no unhandled exceptions inside the block. If you wanted them to surely be executed you would place them in finally blocks so that they are exected even if there is an exception. (That's what the using blocks are using to make sure that they can always dispose the objects.)

A: There are plenty of circumstances in which a using won't dispose of the resource in question.  For example, if you pull the plug on the machine while the using is running, the finally block (which the using is translated to) won't run.
There is no situation in which the finally block wouldn't get run in which duplicating the same cleanup steps inside the using would be any better suited to handle.

A: If disputes like this ever come up, just fire up ILSpy (http://ilspy.net/) and peek inside the framework to see what it is actually doing on the Dispose that gets called from the end of the using statement.
In this case, you are right and all four of StringWriter, StringReader, XmlTextReader, and XmlTextWriter do their disposal work in the Dispose method and Close simply calls Dispose, so those four lines are redundant. (But note that StringWriter and StringReader don't seem to do anything interesting in their Dispose methods.)


Q: Not sure what I am doing wrong - getting is not a function errors I am not sure what I am doing wrong, but I have a few functions inside my component.  However, I'm not able to pass one of those functions down as a prop, I receive a this.nextScene is not a function.
Here's a snippet from my component, and I have commented out where I am having the issue:
  nextScene() {
    this.refs.navigator.push('browse');
  }

  renderNavigationView() {
    return (
      <View style={styles.drawer}>
        <Touchable
          onPress={this.nextScene()}     //issue here, "this.nextScene is not a function"
        >
          <View style={styles.container}>
            <Text style={styles.title}>Browse</Text>
          </View>
        </Touchable>
        <Touchable>
          <View style={styles.container}>
            <Text style={styles.title}>Button</Text>
          </View>
        </Touchable>
      </View>
    );
  }

  render() {
    return (
      <DrawerLayoutAndroid
        ref="drawer"
        drawerWidth={300}
        drawerPosition={DrawerLayoutAndroid.positions.Left}
        renderNavigationView={this.renderNavigationView}>
        <Navigator
          ref="navigator"
          configureScene={(route) => {
            if (Platform.OS === 'android') {
              return Navigator.SceneConfigs.FloatFromBottomAndroid;
            }
          } }
          initialRoute={{}}
          renderScene={this.renderScene}
          />
      </DrawerLayoutAndroid>
    );
  }

Thanks!

A: If you take a look at the component you are rendering, and at the renderNavigationView prop:
renderNavigationView={this.renderNavigationView}

It seems fine, but since the this context in functions is window by default, this refers to window in renderNavigationView. Consider your onPress event handler:
onPress={this.nextScene()}

Since you use this.nextScene() and this refers to window in a function, you're effectively trying to do window.nextScene which does not exist, thus throwing the error. (Also note that that is an invocation - not a reference. Remove the parentheses).

So if I try this.nextScene.bind(this), I get a cannot read property 'bind' of undefined

This is because the function is undefined because window.nextScene doesn't exist. To fix this, use Function.prototype.bind to bind the this correctly on both renderNavigationView and nextScene:
renderNavigationView={this.renderNavigationView.bind(this)}

What bind does in this situation is set the this context in the function. Since this here refers to the class, the class will be used to execute the nextScene method which should work correctly. You must also use bind on nextScene because inside nextScene we want this to refer to the class, not window:
onPress={this.nextScene.bind(this)}

A: Another alternative to using the bind method that winter pointed out in his answer is to use arrow functions which automatically bind this to the parent context for you.
class MyComponent extends React.Component {
  clickHandler = (e) => {
    // do stuff here
  }

  render() {
    return (
      <button onClick={this.clickHandler}></button>
    )
  }
}


Q: A class extending Ext.Window ignores constructor parameters I am trying to create a popup window by extending Ext.Window class:
Ext.define('mine.nameCreationPopup',{
extend: 'Ext.Window',
alias: 'nameCreationPopup',

config:{
    title: 'aTitle', //default value
    width: 700 //default value
},

constructor: function(config){
    this.initConfig(config);
    this.superclass.constructor.call
    (this, {
        title: config.title,
        width: config.width,
        height: 300, //ignored from now on
        layout: 'fit',
        bodyStyle: 'padding:5px;',
        modal: true,
        resizable: false
    });
}

Now, creation:
var pops = Ext.create('nameCreationPopup',{title:'Dunno'});
pops.show();
pops.center();

Width and title are currectly set (title is Dunno, while width is 700 as default value) anyway height and the rest of window attributes are just ignored.
How come?

A: That is not the way how Ext.define should look like. Either configure the window directly (inline) or use initComponent. Inline configuration:
Ext.define('mine.nameCreationPopup',{
    extend: 'Ext.Window',
    alias: 'widget.nameCreationPopup',
    title: 'aTitle',
    width: 700,
    height: 300, //ignored from now on
    layout: 'fit',
    bodyStyle: 'padding:5px;',
    modal: true,
    resizable: false
});

initComponent:
Ext.define('mine.nameCreationPopup',{
    extend: 'Ext.Window',
    alias: 'widget.nameCreationPopup',
    initComponent:function() {
        Ext.applyIf(this, {
            title: 'aTitle',
            width: 700,
            height: 300, //ignored from now on
            layout: 'fit',
            bodyStyle: 'padding:5px;',
            modal: true,
            resizable: false
        });
        this.callParent(arguments);
    }
});


Q: xstream.fromXML returns a Class Using XStream 1.2.2
The XML document:
<?xml version="1.0" encoding="ISO-8859-1"?>
<Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" protocol="OCI" xmlns="C">
<sessionId xmlns="">192.168.1.19,299365097130,1517884537</sessionId>
  <command xsi:type="AuthenticationRequest" xmlns="">
    <userId>me@somewhere.com</userId>
  </command>
</Document>

I'm trying to parse into to a Document;
public class Document {
    private String sessionId;
    public Command command;
    public Command getCommand() {
        return this.command;
    }
    public void setCommand(Command command) {
        this.command = command;
    }
    public String getSessionId() {
        return sessionId;
    }
    public void setSessionId(String sessionId) {
        this.sessionId = sessionId;
    }
}

Parsing code is:
    XStream xstream = new XStream();
    xstream.alias("Document", Document.class);
    xstream.alias("sessionId", String.class);
    xstream.alias("command", Command.class);
    xstream.alias("userId", String.class);

    Document doc = (Document) xstream.fromXML(theInput, Document.class);

but this throws:

java.lang.ClassCastException: java.lang.Class cannot be cast to com.mycompany.ocip.server.model.Document

because the returned object from fromXml is of type: Class<com.mycompany.ocip.server.model.Document>
Shouldn't I expect it to return a com.mycompany.ocip.server.model.Document instance?

A: That needs to be:
Document doc = (Document) xstream.fromXML(theInput);

If you pass in a second parameter, XStream will try to populate that with the values from the XML. Since in your code, you're passing in a class object, XStream will try to populate the class object and return it.
The JavaDoc has the details.


Q: changing slice colour of a pie chart in excel VBA Initially I wrote a function which changes the appearance of a series of pie-charts according to predefined colour themes
    Function GetColorScheme(i As Long) As String
Const thmColor1 As String = "C:\Program Files\Microsoft Office\Document Themes 14\Theme Colors\Blue Green.xml"
Const thmColor2 As String = "C:\Program Files\Microsoft Office\Document Themes 14\Theme Colors\Orange Red.xml"
    Select Case i Mod 2
        Case 0
            GetColorScheme = thmColor1
        Case 1
            GetColorScheme = thmColor2
    End Select
End Function

However, the paths are not constant and I would like to define each Pie chart slice on its own by an rgb colour.
I found here on stackoverflow in a previosu topic (How to use VBA to colour pie chart)  a way to change the colour of each slice of a pie chart
but I don't knwo how to implement the code into the function mentioned above. Could I potentially write
    Function GetColorScheme(i As Long) As String

    Select Case i Mod 2
        Case 0
            Dim clr As Long, x As Long

For x = 1 To 3
    clr = RGB(0, x * 8, 0)
    With ActiveSheet.ChartObjects(1).Chart.SeriesCollection(1).Points(x)
        .Format.Fill.ForeColor.RGB = clr
    End With
Next x
        Case 1
            Dim clr As Long, x As Long

For x = 1 To 3
    clr = RGB(0, x * 8, 0)
    With ActiveSheet.ChartObjects(1).Chart.SeriesCollection(1).Points(x)
        .Format.Fill.ForeColor.RGB = clr
    End With
Next x
    End Select
End Function

The function is linked to the main part of the script (which is)
For Each rngRow In Range("PieChartValues").Rows
chtMarker.SeriesCollection(1).Values = rngRow
ThisWorkbook.Theme.ThemeColorScheme.Load GetColorScheme(thmColor)
chtMarker.Parent.CopyPicture xlScreen, xlPicture
lngPointIndex = lngPointIndex + 1
chtMain.SeriesCollection(1).Points(lngPointIndex).Paste
thmColor = thmColor + 1

where the line
 ThisWorkbook.Theme.ThemeColorScheme.Load GetColorScheme(thmColor)

gets the value of the function  (see first bit of code - the original function) but now I don#t longer have the thmColor variable defined and don't knwo how to best implement the code into the function part

A: Something like this (you'll need to adjust the colors to suit your needs)
http://www.rapidtables.com/web/color/RGB_Color.htm
Sub ApplyColorScheme(cht As Chart, i As Long)

    Dim arrColors

    Select Case i Mod 2
        Case 0
            arrColors = Array(RGB(50, 50, 50), _
                              RGB(100, 100, 100), _
                              RGB(200, 200, 200))
        Case 1
            arrColors = Array(RGB(150, 50, 50), _
                              RGB(150, 100, 100), _
                              RGB(250, 200, 200))
    End Select

    With cht.SeriesCollection(1)
        .Points(1).Format.Fill.ForeColor.RGB = arrColors(0)
        .Points(2).Format.Fill.ForeColor.RGB = arrColors(1)
        .Points(3).Format.Fill.ForeColor.RGB = arrColors(2)
    End With

End Sub

Example usage:
chtMarker.SeriesCollection(1).Values = rngRow
ApplyColorScheme chtMarker, thmColor
chtMarker.Parent.CopyPicture xlScreen, xlPicture


Q: SQL Query to get the Result in One Scan without using analytical function I have a table named Employee Which has 3 columns EmployeeID Award Date and Award
| EMPOYEEID | AwardDate | Award
|1          | 10-03-2018| EOY
|1          | 14-08-2018| EBF
|2          | 10-03-2017| EOY
|3          | 10-03-2016| EOY
|2          | 31-12-2017| COINS
|1          | 31-08-2017| COINS

Using SQL query in oracle, What i want is without using analytical function i want to get the first award and last award date for each employee in one scan.
Below is and example
ID|LastDate  | FirstAward
  1|10-03-2018|31-08-2017
  2|31-12-2017|10-03-2017

A: use aggregate function
select EMPOYEEID, max(AwardDate) LastDate, min(AwardDate) FirstAward
from table_name t1
group by EMPOYEEID