Q:

In Java compiler，which type can be defined as identifier ( ID ) or Keyword (reserved word)?

I have a simple question:
In Java Compiler, Which type of method or variables can be defined as identifier (ID) or Keyword (reserved word)?
For following example, ID should be : add, main, a, b, c, Test1, What about print, is print an ID or keyword?
Example:
public class Test1 {
    public static int add(int a, int b) {
        return a + b;
    }
    public static void main() {
        int c;
        int a = 5;
        c = add(a, 10);
        if (c > 10)
            print("c = " + -c);
        else
            print(c);
        print("Hello World");
    }
}

A:

An identifier is a word used by a programmer to name a variable, method, class, or label.
        // Test1 is a class name identifier
        public class Test1 {
                public static int add(int a, int b) { // add is identifier for a method
                      return a + b;
                 }

                public static void main() {
                    int c; // c is identifier for a variable
                    int a = 5;
                    c = add(a, 10);
                    if (c > 10)
                         print("c = " + -c);
                    else
                        print(c);
                    print("Hello World");
                 }
        }

You cannot use any of the Keywords as identifiers in your java programs
print in your above program is not a Keyword, you can use print as a identifier
After using print as a identifier your code looks like this.
//Test1 is a class name identifier
public class Test1 {
    // add is identifier for a method
    public static int add(int a, int b) {
    return a + b;
}

public static void main(String[] args) {
    int c; // c is identifier for a variable
    int a = 5;
    c = add(a, 10);
    if (c > 10)
        print("c = " + -c); // c is a String
    else
        print(c); // c is a int
    print("Hello World"); // Hello World is a String
}

/**
 * Method Overriding
 */
private static void print(int c) {
    System.out.println("In Integer Print Method "+c);
}

private static void print(String string) {
    System.out.println("In String Print Method "+string);
}

}

Also Refer :

Check Legal Identifiers in java @Peter Lawrey
List of Keywords and Reserved Words in java


Q:

How to retrieve records using select statement in while loop in SQL Server?

I have a 2 tables called Product and ProductDetails.
My criteria are quite difficult. I don't know how to make it.
So again move ProductDetails record to temp table, now balance is 15-12 = 3, now check with 3rd transferred quantity 10,  now 3 < 10 is true. now store this record also to temp table
Can you give any idea to solve this?

A:

If I understand correctly, you want the most recent dates whose cumulative quantity in productdetails meets or exceeds the quantity i product.  That is a cumulative sum and join:
select pd.*
from (select pd.*,
             sum(Quantity) over (partition by ProductID       order by DateTransferred desc) as running_quantity
      from productdetails pd
     ) pd join
     product p
     on p.productid = pd.productid and
        p.quantity >= (pd.runningquantity - pd.quantity);


Q:

Android room inserting with a query

I know inserting data into SQlite room library can be done through @Insert annotation, but I (out of curiosity) tried inserting values through SQL statement but Android studio showed me error stating column names can't be resolved. Is it a way of forcing developer to use @Insert annotation or if I am doing something wrong here? Thanks!
Please review following screenshot -

A:

If you omit the column list that is being highlighted and thus provide values for all columns e.g. :-
@Query("INSERT INTO TestTable VALUES(null,:a,:b)")
List<TestTable> getall(String a, String b, String columna, String columnb);

Android Studio doesn't complain but then you get a compiler error of :-
error: INSERT query type is not supported yet. You can use:SELECT, DELETE, UPDATE

So perhaps better sooner than later.


Q:

How do I share raw data used for ggplot2 graphs?

I am in the strange position of being responsible for data visualization, but there is a good chance that our client will want to change some or all of the graphs I create after they are delivered. Is there an R package (or technique) which can export raw data used to make ggplot2 graphs as .csv files along with the images as they are created?
For example, in a bar chart, I take a survey response, which is a string, and turn it into a factor variable, using
    ggplot(subset(data.df, !is.na(xvar)), aes(factor(xvar))

in order to plot it. I can go through the extra step of selecting the subset of my data again and writing a little .csv file with just the IDs and that variable, but it will be a string again. Help me! I don't want to have to do all this in Excel.

A:

I found it out; it's very simple.
For example, if your graph is p, then simply type p$data to output the data frame that was used to in its creation. I'll report back if I find a way to just output the data that's represented in the graph (as opposed to the entire data frame).


Q:

In Lie groups, why is left translation a diffeomorphism?

The map $G \times G \rightarrow G$ defined as $(x,y) \mapsto xy$ is differentiable. The left translation is $L_x(y) = xy$. To show that it is a diffeomorphism, we need it to be a bijection, that is both differentiable and has a differentiable inverse.
It is injective because if $xy_1 = xy_2$ then $y_1=y_2$.
It is surjective because for some arbitrary element $z \in G$ we can multiply on the left by $x^{-1}$ to get $x^{-1}z=y$. Then $L_x(y)=z$, meaning that $z\in \operatorname{im}(L_x)$.
But why is $L_x$ differentiable, and why is its inverse?

A:

Proposition. Let $G$ be a Lie group, and let $a\in G$. Then the map $L_a\colon G \to G$ with $L_a(x)=ax$ is a diffeomorphism.

Proof. We have already shown that $L_a$ is bijective. (A quicker way to see it might be to notice that $L_{a^{-1}}$ is the inverse of $L_a$.) Left to show is that $L_a$ and $L_a^{-1}$ are both smooth.
To show that $L_a$ is smooth, notice that $L_a=\mu\circ \iota_a$, where $\mu\colon G\times G\to G$ is defined by $\mu(x,y)=xy$, and $\iota_a\colon G\to G\times G$ is defined by $\iota_a(x)=(a,x)$. It follows from the definition of a Lie group that $\mu$ is smooth, and it's easy to show (how?) that $\iota_a$ is also smooth. The desired result now follows directly from the fact that the composition of two smooth maps is smooth itself.
The smoothness of $L_a^{-1}=L_{a^{-1}}$ follows by replacing $a$ by $a^{-1}$ in the previous paragraph.


Q:

Sending '__autoreleasing .....'to parameter of incompatible type

I have a block;
typedef void (^SIResponseHandler) (id obj, NSString *error);

and a method:
+ (void)uploadPhoto:(UIImage *)photo
toPathForComponents:(NSArray *)components
  completionHandler:(SIResponseHandler)responseHandler;

and another method which calls the above method:
+ (void)updateProfilePhoto:(UIImage *)photo handler:(SIResponseHandler *)handler {

    NSArray *components = @[@"users", sharedInstance.username, @"profile", @"photo", @"upload"];
    [SIRequest uploadPhoto:photo
       toPathForComponents:components
           progressHandler:nil
         completionHandler:handler];
}

In the last line, I get this error:
Sending '__autoreleasing SIResponseHandler *' (aka 'void (^__autoreleasing *)(__strong id, NSString *__strong)') to parameter of incompatible type 'SIResponseHandler' (aka 'void (^)(__strong id, NSString *__strong)')

I have no idea what this means. Can someone please explain what's going on ?
Thanks

A:

It appears that SIResponseHandler is a block type, and as such should not be suffixed as a pointer with * in an argument list, unless you know exactly what you are doing.


Q:

A git diff for what's new/modified/deleted from my current branch

I've been playing with git diff a little bit and I can't seem to find a way to compare two branches for new/modified/deleted files coming only from my branch.
Let's says we got master and dev, which is the branch I'm working on. I would like to git diff them but only get what I modified in dev compared to master.

A:

Perhaps this is what you're looking for:
git diff --name-status master dev

See git help diff for a full explanation of all the possible flags at the beginning of each line, but the most frequent would be (A)dded, (D)eleted and (M)odified...
Edit: Actually, if you want to get only the changes made on dev, then the above command will work, but you don't want to compare dev to the current head of master, but to the place where dev diverged from master, which is generally the same as git merge-base master dev. So the above command would be changed to:
git diff --name-status $(git merge-base master dev) dev


Q:

Can one find a Jordan curve which has exactly one inscribed rectangle?

In On the number of inscribed squares of a simple closed curve in the plane it is shown that

Theorem: For every positive integer $n$ there is a simple closed curve in the
  plane (which can be taken infinitely differentiable and convex) which has exactly $n$ inscribed squares.

this is my question:

Can one find a Jordan curve which has exactly one inscribed rectangle? More generally, what is the result if we use "rectangle" instead of "square" in the foregoing theorem?

A:

As Wojowu writes in the comments, Vaughan's argument (which is a paragraph long and can be read here on page 71) shows that there ought to be infinitely many rectangles inscribed in any Jordan curve. (The rectangles come from the double points of a real projective plane in 3-space, and I think — though can't remember the reference — that the preimage of the double set has a component which is nontrivial in first homology, which would imply it's infinite.)
You could fix a side length ratio in advance, and then ask whether there are Jordan curves with exactly one inscribed rectangle with that side length ratio. Probably no one has asked/answered this. Generically there are an even number of rectangles (with fixed side length ratio bigger than 1) inscribed in any Jordan curve, as opposed to an odd number of squares, so you'd have to make the pair of rectangles coincide.
EDIT: The preimage of the double set of a cone over the standard Möbius strip in $\mathbb{R}^3$ — take the standard strip near the unit circle in the $xy$-plane and the cone point at e.g. the origin — is a pair of open arcs whose closure is a generator of $H_1$. And this is roughly the picture corresponding to the projective plane you get from considering Vaughan's idea applied to an ellipse. So my recollection was wrong, but was nearly right for that example if you consider the closure of the preimage of the double set. But after being wrong once, I'm even less sure than I was before that I said something near the truth.
EDIT 2: It's true for the closure of the double set for generic maps. It's a special case of Theorem 2 in Double decker sets of generic surfaces in 3-space as homology classes; see the paper for the precise meaning of generic in this context.


Q:

Failed to dump data from a file with extension. Db

I receive the following error dump the data of a file called instalacionesdep.db. The funny thing is that everything is loaded correctly, but in the logcat I get the following error.
12-11 13:05:54.284: E/SqliteDatabaseCpp(17232): sqlite3_open_v2("data/data/com.mipaquete.instalacionesdep/databases/instalacionesdep.db", &handle, 1, NULL) failed
12-11 13:05:54.354: E/SQLiteDatabase(17232): Failed to open the database. closing it.
12-11 13:05:54.354: E/SQLiteDatabase(17232): android.database.sqlite.SQLiteCantOpenDatabaseException: unable to open database file
12-11 13:05:54.354: E/SQLiteDatabase(17232):   at android.database.sqlite.SQLiteDatabase.dbopen(Native Method)
12-11 13:05:54.354: E/SQLiteDatabase(17232):     at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:1013)
12-11 13:05:54.354: E/SQLiteDatabase(17232):    at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:986)
12-11 13:05:54.354: E/SQLiteDatabase(17232):     at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:962)
12-11 13:05:54.354: E/SQLiteDatabase(17232):     at com.mipaquete.instalacionesdep.db.DataBaseHelper.checkDataBase(DataBaseHelper.java:99)
12-11 13:05:54.354: E/SQLiteDatabase(17232):   at com.mipaquete.instalacionesdep.db.DataBaseHelper.createDataBase(DataBaseHelper.java:72)
12-11 13:05:54.354: E/SQLiteDatabase(17232):  at com.mipaquete.instalacionesdep.db.TodasLasInstalacionesActivity.onClick(TodasLasInstalacionesActivity.java:71)
12-11 13:05:54.354: E/SQLiteDatabase(17232):   at android.view.View.performClick(View.java:3511)
12-11 13:05:54.354: E/SQLiteDatabase(17232):   at android.view.View$PerformClick.run(View.java:14105)
12-11 13:05:54.354: E/SQLiteDatabase(17232):      at android.os.Handler.handleCallback(Handler.java:605)
12-11 13:05:54.354: E/SQLiteDatabase(17232):      at android.os.Handler.dispatchMessage(Handler.java:92)
12-11 13:05:54.354: E/SQLiteDatabase(17232):      at android.os.Looper.loop(Looper.java:137)
12-11 13:05:54.354: E/SQLiteDatabase(17232):  at android.app.ActivityThread.main(ActivityThread.java:4424)
12-11 13:05:54.354: E/SQLiteDatabase(17232):        at java.lang.reflect.Method.invokeNative(Native Method)
12-11 13:05:54.354: E/SQLiteDatabase(17232):     at java.lang.reflect.Method.invoke(Method.java:511)
12-11 13:05:54.354: E/SQLiteDatabase(17232):         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
12-11 13:05:54.354: E/SQLiteDatabase(17232):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
12-11 13:05:54.354: E/SQLiteDatabase(17232):     at dalvik.system.NativeStart.main(Native Method)

I think closing myDbhelper sometime, but I think that I do all the steps and can not find the fault. This is the summary of my class that extends SQLiteOpenHelper DataBAseHelper code.
public class DataBaseHelper extends SQLiteOpenHelper {

    //Variables ausiliares
    private static String DB_PATH="data/data/com.mipaquete.instalacionesdep/databases/";
    private static final String DB_NAME="instalacionesdep.db";
    //private static final int DATABASE_VERSION =1;

    private SQLiteDatabase myDatabase;
    private final Context myContext;

    public DataBaseHelper(Context context) {
        super(context, DB_NAME, null, 1);
        // TODO Auto-generated constructor stub
        this.myContext = context;
    }

    public void createDataBase() throws IOException{
        //para chequear que existe la BD
        boolean dbExist = checkDataBase();

        SQLiteDatabase db_read = null;

        if(dbExist){

        }else{
            //agarramos la BD para leerla y despues la cerramos.
            db_read = this.getReadableDatabase();
            db_read.close();

            try {
                copyDataBase();
            } catch (Exception e) {
                // TODO: handle exception
                throw new Error("Error copying database (createDataBase)");
            }
        }

    }

    public boolean checkDataBase(){
        SQLiteDatabase checkDB = null;
        SQLiteDatabase db_read = null;

        try{
            String myPath = DB_PATH+DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
        }catch (SQLException e) {
            // TODO: handle exception
            File dbFile = new File(DB_PATH+DB_NAME);
            return dbFile.exists();
        }
        if(checkDB != null){
            checkDB.close();

        }

        //regresa un true o un false dependidendo si se cumple la condicion. Los : sustituyen al else
        return checkDB != null ? true : false;
    }

    //vamos a volcar
    public void copyDataBase() throws IOException{

        InputStream myInput = myContext.getAssets().open(DB_NAME);
        String outFileName = DB_PATH+DB_NAME;

        OutputStream myOutPut = new FileOutputStream(outFileName);

        Log.e("LocAndroid", "ESTOY EN copyDataBase");

        //Para trasnferir el fichero en tamaños de 1024 bytes
        byte[] buffer = new byte[1024];
        int lenght;

        //while para que nos mande el archivo.
        while((lenght = myInput.read(buffer))!=-1){
            if(lenght > 0){
                myOutPut.write(buffer, 0, lenght);
            //con esto hemos copiado la base de datos. Basicamente, El volcado del archivo

            }

        }
        myOutPut.flush();
        myOutPut.close();
        myInput.close();
    }

    //Para abrir la base de datos
    public void openDataBase() throws SQLException{

        //myDatabase = this.getWritableDatabase();
        String myPath = DB_PATH+DB_NAME;
        myDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
    }

    //Para cerrar la base de datos
    public synchronized void close(){

        if(myDatabase != null){
            myDatabase.close();
        }
        super.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }

}

thank you!

A:

The error was checkdatabase (). Specifically in the lines:
String myPath = DB_PATH+DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

The first run always give mistake. Because the database does not exist. checkdatabase must contain only the this code:
File dbFile = new File(DB_PATH+DB_NAME); return dbFile.exists();


Q:

Docker container with SWI-Prolog terminated with fatal error

Im developing a Spring Boot Web Application, using SWI-Prolog's JPL interface to call Prolog from Java. In development mode everything runs OK.
When I deploy it to Docker the first call on JPL through API, runs fine. When I try to call JPL again, JVM crashes.
I use LD_PRELOAD to point to libswipl.so
SWI_HOME_DIR is set also.
LD_LIBRARY_PATH is set to point to libjvm.so
My Controller function:
@PostMapping("/rules/testAPI/")
@Timed
public List<String> insertRule() {
    String use_module_http = "use_module(library(http/http_open)).";
    JPL.init();

    Query q1 = new Query(use_module_http);
    if (!q1.hasNext()) {
        System.out.println("Failed to load HTTP Module");
    } else {
        System.out.println("Succeeded to load HTTP Module");
    }

    return null;
}

Console output
1st Call
Succeeded to load HTTP Module

2nd Call
#
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00007f31705294b2, pid=16, tid=0x00007f30d2eee700
#
# JRE version: OpenJDK Runtime Environment (8.0_191-b12) (build 1.8.0_191-8u191-b12-2ubuntu0.18.04.1-b12)
# Java VM: OpenJDK 64-Bit Server VM (25.191-b12 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# C  [libswipl.so+0xb34b2]  PL_thread_attach_engine+0xe2
#
# Core dump written. Default location: //core or core.16
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#

I uploaded the error log file in pastebin. click here
Has anyone faced the same problem? Is there a solution about this?
Note that, I also checked it also with oracle-java-8 but the same error occurs.
UPDATE:
@CapelliC answer didn't work.

A:

Finally it was a bug of JPL package. After contacting SWI-Prolog developers, they patched a fix to the SWI-Prolog Git and now the error is gone!
Right configuration, so that Docker container be able to understand JPL is found in this link: Github : env.sh


Q:

Angular 2: "Global" lifecycle hooks?

TL;DR
We are building an app with Angular 2 and would like to register a "global" ngOnInit and ngOnDestroy function. With "global" I mean that the function is executed for every component, without needing to be explicitly implemented for every component. Is this possible?
Detailed
Some (but not all) of our components need to register something in a global service once they are loaded (e.g. ngOnInit) and unregister it again, once they are unloaded (e.g. ngOnDestroy). Here are two approaches I can think of:

Implement this logic in every component which needs to do so (in ngOnInit and ngOnDestroy).
Implement this logic in a base class which calls abstract methods implemented by the sub classes which specify, what needs to be registered/unregistered.

Both approaches aren't really satisfying:

In the first I need to implement the whole logic over and over again. Yeah, I know, I could put the "boiler plate"-code in a helper class or something. But it seems to be slightly implicit, "hidden" in the regular Angular lifecycle. Having a speaking name (e.g. interface/base class) seems more explicit.
In the second all classes need to extend the same, common base class. But what if they should also extend some other base class (multiple inheritance)?

That's why i came up with following idea:
Why not replace the above mentioned abstract class with an interface that can be implemented by all the required components. I would then register a global function which is executed on every ngOnInit and ngOnDestroy of all the components (if possible - e.g. in an module, routing, etc.?). In the function I would check if the component implements the interface and if it does, then call the appropriate function to get the type specific stuff to be registered.
My questions

Can Angular 2 do this? I.e. can a "global lifecycle hook" (or something like that) be registered?
Or is this a totally wrong approach anyway?
Any other/better ideas?

A:

Forcing the behaviour for the entire app wouldn't be a good idea, this affects third-party components as well for starters.
Boilerplate code can be moved into concrete base class. There are solutions for JS/TS multiple inheritance, e.g. @mixin, see also TypeScript guide.
Since base class methods are fixed, class mixin can be expressed as a simplified decorator:
class CustomLifecycle implements OnInit, OnDestroy  {
  constructor(
    public originalNgOnInit: Function,
    public originalNgOnDestroy: Function
  ) {}

  ngOnInit() {
    ...
    if (typeof this.originalNgOnInit === 'function') {
      this.originalNgOnInit();
    }
  }

  ngOnDestroy() {
    ...
    if (typeof this.originalNgOnDestroy === 'function') {
      this.originalNgOnDestroy ();
    }
  }
}

function Lifecycled() {
  return function (target: Function) {
    const customLifecycle = new CustomLifecycle(
      target.prototype.ngOnInit,
      target.prototype.ngOnDestroy
    );

    target.prototype.ngOnInit = customLifecycle.ngOnInit;
    target.prototype.ngOnDestroy = customLifecycle.ngOnDestroy;
  }
}

And it can be used like
@Component({ ... })
@Lifecycled()
class SomeComponent { .... }

The implementation is limited to ngOnInit, etc. prototype methods, arrow members require a constructor to be patched.


Q:

Play! Framework + Java

when I try to create a new play app and then launch my play application (without modifying any code) locally I get the following error:
http://cl.ly/image/1x311s1w3S2w
which says I have a continuation error. However I cannot fix it as I have other older play projects which I can still launch and they still work perfectly. My java version in eclipse 1.7 and my play version is 1.2.5.
I realise now that my JVM is 1.8, will this make a difference? Although then why do they older apps still work, when they are also written using 1.7.
Any help at all would be great, thanks!

A:

I don't think  the JVM version would be the issue. The issue is with the loading of your class ContinuationEnhancer. Try replacing the jar of that class.


Q:

JVM IntelliJ IDEA permission-level

The problem is when I try to create a directory by mkdir() it returns false. Looks like the reason is that JVM doesn't have enough permission level. How can I fix it? How to increase this level?
Thank You!
UPD!!! I solved the problem.

A:

I've found an answer. But before I tried smth like that:
File fname = new File(currDir + args[i]);//currDir is the path where to create a folder
//and the args[i] is folder name
    if (!fname.exists())
        fname.mkdir();

But here's a mistake so this is the correct code:
File fname = new File(currDir + "/" + args[i]);
    if (!fname.exists())
        fname.mkdir();

That's it =)


Q:

Esper consuming symbiote

I'm looking for the title and author of a story I read years ago. In short: a crack pair of investigators arrive on a planet. One is a high level esper.
They go about their business but notice some of the native populace are "afflicted" with a bright red growth in varying degrees. Some have only a tiny spot, on others it covers large areas of their bodies. The natives consider the tumor-like growths a "blessing" or status symbol.
I don't recall specifics but the pair discovers a cavern filled with the red tumors. The next day the esper has disappears. The remaining off-worlder searches for her and finally discovers the tumors are related to esper ability, and how much you are "afflicted" is directly proportional to your level of ability. In short his partner melded with or was consumed by the tumors, becoming one with the mass in the cavern.

A:

You are are remembering a story by the little known writer George R. R. Martin!
It's called A Song For Lya.
Wikipedia just says " It deals with two telepaths named Robb and Lyanna who visit a planet to find out why the inhabitants worship a mold-like organism and ultimately choose to be absorbed by it" but you are remembering correctly, the absorb-ees start out with little red growths (kind of like the Futurama brain slugs) and eventually merge into a giant red mass / hive-mind.


Q:

Simple bound for generalized geometric series

Let $b \in (0,1)$, $m\in \mathbb{N}$ and $a>0$. I want to bound
$$\sum_{k=m+1}^\infty b^{k^a} \leq c \; b^{m^a}, $$
where $c>0$ is independent from $m$.
Is there a simple way of proving this inequality with $c$ not beeing too large?
Edit: $c$ can only be independent from $m$ if $a>1$. Otherwise it has to grow with $m$ at least linearly, maybe even less...
Thanks!

A:

For $a\ge 1$, the quantity $(m+k+1)^a-m^a$ is increasing w.r.to $m\ge0$ (because  $x\mapsto x^a$ is convex). So for $0<b<1$, the term $b^{(m+k+1)^a-m^a} $ is decreasing w.r.to $m\ge0$, and so is $\sum_{k\ge0}b^{(m+k+1)^a-m^a}=b^{-m^a}  \sum_{k> m}b^{k^a}$. That is, we have
the required bound with $$c=c(b):=  \sum_{k>0} b^{k^a} , $$ which is optimal as it gives an equality for $m=0$ .
For $0<a<1$ the answer is already answered in negative by Christian Remling.
(Note that if $0<a<1$, the above inequality are to be inverted, by concavity of $x\mapsto x^a$,  and  $ b^{-m^a}  \sum_{k> m}b^{k^a}$ is increasing; moreover $(m+k+1)^a-m^a\le am^{a-1}
(k+1)$ so $$b^{-m^a}  \sum_{k> m}b^{k^a}=\sum_{k\ge0}b^{(m+k+1)^a-m^a}\ge \sum_{k\ge0}b^{am^{a-1}
(k+1)}=\frac{1}{1-b^{ {a}{m^{a-1}}} }-1,$$
that diverges  like $m^{1-a}$   as $m\to+\infty$.)


Q:

Stanford Parser: how to extract dependencies?

My work consists in finding a query (can be noun+verb) in a sentence, then extract the object.
exemple: "coding is sometimes a tough work." My query would be: "coding is".
the typed dependencies i get are:
nsubj(work-6, coding-1)
cop(work-6, is-2)
advmod(work-6, sometimes-3)
det(work-6, a-4)
amod(work-6, tough-5)

My program should extract the nsubj dependency, identify "coding" as the query and save "work".
May be this seems simple, but until now, i didn't find a method able to extract a specific typed dependency, and I really need this to finish my work.
Any help is welcome,

A:

You can find dependencies by following code:
Tree tree = sentence.get(TreeAnnotation.class);
// Get dependency tree
TreebankLanguagePack tlp = new PennTreebankLanguagePack();
GrammaticalStructureFactory gsf = tlp.grammaticalStructureFactory();
GrammaticalStructure gs = gsf.newGrammaticalStructure(tree);
Collection<TypedDependency> td = gs.typedDependenciesCollapsed();
System.out.println(td);

Object[] list = td.toArray();
System.out.println(list.length);
TypedDependency typedDependency;
for (Object object : list) {
typedDependency = (TypedDependency) object;
System.out.println("Depdency Name"typedDependency.dep().nodeString()+ " :: "+ "Node"+typedDependency.reln());
if (typedDependency.reln().getShortName().equals("something")) {
   //your code
}


Q:

Why does this code works well? It changes the Constant storage area string;

this is  a simple linux kernel module code to reverse a string which should Oops after insmod,but it works well,why?
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
static char *words = "words";
static int __init words_init(void)
{
  printk(KERN_INFO "debug info\n");
  int  len = strlen(words);
  int  k;
  for ( k = 0; k < len/2; k++ )
  {
     printk("the value of k %d\n",k);
     char  a = words[k];
     words[k]= words[len-1-k];
     words[len-1-k]=a;
 }
 printk(KERN_INFO "words is %s\n", words);
 return 0;
}
static void __exit words_exit(void)
{
  printk(KERN_INFO "words exit.\n");
}
module_init(words_init);
module_exit(words_exit);
module_param(words, charp, S_IRUGO);
MODULE_LICENSE("GPL");

A:

Haha!,I get the answer from the linux kernel source code by myself;When you use the insmod,it will call the  init_moudle,load_module,strndup_usr then memdup_usr function;the memdup_usr function will use kmalloc_track_caller to alloc memery from slab and then use the copy_from_usr to copy the module paragram into kernel;this  mean the linux kernel module paragram store in heap,not in the  constant storage area!! So we can change it's content!


Q:

How do I power down my Pi if I'm ssh'ed in?

I want to power down my Pi, but I don't have console access... I'm just logged in via ssh.
So I issue sudo shutdown now and it drops my connection almost instantly.  How long should I wait to unplug the device?  Are there any clues I can watch for with the on-board lights?

A:

You can wait for all the LED's to go off. Only the red LED(power LED) stays on. That's when the Pi has shutdown

A:

The Raspberry Pi does not allow you to shut it down completely, unless you unplug the power. The best way to turn it off is by running sudo shutdown -h now and waiting until everything has been unloaded properly and then unplugging the device.
If you have no display I would recommend that you run the command and then wait a few minutes until you unplug the device.


Q:

codeigniter form validation set_value works only for the fields which have rules

Suppose if I have two fields in my form viz first_name and last_name
I have set the validation rule only for first_name.
set_value should work for both the fields regardless of rule ? right ?
For me it works only for the fields which have rules with them !!!

A:

set_value only works against the items you have chosen to validate using the form_validation class.
Easiest way is to pretend you are validating by adding this to your form validation config
        array(
            'field'   => 'address1',
            'label'   => '',
            'rules'   => ''
        ),
There is a hack someone has done to the CI library but I haven't been able to find the documentation on that today...Or use this modification instead:
http://codeigniter.com/forums/viewthread/159535/#775628

A:

There is simple solution of this issue. pass $_POST['your_field_name'] variable as a second parameter for fields those don't have any validation rule.
echo set_value('o_title',$_POST['o_title']);

It worked for me.

A:

if you set the validation rule with just the first parameter it seems to work fine.
$this->form_validation->set_rules('city');

etc.
so there isn't a validation rule per se but it repopulates the field for you.


Q:

Преобразование char в const char*

const char * str;
int kolich = help.size();
double znachen(0.0);
for(size_t i(0); i <= help.size(); i++)
{
    str = help[i];
    znachen += atof(str) * pow(10.0, kolich);
    kolich--;
}
return znachen;

Эта функция принимает вектор типа char и возвращает число. В каждой ячейке вектора хранится одна цифра. Для преобразования из char в double использую функцию atof. Но она в качестве аргумента берет const char*. И тут появляется ошибка и вопрос. Как мой элемент типа char сделать const char*?

A:

Если у вас std::vector<char>, то надо взять адрес у элемента.
str = &(help[i]);

Этого недостаточно для функции atof, т.к. она на вход получает 0-детерминированную строку.
В вашем случае, если никак нельзя отказаться от std::vector<char> и очень хочется преобразовать именно char в число, можно применить не самый оптимальный трюк - преобразовать char в std::string
for(size_t i = 0, l = help.size(); i < l; ++i)
{
    std::string str(1, help[i]);
    znachen += atof(str.c_str()) * pow(10.0, kolich);
    kolich--;
}


Q:

How to include new lines for code snippets inside comments?

I want to write short code in comment like:
function ngWrap($scope, fn) {
    return function() {
        var args = [].slice.call(arguments);
        if (!$scope.$$phase) {
            fn.apply(null, args);
        } else {
            return $scope.$apply(function() {
                fn.apply(null, args);
            });
        }
    };
}

But when I put code in backticks the newlines are removed when rendered. How can I insert code into comment, like on this answer?

A:

Comments are meant to be ... comments. That is why they have a cap on maximum length and a minimal support for text formatting.
Pasting that code snippet in your answer seems to be okay.


Q:

Identify admin permissions required by an Azure AD app registration

How can I find out what admin permissions are blocking the user from signing in to an Azure AD app?
I am setting up an App Registration in the Azure AD portal to be used with my Service Fabric cluster. The app registration does basic auth and only has one Required Permission configured: Sign in and read user profile (which does NOT require admin permission).
My tenant has the "Users can consent to apps accessing company data on their behalf" setting to "Yes", so it's not that.
Also, the /authorize request doesn't have any resource parameter, so it's implicitly asking for the permission I configured: Azure AD's Sign in and read user profile.
However when an non-admin user attempts to sign it, I still get the error:

AADSTS90094: The grant requires admin permission

A:

I reproduced the scenario and this is what I observed. Found a workaround, hope it helps.
First I created a Service Fabric (SF) cluster secured with AAD authentication using the steps described here, using an AAD tenant where I am not a global admin.
Then I tried to login to Service Fabric Explorer (SFX) and I got this error:

AADSTS50105: The signed in user is not assigned to a role for the
  application 'f8c79129-deb7-4a21-a6e0-ec29e88298ef'

This is expected, because the user must be assigned to a role (Admin or ReadOnly) in the SF application that represents the cluster. So I went to AAD > Enterprise Applications > found my cluster app and under Users and Groups I added myself to the Admin role. Notice that the fact that a regular user can administer the roles of an application that the user owns is something new, it's available since a month or so -- before that, a regular user couldn't administer the roles of an application.
Then I tried to login again to SFX and I got a different error:

AADSTS65005: Invalid resource. The client has requested access to a
  resource which is not listed in the requested permissions in the
  client's application registration. Client app ID:
  f8c79129-deb7-4a21-a6e0-ec29e88298ef. Resource value from request: .
  Resource app ID: 00000002-0000-0000-c000-000000000000. List of valid
  resources from app registration: .

00000002-0000-0000-c000-000000000000 is Windows Azure Active Directory. For some reason SetupApplications.ps1 doesn't assign the Sign in and Read User Profile permission to the SF cluster application. So I edited the application and I assigned that permission, just like you showed in your print screen. Notice that SetupApplications.ps1 has a parameter AddResourceAccess (not mentioned in the doc) that adds that permission, not sure why it doesn't add it by default. Perhaps it isn't needed when you run SetupApplications.ps1 as a global admin, and the scripts/doc assumes that you are a global admin.
Then I tried to login to SFX again and I got the same error that you observed:

AADSTS90094: The grant requires admin permission.

So I checked the SF application under AAD > Enterprise Applications > found the SF cluster app > Properties. User assignment required is configured "Yes". I changed it to "No" and tried to login to SFX. This time it worked OK, I could consent and access the SFX console. Then I changed User assignment required again to "Yes".
One can argue if the SF app really needs User assignment required > Yes because anyway if a user is not assigned to the Admin or ReadOnly role, SFX will try to fallback to client certificate authentication.
In either way, the AAD behavior is confusing. At least, the error should be more descriptive and point to the User assignment configuration. Perhaps the current behavior has to do with what I mentioned before, that regular users can now administer roles. Perhaps the behavior is being improved.


Q:

writing an xml file that contains a euro symbol (€) in Python using xml.etree

I am trying to use xml.etree to read and write xml files containing a € symbol.
My simplified code looks like this:
optionsdirectory = os.getcwd()
optionsfile = os.path.join(optionsdirectory, "conf")
optionstree = ET.parse(optionsfile)
options = optionstree.getroot()
for option in options:
    if option.tag == "currency":
        option.text = "€"
optionstree.write(optionsfile, encoding="UTF-8")

I get the following error when it is run:
File "C:\curr.py", line 8
    optionstree.write(optionsfile, encoding="UTF-8")
File "C:\Python27\lib\xml\etree\ElementTree.py", line 815, in write
    serialize(write, self._root, encoding, qnames, namespaces)
File "C:\Python27\lib\xml\etree\ElementTree.py", line 934, in _serialize_xml
    _serialize_xml(write, e, encoding, qnames, None)
File "C:\Python27\lib\xml\etree\ElementTree.py", line 932, in _serialize_xml
    write(_escape_cdata(text, encoding))
File "C:\Python27\lib\xml\etree\ElementTree.py", line 1068, in _escape_cdata
    return text.encode(encoding, "xmlcharrefreplace")
UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 2114: ordinal not in range(128)

Is there a way to write a € symbol to an xml file using xml.etree?

A:

You need to use a unicode literal. It'll be easier to use a unicode escape instead of the character:
option.text = u"\u20AC"  # Euro sign

What happens when you do not use a unicode literal but a byte (string) literal instead, is that Python tries to decode the value to a unicode literal using the default encoding, which is ASCII. This results in the UnicodeDecodeError you saw.
If you really do want to use the unescaped character, make sure you specify the encoding of your source file at the top:
# -*- coding: utf-8 -*-

and make sure your editor uses UTF-8 to save the file. You'd still have to use a unicode literal though:
option.text = u"€"


Q:

How to inspect a Corona CAR file?

A customer has supplied us with a corona CAR file. What command line tools (if any) are available to inspect its contents? Its a 'Corona ARchive' containing other files clearly, however it's neither in ZIP or a TAR format.

A:

A .CAR file is not meant to be unpacked for inspection.  Its a proprietary format. I'm unware of any command line tools to unpack it.  Why does your customer need this?


Q:

Why here string literal are not interned?

Here is my main class
public class MainClass {
 public static void main(String args[])  {
   String str1 = "testString";
        String str2 = "testString" + 1; //line1
        //above  literal value(i.e str2 = "testString1") is interned and stored in permamnent generation space
        //now when whenever i create "testString1" down the line in this program, it should refer from same location
        //but it does not seem true
        TestThread tt= new TestThread(str1, str2);
        tt.start();

        }

}

Here is my thread class
package Test;

public class TestThread extends Thread {
    String str2;

public TestThread( String str3, String str4) {
        this.str3 = str3 + 1; //line2
        System.out.println("value inside Thread is "+this.str3);
        System.out.println("value inside Thread is "+str4);
        if(str3 == str4){
            System.out.println("Yes they are equal");
        }else{
        System.out.println("They are not equal");
        }

        //line 3

    @Override
    public void run(){
       // some processing
        }
}

At line 3, "They are not equal" is printed. But why ? line 2 should refer same string as at line 1 as i am using string literal which
  are interned and stored in permgen space.
Update :- Is there a way i can force compiler to use string literal instead of optimizing the code to use new String ?

A:

this.str3 = str3 + 1; //line2

You are using concatenation at runtime which always creates a new String which is not interned by default. You can use  intern() method on this and then try to compare.
String str2 = "testString" + 1; //line1

This is a compile time constant expression and on successful compilation will be converted to
String str2 = "testString1";

which is a String literal and will be interned. Now in your run method you are creating a new String as I explained previously. Hence both are pointing to different String instances and hence == will give you false.


Q:

Accessing Less variables names inside a list

OK, let's say that I have a Less file like so:
// Turquoise
@turquoise: #1ABC9C;
@turquoise-2: #16A085;

// Greens
@green: #2ECC71;
@green-2: #27AE60;

// Blues
@blue: #3498DB;
@blue-2: #2980B9;

// Navy Blues
@navy: #34495E;
@navy-2: #2C3E50;

// Purples
@purple: #9B59B6;
@purple-2: #8E44AD;

// Yellows
@yellow: #F1C40F;

// Oranges
@orange: #F39C12;
@orange-2: #E67E22;
@orange-3: #D35400;

// Reds
@red: #E74C3C;
@red-2: #C0392B;

// Greys
@grey: #ECF0F1;
@grey-2: #BDC3C7;
@grey-3: #95A5A6;
@grey-4: #7F8C8D;

@colour-scheme:
    @red, @red-2,
    @orange, @orange-2, @orange-3,
    @yellow,
    @green, @green-2,
    @turquoise, @turquoise-2,
    @blue, @blue-2,
    @purple, @purple-2,
    @navy, @navy-2,
    @grey, @grey-2, @grey-3, @grey-4
;

And I wanted to make a mixin that went like so:
.createBG( @colour-array: @colour-scheme, @n: length( @colour-scheme ), @i: 0 ){
    &.<[COLOUR-ARRAY[@i] VARIABLE NAME]>{
        background-color: extract( @colour-array, @i );
    }
    .createBG( @colour-array, ( @i + 1 ) )
}

How would I achieve to replace <[COLOUR-ARRAY[@i] VARIABLE NAME]> with valid Less code that would give me the variable name of the current index of the list/array.
What would be the surefire, and best practice, way of implementing this?

A:

You can do this using the extract function itself by just setting the color variable names as value for the @color-scheme variable instead of giving it the variable itself. Within the mixin, @@ can be used to resolve the variable's name to its actual color value.
@colour-scheme:
  red, red-2, orange, orange-2, orange-3, yellow, green, green-2, turquoise, turquoise-2,
  blue, blue-2, purple, purple-2, navy, navy-2, grey, grey-2, grey-3, grey-4;

.createBG(@colour-array: @colour-scheme, @n: length(@colour-scheme), @i: 1 ) when (@i <= @n){
  @color: extract(@colour-array, @i);
  &.@{color}{
    background-color: @@color;
  }
  .createBG( @colour-array, @n, @i + 1 )
}
.createBG();

Since you need the color names also (to be the class name), you'd definitely have to store the names in some variable and so there is not much reduction possible. But we could still use associative array. A sample for associative array is provided below.
@colour-scheme:
  red #E74C3C, red-2 #C0392B,
  orange #F39C12, orange-2 #E67E22, orange-3 #D35400,
  yellow #F1C40F,
  green #2ECC71, green-2 #27AE60,
  turquoise #1ABC9C, turquoise-2 #16A085,
  blue #3498DB, blue-2 #2980B9,
  purple #9B59B6, purple-2 #8E44AD,
  navy #34495E, navy-2 #2C3E50,
  grey #ECF0F1, grey-2 #BDC3C7, grey-3 #95A5A6, grey-4 #7F8C8D;

.createBG(@colour-array: @colour-scheme, @n: length(@colour-scheme), @i: 1 ) when (@i <= @n){
  @color-name-hex: extract(@colour-array, @i);
  @color-name: extract(@color-name-hex, 1);
  @color-hex: extract(@color-name-hex, 2);
  &.@{color-name}{
    background-color: @color-hex;
  }
  .createBG( @colour-array, @n, @i + 1 )
}
.createBG();

Note: Have a look at this bug in v2.6.1 and it could end up spoiling your loops. It will be fixed though.


Q:

DELETE with SELECT sub-query gets stuck

The following delete statement causing mysql to stuck:
DELETE FROM domains WHERE id IN (SELECT domain_id FROM domains_groups WHERE group_id = 9);
While this statement, which does the same, works:
DELETE FROM domains WHERE id IN (select id from (SELECT domain_id as id FROM domains_groups WHERE group_id = 9) a);
Can anyone explain why?

A:

The reason has to do with the optimization of SQL queries.  Your first version is evaluating the subquery for each row -- although this has been fixed in more recent versions of MySQL.  The second version is creating a temporary table, so this goes much faster.
I would recommend using exists or join:
DELETE d FROM domains d
    WHERE EXISTS (SELECT 1 FROM domains_groups dg WHERE dg.group_id = 9 AND dg.domain_id  = d.id);

Or:
DELETE d
    FROM domains d JOIN
         domaings_groups dg
         ON dg.group_id = 9 AND dg.domain_id  = d.id;

I would also recommend an index either domain_groups(domain_id, group_id) (for the above two versions) or domain_groups(group_id, domain_id) (for the in version).


Q:

Reference request: A book to explain the definition $\lim_{n \to \infty} \frac{f(t)-f(t_n)}{t-t_n}$ showing a function is continuous.

I have a function $f: I \to \mathbb{R}$ where I is an interval in $\mathbb{R}$.
I have two sequences $t$ and $t_n$.
I am told that if $$\lim_{n \to \infty} \frac{f(t)-f(t_n)}{t-t_n}$$  exists, then the function $f$ is continuous.
Is there a book which explains this definition?
In the books I have seen such as Walter Rudin "principles of mathematics", the differentiability of a function is only examined at a point rather than the whole function.
The context in which I am looking at it is that I am using that definition to prove that a certain function is not differentiable.

A:

I suppose that you don't have two sequences; rather, fixing $t$ in $I$, we take $t_n$ to be an arbitrary sequence converging to $t$ (and for technical reasons $t_n \neq t$ for all $n$). In this case, the existence of the given limit is equivalent to the existence of the derivative $f'$ at the point $t$. If the limit exists, then we see \begin{align*} \lim_{n\to\infty} \lvert f(t) - f(t_n) \rvert &= \lim_{n\to\infty} \lvert t -t_n \rvert \frac{\lvert f(t) - f(t_n) \rvert}{\lvert t - t_n \rvert}\\
&= \left( \lim_{n\to\infty} \lvert t -t_n \rvert\right) \left(\lim_{n\to \infty} \frac{\lvert f(t) - f(t_n) \rvert}{\lvert t - t_n \rvert}\right) = 0 \cdot \lvert f'(t) \rvert = 0.
\end{align*} Thus whenever $t_n \to t$, we have $f(t_n) \to f(t)$ which implies continuity of $f$ at $t$ by the sequential criterion theorem.
This is not a definition of continuity; indeed a function may be continuous and the given limit may fail to exist. However, existence of the limit implies the continuity of $f$.


Q:

Error when using the Domain Access module

I installed the Domain Access module and get the following error:

Domain access failed to load during phase: bootstrap include. Please check your settings.php file and site configuration.

How can I solve this?

A:

You can access the readme file here.
There is also a quickstart version here.
The main bit you will need is the following (taken from the quickstart version - line 24):

Add the following four lines of code to your settings.php file:

/**
    * Add the domain module setup routine.
    */
    include DRUPAL_ROOT . '/sites/all/modules/domain/settings.inc';

NOTE: You may need to alter the file path above based on your
       site configuration.  See INSTALL.txt for further help.
IMPORTANT: You must add these lines to settings.php after the
       $databases. Normally, you should add these lines to the end of the
       settings.php file.
NOTE: If you perform a Drupal core version upgrade, you must
       remove these lines from settings.php.  See UPGRADE.txt for details.


Q:

How to delete Content Type created through features

I was trying to use a project feature from openAid features based distribution.
So I copied all the features from that distribution and required contrib and custom modules in my drupal installation.
Then I enable the project feature from admin/structure/features which enables few other features like resources and partners.
Any how I was unable to make it work as per my requirement so I deleted all three folders including the features, contrib and custom modules.
but the issue is that it has created three content types Project, Partners and there is no option to delete them.
Please let me know if there is a way to delete those content types which were created through the features which I have already deleted.

A:

Open the content type (for example: article) for editing which should bring you to a URL:

admin/structure/types/manage/article

You can then append "/delete" into the URL like so:

admin/structure/types/manage/article/delete

Which should open a form that will let you delete the content type. I don't know if this lets you delete ones that are coming from an active features package, but it definitely does help you delete obsolete content types from inactive features packages. So be careful

FYI, if you do this for multiple content types, don't open all the delete forms in multiple tabs and try to be clever by deleting several types at once. Bad things will happen :-p Make a backup and delete one content type at a time.

A:

You may try the following code for getting the delete link (as we get delete link for the manually created content types) for the content types as created by the feature module:
<?php
/**
 * Implements hook_uninstall().
 */
function FEATURE_NAME_uninstall() {

  // List custom content types added by this feature.
  $custom_ctypes = array(
    'CONTENT_TYPE1',
    'CONTENT_TYPE2',
  );

  // Loop through each and unlock the content type.
  foreach ($custom_ctypes as $ctype) {
    db_query("UPDATE {node_type} SET `custom` = 1, `locked` = 0 WHERE `type` = :ctype", array(':ctype' => $ctype));
  }

  // Clean Drupal cache; this is necessary for the "Delete" link to appear
  // next to the content type created by the feature.
  drupal_flush_all_caches();
}
?>

After executing the above script, you will get the "delete" link as we get for the manually created content type and than you can delete the content type (created by feature module) from UI itself.

Another easy way to delete the content type: manually go to /admin/structure/types/manage/"CONTENT_TYPE_NAME"/delete it will delete it
Reference: https://drupal.org/node/1055460


Q:

Non HBase solution for storing Huge data and updating on real time

Hi i have developed an application where i have to store TB of data for the first time and then 20 GB monthly incremental like insert/update/delete in the form of xml that will be applied on top of this 5 TB of data .
And finally on request basis i have to generate full snapshot of all data and create 5K text files based on the logic so that respective data should be in the respective files .
I have done this project using HBase .
I have created 35 tables in the HBase having region from 10 to 500 .
I have my data in my HDFS and the using mapreduce i bulk load data into receptive Hbase tables .
After that i have SAX parser application written in java to parse all incoming xml incremental files and update HBase tables .The frequency of the xml files are approx 10 xml files per minutes and total of 2000 updates .
The incremental message are strictly in order .
Finally on request basis i run my last mapreduce application to scan all Hbase table and create 5K text files and deliver it to the client .
All 3 steps are working fine but when i went to deploy my application  on production server that is shared cluster ,the infrastructure team are not allowing us to run my application because i do full table scan on HBase .
I have used 94 node cluster and the biggest HBase table data that i have is approx 2 billions .All other tables has less than a millions of data .
Total time for mapreduce to scan and create text files  takes 2 hours.
Now i am looking for some other solution to implement this .
I can use HIVE because i have records level insert/update and delete that too in very precise manner.
I have also integrated HBase and HIVE table so that for incremental data HBase table will be used and for full table scan HIVE will be used .
But as HIVE uses Hbase storage handler i cant create partition in HIVE table and that is why HIVE full table scan becomes very very slow even 10 times slower that HBase Full table scan
I cant think of any solution right now kind of stuck .
Please help me with some other solution where HBase is not involved .
Can i use AVRO or perquet file in this use case .But i am not sure how AVRO will support record level update .

A:

I will answer my question .
My issue is that i dont want to perform full table scan on Hbase because it will impact performance of the region server and specially on the shared cluster it will hit the read wright performance on of the HBase .
So my solution using Hbase because it is very good for the update specially delta update that is columns update .
So in order to avoid that Full table scan take snapshot of HBase table export it to the HDFS and them run full table scan on the Hbase table snapshot.
Here is the detailed steps for the process
Create snapshot
snapshot 'FundamentalAnalytic','FundamentalAnalyticSnapshot'

Export Snapshot to local hdfs
hbase org.apache.hadoop.hbase.snapshot.ExportSnapshot -snapshot FundamentalAnalyticSnapshot -copy-to /tmp -mappers 16

Driver Job Configuration to rum mapreduce on Hbase snapshot
String snapshotName="FundamentalAnalyticSnapshot";
Path restoreDir = new Path("hdfs://quickstart.cloudera:8020/tmp");
String  hbaseRootDir =  "hdfs://quickstart.cloudera:8020/hbase";

 TableMapReduceUtil.initTableSnapshotMapperJob(snapshotName, // Snapshot name
                        scan, // Scan instance to control CF and attribute selection
                        DefaultMapper.class, // mapper class
                        NullWritable.class, // mapper output key
                        Text.class, // mapper output value
                        job,
                        true,
                        restoreDir);

Also running mapreduce on Hbase snapshot will skip scan on Hbase table and also there will be no impact on region server.


Q:

Pass options to ES6 module imports

Is it possible to pass options to ES6 imports?
How do you translate this:
var x = require('module')(someoptions);

to  ES6?

A:

There is no way to do this with a single import statement, it does not allow for invocations.
So you wouldn't call it directly, but you can basically do just the same what commonjs does with default exports:
// module.js
export default function(options) {
    return {
        // actual module
    }
}

// main.js
import m from 'module';
var x = m(someoptions);

Alternatively, if you use a module loader that supports monadic promises, you might be able to do something like
System.import('module').ap(someoptions).then(function(x) {
    …
});

With the new import operator it might become
const promise = import('module').then(m => m(someoptions));

or
const x = (await import('module'))(someoptions)

however you probably don't want a dynamic import but a static one.

A:

Concept
Here's my solution using ES6
Very much inline with @Bergi's response, this is the "template" I use when creating imports that need parameters passed for class declarations. This is used on an isomorphic framework I'm writing, so will work with a transpiler in the browser and in node.js (I use Babel with Webpack):
./MyClass.js
export default (Param1, Param2) => class MyClass {
    constructor(){
        console.log( Param1 );
    }
}

./main.js
import MyClassFactory from './MyClass.js';

let MyClass = MyClassFactory('foo', 'bar');

let myInstance = new MyClass();

The above will output foo in a console
EDIT
Real World Example
For a real world example, I'm using this to pass in a namespace for accessing other classes and instances within a framework. Because we're simply creating a function and passing the object in as an argument, we can use it with our class declaration likeso:
export default (UIFramework) => class MyView extends UIFramework.Type.View {
    getModels() {
        // ...
        UIFramework.Models.getModelsForView( this._models );
        // ...
    }
}

The importation is a bit more complicated and automagical in my case given that it's an entire framework, but essentially this is what is happening:
// ...
getView( viewName ){
    //...
    const ViewFactory = require(viewFileLoc);
    const View = ViewFactory(this);
    return new View();
}
// ...

I hope this helps!

A:

Building on @Bergi's answer to use the debug module using es6 would be the following
// original
var debug = require('debug')('http');

// ES6
import * as Debug from 'debug';
const debug = Debug('http');

// Use in your code as normal
debug('Hello World!');


Q:

Images height too tall

I am trying to setup a section of a screen with 4 images around each other but there is huge white space between them as per image example:

I would like them all right next to each other. Below is the XML I am using:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
          android:orientation="vertical">

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

    <ImageView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/imageView1"
        android:src="@drawable/test1"
        android:layout_weight="1"/>
    <ImageView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/imageView2"
        android:src="@drawable/test"
        android:layout_weight="1"/>

</LinearLayout>

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/imageView3"
        android:src="@drawable/test1"
        android:layout_weight="1"/>

    <ImageView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/imageView4"
        android:src="@drawable/test"
        android:layout_weight="1"/>
</LinearLayout>

I am also trying to get them to the top of the screen but that white space is preventing that.
The images you see dont have any white space at all, the edge of the colors are the edge of the image?
Thanks

A:

You need to set the scaleType to centerInside and the adjustViewBounds to true like this: (adjust view bounds should get rid of the space you don't want.)
   <ImageView
        ...
        android:layout_height="wrap_content"
        android:scaleType="centerInside"
        android:adjustViewBounds="true" />


Q:

SQLAlchemy, get object not bound to a Session

I am trying to get an collection of objects out of a database and pass it to another process that is not connected to the database.  My code looks like the one below but I keep getting:
sqlalchemy.exc.UnboundExecutionError: Instance <MyClass at 0x8db7fec> is not bound to a Session; attribute refresh operation cannot proceed

When I try to look at the elements of my list outside of the get_list() method.
def get_list (obj):
    sesson = Session()
    lst = session.query(MyClass).all()
    session.close()
    return lst

However, if I use this:
def get_list_bis (obj)
    session = Session()
    return session.query(MyClass).all()

I am able to use the elements but worry about the state of the session since it was not closed.
What am I missing here?

A:

If you want a bunch of objects produced by querying a session to be usable outside the scope of the session, you need to expunge them for the session.
In your first function example, you will need to add a line:
session.expunge_all()

before
session.close()

More generally, let's say the session is not closed right away, like in the first example. Perhaps this is a session that is kept active during entire duration of a web request or something like that. In such cases, you don't want to do expunge_all. You will want to be more surgical:
for item in lst:
    session.expunge(item)

A:

This often happens due to objects being in expired state, objects get expired for example after committing, then when such expired objects are about to get used the ORM tries to refresh them, but this cannot be done when objects are detached from session (e.g. because that session was closed). This behavior can be managed by creating session with expire_on_commit=False param.
>>> from sqlalchemy import inspect
>>> insp = inspect(my_object)
>>> insp.expired
True  # then it will be refreshed...


Q:

Put a GeoJSON on a Leaflet map: Invalid GeoJSON object. throw new Error('Invalid GeoJSON object.');

I've some trouble with a Leaflet code that build a GeoJSON and put it on the map.
The GeoJSON is builded from an XML response of a service.
The error is
Invalid GeoJSON object. throw new Error('Invalid GeoJSON object.');
My code is ...

<title>Prova caricamento WMS Indirizzi del PCN</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css"/>

You can copy/paste it and shoud work on your desktop/laptop.
Note that if you uncomment the row ....
//var addressPCN = {"type": "FeatureCollection","features":[{"type": "Feature", "properties": { "popupContent": "Via Pegolo 9", "show_on_map": true }, "geometry": { "type": "Point", "coordinates": [7.719490,44.849197]}},{"type": "Feature", "properties": { "popupContent": "Via Pegolo 8", "show_on_map": true }, "geometry": { "type": "Point", "coordinates": [7.719490,44.849197]}},]};

.... you've the GeoJSON I'm building (you can match it with the alert message ....).
In this case all it's working right.
NOTE: you've to use Firefox or Chrome at the momenti, my code still doesn't work foi IE.
Any suggestion is appreciated!!
Thank you in advance!!
Cesare

A:

The problem was about I tried to use a string as a JSON object.
The solutions is to use jQuery.parseJSON function to convert my string with my JSON code (addressPCN1) to a Javascript JSON object.
Here you are code that works ...
<!DOCTYPE html>

  <title>Prova caricamento WMS Indirizzi del PCN</title>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css"/>


Q:

Checkbox jquery change function is not working and no errors

I have a list of items and I want to do something whenever one of the items is selected, but the problem is that the check-box's change function is not working with me.
I have checked the code inside the function and it's working fine outside the change event. i'm not sure of the reason why it's not working but what could it be other than the function its self ?
Here the change function:
$("input[name='checkCoResult']").change(function () {
     if (this.checked) {
        $("#searchResultSecond").attr("style", "opacity: 0.6");
        $("#searchResultSecond *").attr("disabled", "disabled").off('click');
     }

});

and this is the code that generate my list:
$.ajax({
        url: "CCDMSWebService.asmx/getCoSearchResult",
        data: JSON.stringify(objectData),
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
             var Result = response.d;
                 contantDiv.text("");
        $.each(Result, function (index, val) {
            contantDiv.append('
<input type="checkbox" value="' + val.companyID + '" name="checkCoResult" class="nnn"> '
        +'' + val.companyName + ' provides all your needs
');
           })
        },
        failure: function (msg) {
        alert(msg);
       }
    });

A:

if your content is dynamic then try
$(document).on("change","input[name='checkCoResult']",function(){
     // your code
});


Q:

Double for loop variable initialization

What are the ramifications for the different placement of my variable initialization shown below? Bit of a slow night mentally :/
for row in range(0,3):
    for column in range(0,3):
        block_set = set()

for row in range(0,3):
    block_set = set()
    for column in range(0,3):

A:

Of course there will be differences. The first version creates a new set for each iteration of the inner loop, whereas the second version will create a single set for each iteration of the outer loop.
To put it another way: the second version will create a set that will be shared between all iterations of the inner loop, whereas the first version creates a new set each time, and all data added to the set will be lost. I can't tell for sure without seeing the rest of the code, but it's almost certain that one of the two versions is wrong (it all depends on what you actually want to do.)


Q:

CannotGetMongoDbConnectionException: Failed to authenticate to database

In the replica-set Mongo Shell, use products;db.auth('worker'.'a*******6'); is alright, but in spring-data-mongondb, I encountered the following problem:
Exception in thread "main" org.springframework.data.mongodb.CannotGetMongoDbConnectionException: Failed to authenticate to database [products], username = [worker], password = [a*******6]
    at org.springframework.data.mongodb.core.ReflectiveDbInvoker.authenticate(ReflectiveDbInvoker.java:83)
    at org.springframework.data.mongodb.core.MongoDbUtils.doGetDB(MongoDbUtils.java:127)
    at org.springframework.data.mongodb.core.MongoDbUtils.getDB(MongoDbUtils.java:94)
    at org.springframework.data.mongodb.core.SimpleMongoDbFactory.getDb(SimpleMongoDbFactory.java:197)
    at org.springframework.data.mongodb.core.SimpleMongoDbFactory.getDb(SimpleMongoDbFactory.java:185)
    at org.springframework.data.mongodb.core.MongoTemplate.getDb(MongoTemplate.java:1595)
    at org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:441)
    at org.springframework.data.mongodb.core.MongoTemplate.doCreateCollection(MongoTemplate.java:1612)
    at org.springframework.data.mongodb.core.MongoTemplate.createCollection(MongoTemplate.java:492)
    at com.qixin.appmarket.service.test.TestMongodb.main(TestMongodb.java:24)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

A:

Try updating to spring-data-mongodb to the latest version. I was getting that authentication error while using version 1.7.2.RELEASE but it stopped after updating to 1.8.0.RELEASE.


Q:

rails- slimでのf.submitの文言指定

Ruby on Railsで開発をしています。
createとupdateで使うformファイルでf.submitタグの文言はcreateでrenderするかupdateでrenderするかによって自動で変わってるんですが、そこを私が指定したいんです。
ですが、文言を指定するとcreateとでもupdateでも私が指定した文言に出てしまい困っています。
create時は’登録’、update時は’修正’と指定したいんですが何か方法があれば教えてください。
下記は自分のコードです。
= form_for @book do |f|
  div.form-group
    .field
      = f.label :番号
      = f.text_field :BookNum, class: 'form-control', placeholder: 'Enter...'
        .
        .
        .

  div.box-footer
      .actions
      = f.submit 'create book', class: 'btn btn-info pull-right'

A:

i18nの仕組みにのっかって、config/locales/ja.ymlにbookモデル用のhelpers.submitの設定を追加するとよいと思います。
http://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-submit
= form_for @book do |f|
  div.form-group
    .field
      = f.label :番号
      = f.text_field :BookNum, class: 'form-control', placeholder: 'Enter...'
        .
        .
        .

  div.box-footer
      .actions
      = f.submit class: 'btn btn-info pull-right'

config/locales/ja.yml
ja:
  helpers:
    submit:
      book:
        create: "登録"
        update: "修正"


Q:

dismiss view controller custom animation

I am trying to replicate this animation to dismiss a view controller (15 second video): https://www.youtube.com/watch?v=u87thAbT0CQ
This is what my animation looks like so far: https://www.youtube.com/watch?v=A2XmXTVxLdw
This is my code for the pan gesture recognizer:
 @IBAction func recognizerDragged(sender: AnyObject) {
    let displacement = recognizer.translationInView(view)
    view.center = CGPointMake(view.center.x + displacement.x, view.center.y + displacement.y)
    recognizer.setTranslation(CGPoint.zero, inView: view)
    switch recognizer.state {
    case .Ended:
        UIView.animateWithDuration(0.4, animations: { () -> Void in
            self.view.layer.position = CGPoint(x: self.view.frame.width / 2, y: self.view.frame.height / 2)
        })
    default:
        print("default")
    }

    let velocity = recognizer.velocityInView(self.titleView)
    print(velocity)
    if velocity.y < -1500 {
        up = true
      self.dismissViewControllerAnimated(true, completion: nil)
    }
    if velocity.x > 1500 {
        right = true
        self.dismissViewControllerAnimated(true, completion: nil)
    }
}

It may be a little hard to notice in my video, but there is a small disconnect in how fast the user flicks up, and how fast the animation completes. That is to say, the user may flip up very fast but the animation is set to a hardcoded 0.3 seconds. So if the user flicks the view fast, then as the animation completes, as soon as their finger lifts off the view, the animation actually slows down.
I think what I need is a way to take the velocity recorded in the recognizerDragged IBAction, and pass that to the animation controller, and based on that, calculate how long the animation should take, so that the velocity is consistent throughout, and it looks smooth. How can I do that?
Additioanlly, I'm slightly confused because the Apple Documentation says that the velocityInView function returns a velocity in points, not pixels. Yet different iOS devices have different points per pixels, so that would further complicate how I would translate the velocity before passing it to the animation class.
Any idea how to pass the velocity back to the animation controller, so that the animation duration changes based on that, and make it work for different iPhones ?
thanks

A:

What you are likely looking at in the video you are trying to replicate is a UIDynamics style interaction, not a CoreAnimation animation. The velocity returned from velocityInView can be used directly in UIDynamics like this:
[self.behavior addLinearVelocity:
        [pan velocityInView:pan.view.superview] forItem:pan.view];

I wrote a tutorial for doing this style of view interaction here: https://www.smashingmagazine.com/2014/03/ios7-new-dynamic-app-interactions/
To stick with UIView animations you just need to look at the frame's bottom  (which is also in points) and calculate the new time. This assume that you want frame's bottom to be at 0 at the end of the animation:
  animationTime = CGRectGetMaxY(frame) / velocity

You aren't showing how you created the animation controller, but just keep a reference to it and pass the time before calling dismiss.  This is also assuming you are using a linear curve.  With any other kind of curve, you will have to estimate what the starting velocity would have to be to be based on time and adjust.


Q:

Listview becomes disabled by default

I have a listview whose adapter is used with 2 textviews and one imageview.
But I can't click any item in the listview. The listview becomes grayed out at runtime. I have set OnItemCLickListener for the listview but it still doesn't work.
m_lv.setOnItemClickListener(new OnItemClickListener() {

     @Override
     public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                        long arg3) {
         ((JListAdapter)arg0.getAdapter()).setSelView(arg1);
         ListView lv=(ListView)arg0;
         TextView v=(TextView)lv.getChildAt(arg2);
         String s=(String) v.getText();
         Toast.makeText(m_context, s, Toast.LENGTH_LONG).show();
    }
}

Here is the xml for listview's items.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dp"
    android:clickable="true"
    android:focusable="true"
    android:focusableInTouchMode="false"
    android:scrollbars="vertical"
    android:visibility="visible" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="false"
        android:layout_centerInParent="true"
        android:contentDescription="@string/dummy_txt"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:src="@drawable/lvitem" />

    <TextView
        android:id="@+id/tv_lv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/imageView1"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="2dp"
        android:layout_toRightOf="@+id/imageView1"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:maxLines="2"
        android:text="@string/dummy_txt"
        android:textSize="9sp"
        android:textStyle="bold"
        tools:ignore="SmallSp" />

    <TextView
        android:id="@+id/tv_lv_datetime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/tv_lv_title"
        android:layout_below="@+id/imageView1"
        android:layout_marginBottom="2dp"
        android:layout_marginTop="5dp"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:text="@string/dummy_txt"
        android:textSize="7sp"
        android:textStyle="italic"
        tools:ignore="SmallSp" />

</RelativeLayout>

A:

You just want to edit your xml file as Below:

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="false"
        android:layout_centerInParent="true"
        android:contentDescription="@string/dummy_txt"
        android:focusable="false"
        android:src="@drawable/lvitem" />

    <TextView
        android:id="@+id/tv_lv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/imageView1"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="2dp"
        android:layout_toRightOf="@+id/imageView1"
        android:focusable="false"
        android:maxLines="2"
        android:text="@string/dummy_txt"
        android:textSize="9sp"
        android:textStyle="bold"
        tools:ignore="SmallSp" />

    <TextView
        android:id="@+id/tv_lv_datetime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/tv_lv_title"
        android:layout_below="@+id/imageView1"
        android:layout_marginBottom="2dp"
        android:layout_marginTop="5dp"
        android:focusable="false"
        android:text="@string/dummy_txt"
        android:textSize="7sp"
        android:textStyle="italic"
        tools:ignore="SmallSp" />

</RelativeLayout>


Q:

related to float and width

I have a sidebar and a content area. I just floated the sidebar to the left and the content area to the right. But I have problem when the screen size changes. There occurs a significant space between the two floats. I think it's due to the size of the image in the content area and since it's floated right. Hence I floated this content area also to the left. now the content area is not extending to the extreme right end of the screen. Is there any way to put the content area fit in the right portion without any space (just the space to divide the sidebar and content area is enough)?
If you need more explanations, please let me know.

A:

Change your CSS to this:
.dashContent {
     float: left;
     margin: 10px;
     position: relative;
     top: 25px;
     min-width: 80%;
}

.sidebarDash {
    float: left;
    height: auto;
    width: 195px;
}

This will remove the space and also retain fluidity in the layout - Removed as the OP wants a fixed layout


Q:

Startup and shutdown DB Oracle in preset time

How I can preset time startup and shutdown DB Oracle ? Help me please.

A:

Presuming that you know how to start it up and shut it down, create two scripts (if on MS Windows, these would be .BAT files). Test whether they work correctly.
Then, using Task Scheduler, schedule the STARTUP.BAT to run in the morning and SHUTDOWN.BAT to run in the afternoon (or whenever you want).


Q:

JOptionPane throwing error when cancelled

Currently having an issue where I am popping a message dialog up to prompt the user to enter a string. I have a check for the name being empty which works properly if they hit the "ok" button however if the user hits the cancel button (whether they input anything into the textbox or not) then I get the following error:
java.lang.NullPointerException
at cc.nisc.mapping.mappingadvsearch.ResultsPopupMenu$1.doActionPerformed(ResultsPopupMenu.java:98)
at cc.nisc.gui.action.NiscAction.actionPerformed(NiscAction.java:225)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.AbstractButton.doClick(AbstractButton.java:376)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:833)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:877)

The relevant code is :
public final ResultsMenuAction createLayerAction = new ResultsMenuAction("uiCreateLayer") {
    @Override
    protected void doActionPerformed(ActionEvent e) {

        try {
            String queryName = JOptionPane.showInputDialog(WinMgr.getInstance().getSelectedNavigator(),
                                                           "Enter a name for your exported query layer",
                                                           "Enter Query Name",
                                                           JOptionPane.QUESTION_MESSAGE);
            if (queryName.isEmpty()) {
                JOptionPane.showMessageDialog(WinMgr.getInstance().getSelectedNavigator(),
                                              "Please enter a name for your query",
                                              "Empty name",
                                              JOptionPane.WARNING_MESSAGE);
                return;
            }
            ....
            ....

How can I check to see if the cancel button has been clicked in order to return instead of raising the error?

A:

From the JavaDoc on JOptionPane.showInternalInputDialog() which is called by the method you're using:

Returns:
  user's input, or null meaning the user canceled the input

Thus null would indicate the input being cancelled.
To check for null or empty input, you'd first check the for null and then for empty, since calling isEmpty() on null will result in an NPE.
Keep in mind that || is the short circuit or operator, i.e. it will evaluate expressions from left to right and stop whenever a condition becomes true. Thus if( queryName == null || queryName.isEmpty() ) won't throw a NPE because if queryName is null the condition is true and isEmpty() is never called.
In contrast a single pipe | isn't a short circuit operator, i.e. both expressions are evaluated regardless of whether the left is already true. Thus queryName == null | queryName.isEmpty() might still throw a NPE.


Q:

Using `++` in pattern matching

Typing the following into a GHC interpreter
let describe' all@([x] ++ [y]) = "The first letter of " ++ all ++ " is " ++ [x]

yields

Parser error in pattern: [x] ++ [y]

Why is Haskell unable to match the pattern all@([x] ++ [y]) against expressions like "HI" or [1,2]?

A:

let's assume you could pattern-match on ++ - now think about how you could match this:
a ++ b = [1,2]

you could have:

a = [1,2], b = []
a = [1], b = [2]
a = [], b = [1,2]

now what is the right one?

the technical reason is that ++ is not data-constructor ;)

in your specific situation you could use
let describe' all@[x,y] = "The first letter of " ++ all ++ " is " ++ [x]

(which will only match strings with length exactly 2)
or better
let describe' all@(x:_) = "The first letter of " ++ all ++ " is " ++ [x]

(which will match all strings of length at least 1)
a safe version would be this
describe' :: String -> String
describe' ""        = "your input was empty"
describe' all@(x:_) = "The first letter of " ++ all ++ " is " ++ [x]

A:

You may only use constructors in pattern matches. The pattern [x] desugars to the pattern x:[], where : and [] are both constructors. ++, however, is a function. This is a small flaw of the Haskell language design in that we are unable to quickly distinguish between what symbols we have defined as functions and what symbols come to us from their datatype declarations. For a full treatment, see section 3 of the Haskell 2010 Language Report.


Q:

Does anyone have any tips for developing a character in skyrim?

This is my first time in the series and I feel like I am all over the place. I'm a master at smithing, but everything else is in the 50's/60's. Only a few others are over 70.
This link made me rethink my choices: http://www.bigbadbob113.com/2011/11/29/elder-scrolls-v-skyrim-character-build-guide-rogue-2/
If you scroll down, this guy is a level lower than me and it looks like most of his stats are 60 or higher.
Don't get me wrong, I've had a lot of fun so far and I understand its what I make of it, but I just wonder if I could have planned things better or is this how things normally go?
To give you an idea of what I have - Level 41 Breton where I hack at people with an axe and use destruction spells with my other hand. I've liked it so far, but I'm starting to feel like I need to start over. I feel like I am just getting by on dying multiple times to try different tactics and occasionally get a crazy stroke of good luck.
I might also be burnt out because I spent close to 8 hours concentrating on smithing alone so I could go from level 85-100 and my enchanting is only 56. I am beginning to feel like I am working more than playing the game.
Any tips? Thanks for all your suggestions!

A:

For better or for worse, I think that's kind of just how things go. Each player puts effort in to what they enjoy the most or what is most useful for the type of character they want to play. The latter of which is pretty straight forward, I think. If you love battle, focus on weapons and armor; if you want to be a mage, focus on enchanting, et cetera.
However, unlike Oblivion, you don't have to pick a skill every time you level up. Instead, leveling up your skills boosts your character level. Personally, I think this gives the player a lot more leeway in their character build, even if it does feel a little "all over the place" at times. This way, when you've maxed out all the "fighting" skills of your character, you could go back and just make them a kick ass mage as well.
Just my two cents, hope that answered part of your question at least.
Here's a decent reference for the leveling system in Skyrim: http://www.uesp.net/wiki/Skyrim:Leveling


Q:

Adobe suite to create a high definition 3D cube animation?

I'm looking to try and create something along the quality of this video below:
http://www.shutterstock.com/video/clip-1992226-stock-footage-red-cube.html?src=search/H2Qpzpwk6MCZPa0pfA2U0g:1:25/3p
Now, creating the 3D object I can probably do in Photoshop, but wouldn't the frame rate be too low for something like this? Also, could it be exported as an MP4, rather than an animated gif?
Failing that, would anybody care to recommend any other solutions to this inside the Adobe CC suite? Or would I need to purchase different software altogether in order to achieve my goal?

A:

You'd be a lot better off probably using Blender, Maya, or After Effects + Cinema4D for this. But if you are confident you can create the object in Photoshop than frame rate shouldn't be an issue. Adobe Photoshop has decent video controls now and renders as .mp4. Additionally, you could use Adobe Media Encoder if you need to convert from .mp4 to some other format.


Q:

Loop Help For Storing Values From Text File

I am reading in a text file and splitting it at delimited point.  Everything before the : is the left value, and everything after is the right. What is the best loop through the lines and store the string values into 2 lists, a left and a right? I don't need them to output, just store the values in the list.
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        id newId = new id();
        newId.Left = "";
        id newId2 = new id();
        newId2.Right = "";

    }
    private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog of = new OpenFileDialog();
        of.ShowDialog();
        textBox1.Text = of.FileName;
        using (StreamReader sr = new StreamReader(of.FileName));

        string content = File.ReadAllText(of.FileName);
        string[] split = content.Split(';' , ':');
        foreach (string segment in split)
        {

            if

        }

              }

A:

This should work. Not sure if you wanted the semicolon at the end so I just removed it.
var left = new List<string>();
var right = new List<string>();
using (var diag = new OpenFileDialog()) {
    if (diag.ShowDialog() == DialogResult.OK) {
        using (var sr = new StreamReader(diag.FileName)) {
            string line;
            while ((line = sr.ReadLine()) != null) {
                var split = line.Replace(";", "").Split(':');
                if (split[0] != null && split[1] != null) {
                    left.Add(split[0]);
                    right.Add(split[1]);
                }
            }
        }
    }
}

I noticed you mentioned this is a key/value thing so I would actually do:
var dict = new Dictionary<string, string>();
using (var diag = new OpenFileDialog()) {
    if (diag.ShowDialog() == DialogResult.OK) {
        using (var sr = new StreamReader(diag.FileName)) {
            string line;
            while ((line = sr.ReadLine()) != null) {
                var split = line.Replace(";", "").Split(':');
                if (split[0] != null && split[1] != null)
                    dict.Add(split[0], split[1]);
            }
        }
    }
}

Could be cleaned up a bit but you see the point. You were reading the entire file and then splitting. How would you know which was on the left and right of each line? Maybe check even and odds? That's terrible though when you can just read a single line and then split that. Then just grab the first and second items in the array and you have your two items.


Q:

Dry wall in shower a little moldy

I've been using my shower with just dry wall up for months now (don't ask :) Anyway, there's a little bit of mold, I'm guessing, on a small section of the wall. I'm finally ready to put up some tile.
Do I need to replace the dry wall since I've been abusing it with the shower before I put up new tile. Can't I just let it dry or spray something on it?

A:

Drywall shouldn't be in the shower.  Take it down and replace with cement board.  This will cost you $50 and will ensure the money and time you put into the tile last more than a year.
If for some odd reason you are using a Kerdi membrane or something like that (which your question leads me to think you are not) than you could keep the drywall.  You would have to scrape off the mold and hit the drywall with a anti-mold spray.  If the mold doesn't scrape off then you need to replace that section of drywall.


Q:

how to call a member function from a destructor

I'm doing work for a C++ project, but I want to know how to call a member function from a class/structure within a destructor. The rest of my project is going well, so I just need to know this to be finished with it :)
    ~Drink()
    {
        cout << "hi";
        cout << "I want to know how to summon a member function from a destructor.";
    }

    int Drink::dailyReport()
    {
        cout << "This is the member function I want to call from the destructor.";
        cout << "How would I call this function from the destructor?"
    }

Proper syntax and all would be appreciated! Examples of how to call a member function from a destructor would be lovely!

A:

The problem here is that you didn't prefix your destructor with Drink::
Since the destructor doesn't know what class it is supposed to be associated with (assuming it is being defined outside of the class declaration), it does not know that it even has a member function to call.
Try rewriting your code to:
Drink::~Drink() // this is where your problem is
{
    cout << "hi";
    cout << "I want to know how to summon a member function from a destructor.";
    dailyReport(); // call the function like this
}

int Drink::dailyReport()
{
    cout << "This is the member function I want to call from the destructor.";
    cout << "How would I call this function from the destructor?"
}


Q:

Why do I get the error "The service type ITraceWriter is not supported." from Azure?

I am trying to get my Web API 2 up and running on an Azure App Service. It works fine on my machine, on IIS 10, with the following tracing added, from the package Microsoft.AspNet.WebApi.Tracing:
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.EnableSystemDiagnosticsTracing();
        SystemDiagnosticsTraceWriter traceWriter = config.EnableSystemDiagnosticsTracing();
        traceWriter.IsVerbose = true;
        traceWriter.MinimumLevel = TraceLevel.Debug;
        config.Services.Add(typeof(ITraceWriter), new TextFileTracer());

This works fine on my dev machine, but I get the error

The service type ITraceWriter is not supported.

as soon as I publish to Azure. I thought a modern ASP.NET app was supposed to be self contained, and not rely on services being present or configured on the host, and a very up to date host at that. Why is this happening?

A:

According to your description, I tested your code on my Web API application and I got the server error as follows on my local side.

The service type ITraceWriter is not supported.
  Parameter name: serviceType

As mentioned in this official document about setting the Trace Writer:

To enable tracing, you must configure Web API to use your ITraceWriter implementation. You do this through the HttpConfiguration object, as shown in the following code:

config.Services.Replace(typeof(ITraceWriter), new TextFileTracer());

Only one trace writer can be active. By default, Web API sets a "no-op" tracer that does nothing. (The "no-op" tracer exists so that tracing code does not have to check whether the trace writer is null before writing a trace.)

After replacing ITraceWriter service with the TextFileTracer instance, I could make it work as expected both on my side and Azure.


Q:

I need to install composer on my server to be able to perform a cron job with laravel?

Is my first project in laravel and I am trying to perform a cron job but for some reason this does not seem to work, initially I worked the project in local, then upload it to the server and never installed composer in the cPanel, this is the cause that Does not work ?, I leave the code I have used.
for the command
<?php
namespace App\Console\Commands;
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Plan;
use App\Plan_negocio2;
use App\Plan_negocio;
use App\Pagina;
use DateTime;
use Illuminate\Console\Command;

//use Illuminate\Foundation\Inspiring;

class Resaltador extends Command {

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'res:resaltado';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Verificar Resaltador';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $plan=Plan_negocio::all();
        //$fechaAct=$request->fecha;

        if ($plan)
        {
            $arrNegocio=[];
            foreach ($plan as $key => $value)
             {
                //$value->fechafin=strtotime("2017-04-07")-time();

            date_default_timezone_set('America/Caracas');
            $date = new DateTime($value->fechafin);
            $dateHoy=new DateTime();
            //$dat=$dateHoy->getTimestamp();
            $dat=9999999999999999;
            $value->fechafin=$date->getTimestamp();
            //$now = new DateTime();

                //$gene= $date1->format('U') - $now->format('U');

                if ($dat>$value->fechafin)
                {
                 $negoPlan=Pagina::find($value->negocio_id);
                 $negoPlan->resalta_id=1;
                 $res=$negoPlan->save();

                }

             }
        }

    }

}

code of the kernel.php
  <?php
   namespace App\Console;

  use Illuminate\Console\Scheduling\Schedule;
  use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

   class Kernel extends ConsoleKernel {
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [

        //'App\Console\Commands\Inspire',
        \App\Console\Commands\Resaltador::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        /*$schedule->command('inspire')
                 ->hourly();*/

                 $schedule->command('res:resaltado')->everyMinute();
    }

}

route of the cron job
The path that I give to the cron job does not give me any errors, so I do not think this is giving errors
the path is this
/usr/bin/php -q home3/pixsony6/public_html/loupper.com/loupper/artisan schedule:run 1>> /dev/null 2>&1

Any suggestions would be good, thanks

A:

No, you do not need Composer to run a cron job with Laravel.
If you're vendor folder is present with all dependancies then you can run commands.
Composer is for installing packages to the vendor folder.
For your specific problem, try using the php-cli instead of php