text:
Q: Array() = range().value I saw array() = range().value in an example and I'm trying to understand how it works.
Sub test()
Dim arr() As Variant

arr() = Range("E5:E7").Value
For i = 0 To UBound(arr)
    Debug.Print arr(i)
Next i

End Sub

First, above code is giving me subscript out of range error. How come ? Second, what part of the documentation would let me know how array() = range().value would play out without testing it ? My hypothesis is that it will go through the cells from the top left to the bottom right and add them to the array. How can I confirm that though ?

A: I see two issues with your code.  The first is that you start i at 0, but arrays in Excel begin at index 1.  Instead of For i = 0 you can use For i = LBound(arr) like you use UBound(arr) or just start it at 1.
Second, and more importantly, an array of cells has both columns and rows.  When you read a range into a variant array, you get a two-dimensional result (rows and columns) and not a one-dimensional result as you seem to be expecting.
Try this:
Sub test()
        Dim arr() As Variant
        Dim i As Long, j As Long

        arr() = Range("E5:E7").Value
        For i = 1 To UBound(arr, 1)
                For j = 1 To UBound(arr, 2)
                        Debug.Print arr(i, j)
                Next j
        Next i
End Sub

If you want to get just the values of the cells into a one dimensional array, you can do that by using the Transpose function, like this:
arr() = Application.WorksheetFunction.Transpose(Range("E5:E7").Value)

If you do this, the array is now one-dimensional and you can iterate through it like you were trying to.
arr() = Application.WorksheetFunction.Transpose(Range("E5:E7").Value)

For i = 1 To UBound(arr)
    Debug.Print arr(i)
Next i

A: This is a good read for you: http://www.cpearson.com/excel/ArraysAndRanges.aspx
The reason you're getting "out of range" is because it returns a 2 dimensional array.
Your line of code For i = 0 To UBound(arr) should be For i = 1 To UBound(arr,1)
Also, the array starts at 1, so don't use the 0 For i = 1 to UBound(arr, 1)
Your corrected code would be:
Sub Test()

Dim arr() as Variant
arr = Range("E5:E7")
For i = 1 To UBound(arr, 1)
    MsgBox (arr(i, 1))
Next i

End Sub

A: It's basically loading the cell values of E5 - E7 into an array. But it is going to be two dimensional. So you will need Debug.Print arr(i, 1)
Sub test()
Dim arr() As Variant

arr() = Range("E5:E7").Value
For i = 1 To UBound(arr)
    Debug.Print arr(i, 1)
Next i

End Sub


text:
Q: Relation between cyclotomic character and fundamental character of level The question I have is the following: is it true that the $p+1$ exponentiation of the fundamental character of level $2$ gives us the reduction (mod $p$) of the cyclotomic character?
For a review of the definitions, see here.
Thank you for yours answers.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Where to start for Augmented Reality in iPhone? I have done lots of applications for iOS using Xcode. And i want to explore the feasability of Augmented Reality in iPhone. I searched for it and found that we need  SDKs for it i.e Qualcom or String. Can anybody suggest me whichone is best to start with? And any sample tutorial for start-up related to that.?

A: If you want to learn about Augmented Realty and many different APIs, IDEs, Engines and SDKs, this book may be the best resource for you
Pro iOS 5 Augmented Reality
It is for iOS 5, but I see no adoption that prevents it from working with iOS 6. It is great! It shows Qualcomm demoes, Open-CV, String and more!'
The author works with you throughout the book with examples and explanations which are beyond interesting and cool.
After reading this book I feel like a professional, just read the reviews, a great valuable book!
Answering your ultimate question, which is the best SDK/API? I think that it depends on what you want, they have different purposes, functionalities, learning curves etc. I suggest you read this book to explore all

A: You could use iPhone-AR-Toolkit. It's up on GitHub, and I've added in lots of helpful things like a radar, modern callouts etc...


text:
Q: Hibernate 5 + Eclipse RCP + SQLite 3 - Unable to resolve name as strategy org.hibernate.dialect.Dialect I have Eclipse RCP Application. JARs with hibernate are in another plugin which is included in the main project in MANIFEST.MF.
I try to establish simple connection Hibernate -> SQLite DB using code:
try {
    Configuration lConf = new Configuration();
    lConf.addAnnotatedClass (eDocument.class);
    lConf.setProperty("hibernate.dialect", "app.sqlite.SQLiteDialect");
    lConf.setProperty("hibernate.connection.driver_class", "org.sqlite.JDBC");
    lConf.setProperty("hibernate.connection.url", "jdbc:sqlite:sfOrders.db");
    lConf.setProperty("hibernate.connection.username", "");
    lConf.setProperty("hibernate.connection.password", "");

    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(lConf.getProperties());
    _sessionFactory = lConf.buildSessionFactory(builder.build());
} catch (Throwable ex) {
    throw new ExceptionInInitializerError(ex);
}

I use custom SQLiteDialect and i get error:
java.lang.ExceptionInInitializerError
    at app.sqlite.DatabaseConnector.connect(DatabaseConnector.java:57)
    at views.TransactionManagerView$6.widgetSelected(TransactionManagerView.java:144)
    at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:248)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
    at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4362)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1113)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4180)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3769)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1127)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1018)
    at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:156)
    at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:654)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:598)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:150)
    at smoothflow.Application.start(Application.java:25)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:380)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:235)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:669)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:608)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1515)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1488)
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:244)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:208)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:217)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
    at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418)
    at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:692)
    at app.sqlite.DatabaseConnector.connect(DatabaseConnector.java:55)
    ... 29 more
Caused by: org.hibernate.boot.registry.selector.spi.StrategySelectionException: Unable to resolve name [app.sqlite.SQLiteDialect] as strategy [org.hibernate.dialect.Dialect]
    at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.selectStrategyImplementor(StrategySelectorImpl.java:113)
    at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveDefaultableStrategy(StrategySelectorImpl.java:162)
    at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveDefaultableStrategy(StrategySelectorImpl.java:126)
    at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveStrategy(StrategySelectorImpl.java:120)
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.constructDialect(DialectFactoryImpl.java:74)
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:51)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:137)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:234)
    ... 42 more

I tried to compile it with the same hibernate configuration Java code in empty normal Java project and it works

*

*db: sfOrders.db exists

*without lConf.addAnnotatedClass (eDocument.class) i get the same error

*i cant use xml/hbm configs

EDIT:
it must be something with the way Hibernate load classes as from what I see in sources [Line 113], there is no simple Class.forName but classLoaderService:
https://github.com/hibernate/hibernate-orm/blob/master/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorImpl.java
I have tried replace hibernate.dialect with this:
lConf.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");

Of course, there are other errors as I use SQLite (not MySQL) but MySQLDialect is found properly by StrategySelectorImpl.class.
To be 100 % sure that my app.sqlite.SQLiteDialect exists i created code:
Class lClass = Class.forName("app.sqlite.SQLiteDialect");

lClass is not null

EDIT:
I see that hibernate caches some kind of loader and it tries to find class inside my Eclipse RCP project with JARs instead of main project (in which the project with JARs is included). I changed dialect to MySQLDialect.class and next error i got is:
ClassNotFoundException: app.eCommerceCalls.eDocument cannot be found by SFLib_1.0.0

eDocument.class exists but in main project (not in Eclipse RCP Project with JARs [including hibernate]). SFLib_1.0.0 - project with JARs

EDIT:
So the question is, how to make classes from main RCP project visible for classes inside JAR from Eclipse RCP Project with libraries.
so in my case, the BundleLoader.class from SF1.0.0 can't find a class from main project eDocument.class.

A: Try to replace this line:
    lConf.setProperty("hibernate.dialect", "app.sqlite.SQLiteDialect");

With:
lConf.setProperty("dialect", "app.sqlite.SQLiteDialect");

A: The issue is resolved. The problem was in bundle visibility. The solution was to add into MANIFEST.MF (under Runtime tab), hibernate mapped classes to make them available to reach from bundle Eclipse plugin where hibernate was added

A: It seems like the default collection of ClassLoaders that Hibernate starts with does not have access to the "app.sqlite.SQLiteDialect" class. Since you are booting it up with a manual configuration, rather than just a persistence.xml, then a solution would be to pass the class reference, rather than the name. In that case it might be better if you use the JPA boot-up through the Persistence class, using Persistence.createEntityManagerFactory(String unitName, Map props). That way it isn't limited to only taking strings.
Without moving to JPA-boot, this should work for 5.2:
Properties props = new Properties();
Configuration lConf = new Configuration();
lConf.addAnnotatedClass (eDocument.class);
props.put("hibernate.dialect", app.sqlite.SQLiteDialect.class);
props.put("hibernate.connection.driver_class", "org.sqlite.JDBC");
props.put("hibernate.connection.url", "jdbc:sqlite:sfOrders.db");
props.put("hibernate.connection.username", "");
props.put("hibernate.connection.password", "");
lConf.setProperties(props);
lConf.buildSessionFactory();

Using setProperties bypasses the typecast to String.


text:
Q: Programs to demo a high-end video card? I'm the proud owner of an nVidia GTX 260, but I'm not a gamer. I bought the card to play around with CUDA programming, but I find myself tempted to see what kinds of great things a powerful graphics card can do.
I'm looking for recommendations for programs, games, or screen savers that will really show off this graphics card. The card is on a pretty reasonable machine (core i7, ssd, 6 GB RAM), so I don't think those will be a bottleneck.

A: Try FurMark (the testing and benchmarking game).

Also, GPU Caps Viewer and FluidMark.

A: Crysis. Turn everything as high as possible and it looks gorgeous.

A: Speak Visual with the card.
You need to read up individual demo links (learn more) to check which are applicable for you.
Some may be just patches to other software and others may not work on your card.
From what remains, you may not be interested in some.
But, could be interesting.

A: nVidia has a couple of cool demos that will make you feel good about your graphics card :)
debris is another excellent demo (196kb) from the folks who made the infamous 96kb 3D shooter kkrieger

A: Really Slick Screensavers look good.

A: rthdribl (Real-Time High Dynamic Range Image-Based Lighting) is relatively old now, but worth a look.


text:
Q: I am trying to write out the results of a process to a text file, the issue I have is with the alignment of the columns I am sure someone somewhere has had this same issue but I have looked far and wide (including here on the stackoverflow) to find out how to properly align my columns in an output file. The following is the complete code I am using (for an event generator called Pythia 8 of which C++ is the primary language):
using namespace Pythia8;

int main()
{
    Pythia pythia;
    pythia.readString("Top:gg2ttbar = 1");
    pythia.init(2212, 2212, 14000.);
    ofstream myfile;
    myfile.open("ttbar.txt");

    for (int iEvent = 0; iEvent < 1; ++iEvent)
    {
        if (!pythia.next()) continue;

        vector<double> part;
        for (int i = 0; i < pythia.event.size(); ++i)
        {
            if (pythia.event[i].status() == 91) part.push_back(i);
        }

        myfile << "N = " << part.size() << endl;
        for (int j = 0; j < (int(part.size()) - 1); ++j)
        {
            myfile << left << setw(4) << int(part[j]);
            myfile << setw(4) << left << pythia.event[part[j]].name() << "     "
                   << right << pythia.event[part[j]].id() << "     "
                   << pythia.event[part[j]].px() << "     " << pythia.event[part[j]].py()
                   << "     " << pythia.event[part[j]].pz() << "     "
                   << pythia.event[part[j]].m() << "     " << pythia.event[part[j]].pT() << endl;
        }

    }

    pythia.stat();
    myfile.close();
    return 0;
}

The issue occurs near the bottom where the loop that writes out the text file starts, as it is currently written in the above code, the first two columns are mashed together:
N = 665
1777pi-      -211     1.19978     0.715507     32.7878     0.13957     1.39694
1779pi+      211     -8.24173     6.07047     -31.6818     0.13957     10.2361

That is the first couple lines of the output (the program shows the line number where a certain particle is produced and relevant information about it like the name, mass...etc.). I cannot seem to format it so I don't have to use the inserted spaces that I put in by hand.

A:
as it is currently written in the above code, the first two columns are mashed together

well, yes, you explicitly wrote the first two columns with no whitespace between them:
        myfile << left << setw(4) << int(part[j]);
        myfile << setw(4) << left << pythia.event[part[j]].name() << ...

If you want a general way to format this without worrying adding manual whitespace, split it into two steps:

*

*create a vector<string> containing the columns for each line (you can just use an ostringstream to format each column individually)

*write a function to take that vector and write it to an ostream, with spaces between.
std::copy(begin, end, std::ostream_iterator(myfile, "    "));

will be sufficient if you just want a fixed number of spaces between each column


text:
Q: Matching optionally in expression with Python regex? I have written the following regex to match human-readable time at the command-line:
^(?:(?:(?:(\d+)d\s*)?(\d+)h\s*)?(\d+)m\s*)?(\d+)s$

Using non-capturing strings, this regex matches "human-readable" time equally-well in the following formats:
1d 2h 3m 4s
1h 2m 3s
1m 2s
1s

...and...
1d2h3m4s
1h2m3s
1m2s
1s

In this regex, if I include a minutes value, I also have to include a seconds value. I.e., I can't simply provide 15m or 1d3m, I have to provide 15m0s or 1d0h3m0s.
Is it possible to extend a regex to match these latter two use cases? How? Please note: I'm not necessarily looking for a drop-in solution, but a pointer in the right direction would be greatly appreciated.
Update
Just a brief update that I made awhile back - this is for regex in Python.

A: You can use this pattern:
\A(?=\S)(?:\d+d)?(?:\h*\d+h)?(?:\h*\d+m)?(?:\h*\d+s)?\z

The approach is to make all element optional. The lookahead at the begining ensures that there is at least a character that is not a space. (in other words, it ensures that there is at least one element)

A: Rather that maintaining that regular expression and trying to tweak it I would suggest greatly simplifying your regex to this:
/ *(\d+)([dhms])/gm

RegEx Demo
As you can see it matches all your current and proposed strings. You can then post-process both captured groups in your code.

A: your seconds files is not optional.there is no ? after it.so all fields not containg s will fail.
See demo.
http://regex101.com/r/iX5xR2/28
I have applied question mark.

A: You can use nested groups:
/^(?:(?:(?:(\d+)d\s*)?(\d+)h\s*)?(\d+)m\s*)?(\d+)s$/g

The value for d, h, m and s are in groups 1, 2, 3 and 4 respectively.
Here is a regex demo!


text:
Q: a clue to solve $\int ^{1}_{0}(\frac {1-x}{\ln x}\left( x^{2^{0}}+x^{2^{1}}+\ldots +x^{2 ^{n}}\right))dx$ need a clue to solve
$$\int ^{1}_{0}(\dfrac {1-x}{\ln x}\left( x^{2^{0}}+x^{2^{1}}+\ldots +x^{2 ^{n}}\right))dx$$
the answer is -ln3.
I have no idea to begin with.

A: HINT:
$$\int_0^1 x^\text{m}\cdot\frac{1-x}{\ln\left(x\right)}\space\text{d}x=\ln\left(1+\text{m}\right)-\ln\left(2+\text{m}\right)\tag1$$
When $\Re\left(\text{m}\right)>-1$

*

*When $\text{m}=2^0$:
$$\int_0^1 x^{2^0}\cdot\frac{1-x}{\ln\left(x\right)}\space\text{d}x=\ln\left(1+2^0\right)-\ln\left(2+2^0\right)\tag2$$

*When $\text{m}=2^1$:
$$\int_0^1 x^{2^1}\cdot\frac{1-x}{\ln\left(x\right)}\space\text{d}x=\ln\left(1+2^1\right)-\ln\left(2+2^1\right)\tag2$$

A: $$\int_{0}^{1}\frac{x^b-x^a}{\ln x}\mathrm dx\\=\int_{0}^{1}\int_{a}^{b}x^u\,\mathrm du\mathrm dx\\
=\int_{a}^{b}\left(\int_{0}^{1}x^u\mathrm dx\right)\mathrm du\\=\int_{a}^{b}\frac{\mathrm du}{u+1}=\ln\frac{b+1}{a+1}$$


text:
Q: Error: MySQL shutdown unexpectedly i see this error in my xampp/mysql/logs. what shoud i do?
2019-09-18 16:06:13 0 [Note] InnoDB: Completed initialization of buffer pool
2019-09-18 16:06:13 0 [ERROR] InnoDB: Cannot create log files because data files are corrupt or the database was not shut down cleanly after creating the data files.
2019-09-18 16:06:13 0 [ERROR] InnoDB: Plugin initialization aborted with error Generic error
2019-09-18 16:06:13 0 [Note] InnoDB: Starting shutdown...
2019-09-18 16:06:13 0 [ERROR] Plugin 'InnoDB' init function returned error.
2019-09-18 16:06:13 0 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2019-09-18 16:06:13 0 [Note] Plugin 'FEEDBACK' is disabled.
2019-09-18 16:06:13 0 [ERROR] Unknown/unsupported storage engine: InnoDB
2019-09-18 16:06:13 0 [ERROR] Aborting
2019-09-18 16:14:28 0 [Warning] InnoDB: Are you sure you are using the right ib_logfiles to start up the database? Log sequence number in the ib_logfiles is 49468, less than the log sequence number in the first system tablespace file header, 1630815.
2019-09-18 16:14:28 0 [Note] InnoDB: Starting a batch to recover 112 pages from redo log.
2019-09-18 16:14:28 0 [ERROR] InnoDB: We scanned the log up to 1603190. A checkpoint was at 49468 and the maximum LSN on a database page was 294254698. It is possible that the database is now corrupt!
2019-09-18 16:14:28 0 [ERROR] InnoDB: Page [page id: space=0, page number=7] log sequence number 285914931 is in the future! Current system log sequence number 1603199.
2019-09-18 16:14:28 0 [ERROR] InnoDB: Your database may be corrupt or you may have copied the InnoDB tablespace but not the InnoDB log files. Please refer to https://mariadb.com/kb/en/library/innodb-recovery-modes/ for information about forcing recovery.


text:
Q: Use C to exit ssh session to linux I"m running a program that runs over ssh session. Meaning I connect to a linux using putty, the program starts, using the /etc/bash.bashrc file. At some point the program suppose to end and with it the ssh session via putty should disconnect.
What I"ve done untill now with a code below, and it doesn't work: the program  exits, and stays in linux shell, meaning the putty is connected. What I expected is the command "exit" to end the putty ssh session.
 char file_name[20];
 pid_t pid = fork();
        if (pid == 0)
        {
            printf("Starting vi\r\n");
            char external_cmd[200] = "vi ";
            strcat(external_cmd, file_name);
            system(external_cmd);
        } else
        {
            waitpid(pid,0,0);
            printf("Exit..\r\n");
            system("exit");

        }

thanks for the help.

A: The easiest solution is to start your C program with exec so that it replaces the shell. The SSH session will naturally end when the program exits.
$ exec your_program

A: This code doesn't accomplish anything:
system("exit");

system() runs a child process under sh:

The system() function shall behave as if a child process were
  created using fork(), and the child process invoked the sh utility
  using execl() as follows:
execl(<shell path>, "sh", "-c", command, (char *)0);

So, your call to system() starts a sh process, which then executes the exit command you passed to it - and the child process exits, doing nothing to the parent processes.
You can kill the parent shell, though, by obtaining the PID of the parent process with getppid() and then calling kill() to kill it:
#include <unistd.h>
#include <signal.h>
...
pid_t parent = getppid();
kill( parent, SIGKILL );

SIGKILL is probably a bit extreme - it kills a process immediately, with no chance for the process to clean up after itself, but it will work (unless you're running a non-root setuid child process in this case - if you don't know what that is, don't worry about it.).  SIGTERM is a less-extreme signal, but since it can be caught or blocked it isn't guaranteed to end a process.  SIGINT is the equivalent of CTRL-C and may also work, but again the process can catch or ignore the signal.  SIGQUIT can also be used, but it's purpose is to cause the process to quit and dump a core file, which you probably don't want.


text:
Q: Do I need spf in amazon SES? I know its recommended to use it but in the email headers of my test emails I already get "Received SPF: pass" . Its obviously looking up their SPF. So do I need to add a SPF record in my domain? I'm using Interspire, postfix and the amazon ses smtp. And the DNS of my registrar.

A: No, it's not required to publish SPF records for your domain, SPF Checks two things:

*

*HELO identity (optional)

*Mail from Identity

SES bydefault changes the mail from and return path address as message-id@amazonses.com so that it can receive Bounce back and complaint and can keep track of it.
Your SPF and DKIM will always pass using SES, The only problem is when the domain you're using to send email has DMARC publish, in DMARC, it requires the policy evaluation and check the mailfrom domain part vs the From header domain part and thats when it fails, as long as your sending domain doesn't have DMARC record published, you don't need to publish any DKIM or SPF record because SES takes care of it.
In case DMARC is used, you need to create a custom mail from in SES like mail.domain.com and you need to publish SPF record to include amazonses.com in spf reccord because using when custom mail from, the mail from address would be written as messageid@mail.domain.com and recipient will look for spf record for mail.domain.com.
In any case, custom mail from and easy dkim should be used for higher deliverability.

A: You should do the SPF and DKIM Settings for Your Amazon SES Account.
Just go to Your domain or your email address.
and you will find that option there.
Get the DKIM Records and put it in your DNS (as CNAME) Records.
It will work.
And Your Answer is "YES" it is always required to maximize the delivery in INBOX.

A: If you want to send it from different email addresses from the same domain, then you can verify your domain. so once domain is verified you can use any email address from that domain as sender email.
Yes, you definitely have to add all the records generated when you try to verify your domain.
That'll ensure the deliverability.


text:
Q: Expression with Triple Sum of Kronecker Delta I am trying to evaluate the following term.
I already have asked a question to a similar problem.
$$\sum_{c_1}^N\sum_{c_2\ge c_1}^N\sum_{c_3\ge c_1}^N \delta_{c_2,c_k}P_{c_1,c_2}\delta_{c_3,c_l}P_{c_1,c_3}$$
I tried it myself: So one can group some terms:
$$\sum_{c_1}^N\sum_{c_2\ge c_1}^N\delta_{c_2,c_k}P_{c_1,c_2}\sum_{c_3\ge c_1}^N \delta_{c_3,c_l}P_{c_1,c_3}$$
The terms inside the last two sums are only non-zero if $c_{2,3}=c_{k,l}$ because of the kronecker deltas. But how can i simplify this further?
Edit: So I analyzed myself, but I am not sure if it is correct. Basically as I said the terms inside the last two sums contribute only if the kronecker delta doesn't vanish. But it doesn't vanish trivially if $c_{2,3}=c_{k,l}$, because the sums are not over all elements. So one gets in addition the conditions $c_1\le c_l, c_1\le c_k$. Which can be summarized as: $$c_1\le min(c_l,c_k)$$
So the final results must be:
$$\sum_{c_1\le min(g_l,g_k)}P_{c_1,c_l}P_{c_1,c_k}$$
Could somebody please confirm my result?


text:
Q: Why two independent sample t-test and two-way ANOVA give different results on same data set? I have two samples of data collected under two different treatments:
sam.a <- c( 0.1333333, 0.2258065, 0.1944444, 0.2894737)
sam.b <- c(0.137931, 0.093750, 0, 0)

I first tried t.test in R:
t.test(sam.a,sam.b)

which gave me result as below (p < 0.05):
    Welch Two Sample t-test

data:  sam.a and sam.b
t = -4.1497, df = 5.8602, p-value = 0.006329
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -0.27151717 -0.06935361
sample estimates:
mean of x mean of y
0.1994576 0.3698930

When I tried the same data using anova in R:
aov(sam.a ~ sam.b)

The results became insignificant (p > 0.05):
            Df   Sum Sq  Mean Sq F value Pr(>F)
sam.b        1 0.005970 0.005970   1.778  0.314
Residuals    2 0.006714 0.003357

Can someone solve this problem for me? Many thanks!

A: If you want to do the equivalent ANOVA you have to set it up differently.
t.test(sam.a,sam.b, var.equal = TRUE)$p.value
#[1] 0.01819264

You need to construct a variable, which describes to which vector a value belongs:
samples <- c(sam.a, sam.b)
fac <- c(rep("a", length(sam.a)),
         rep("b", length(sam.b)))

summary(aov(samples ~ fac))[[1]]$"Pr(>F)"[1]
#[1] 0.01819264

You used samp.a as the dependent and samp.b as the independent and basically did a regression between them, which is not the same at all. (Note that aov internally always does OLS regression and calculates the relevant sums of squares from the regression result.)
If you assume unequal variances in the t-test (as the default does) and do a Welch test, standard ANOVA won't reproduce the p-value exactly.


text:
Q: Suppose f: R to R is differentiable and its derivative has absolute value smaller than 1 for all x in R. Suppose $f\colon\mathbb{R} \to \mathbb{R}$ is differentiable and its derivative has absolute value smaller than $1$ for all $x \in \mathbb{R}$. Is it true that $f$ is a contraction*?
*That is, that there exists $c < 1$ such that $\lvert f(x)- f(y)\rvert \leq c\lvert x- y\rvert$ for all $x,y\in \mathbb{R}$.


text:
Q: Does the async attribute represent a contract to not change the DOM? One of the reasons that browsers block parsing and rendering of a page when they find a <script> tag is to allow scripts to modify the DOM.
From Load Non-blocking JavaScript with HTML5 Async and Defer:

The defer Attribute
The defer attribute makes a solemn promise to the browser. It states
  that your JavaScript does not contain any document.write or DOM
  modification nastiness:
 The browser will begin to
  download file.js and other deferred scripts in parallel without
  stopping page processing.defer was implemented in Internet Explorer
  version 4.0 — over 12 years ago! It's also been available in Firefox
  since version 3.5.While all deferred scripts are guaranteed to run in
  sequence, it's difficult to determine when that will occur. In theory,
  it should happen after the DOM has completely loaded, shortly before
  the DOMContentLoaded event. In practice, it depends on the OS and
  browser, whether the script is cached, and what other scripts are
  doing at the time.

As I understand it, the defer attribute represents a 'contract' with the browser your script isn't going to change the DOM. Is the same also true of async?
(Of course, this doesn't prevent you loading scripts that change the DOM using async - you just have to structure your code so DOM-changing is done on document ready or load).

A: No, it does not, and don't trust that article you linked to. The defer and async attributes tell the browser when the script should be executed and whether parsing should wait while loading it. It makes no promise.
So, using either of those attributes would prevent document.write from writing at the script's position, and, in the case of defer, enables straight DOM modification to affect DOM elements that are parsed after the script element.


text:
Q: FATAL EXCEPTION: JavaBridge - Only the original thread that created a view hierarchy can touch its views I'm developing the cordova plugin for playing Media.(Video)
I try to play video using mediaPlayer Class for Android.
There was no error, I succeeded to the prepare step.
But in "onPrepared" function, i try to use "mediaController.show() & mediaPlayer.start()" api,
There is error [logcat] :
E/AndroidRuntime: FATAL EXCEPTION: JavaBridge
                  Process: yongju.example.media, PID: 3779
                  android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
                      at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6891)
                      at android.view.ViewRootImpl.recomputeViewAttributes(ViewRootImpl.java:3247)
                      at android.view.ViewGroup.recomputeViewAttributes(ViewGroup.java:1324)
                      at android.view.ViewGroup.recomputeViewAttributes(ViewGroup.java:1324)
                      at android.view.ViewGroup.recomputeViewAttributes(ViewGroup.java:1324)
                      at android.view.View.setFlags(View.java:11580)
                      at android.view.View.setKeepScreenOn(View.java:7554)
                      at android.view.SurfaceView$1.handleMessage(SurfaceView.java:135)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.os.HandlerThread.run(HandlerThread.java:61)

There are my codes [cordova plugin] :
package com.cordova.plugin.toast;

import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;

import android.content.Context;

import android.media.AudioManager;
import android.net.Uri;
import android.os.Looper;
import android.util.Log;

import org.apache.cordova.CallbackContext;

import org.apache.cordova.CordovaActivity;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;

import android.view.View;
import android.widget.FrameLayout;
import android.widget.MediaController;

import android.media.MediaPlayer;
import android.view.SurfaceHolder;

import android.os.Handler;

import android.widget.VideoView;

import java.io.IOException;

public class Media extends CordovaPlugin implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener, MediaController.MediaPlayerControl {

    class MediaPlayerState {
        protected String NONE = "NONE";
        protected String IDLE = "IDLE";
        protected String READY = "READY"; // prepared
        protected String PLAYING = "PLAYING";
        protected String PAUSED = "PAUSED";
    }

    private MediaPlayerState mPlayerState = new MediaPlayerState();
    private static final String TAG = "Media";

    private FrameLayout fraLayout;
    private CordovaWebView webView;

    private MediaPlayer mediaPlayer;
    private MediaController mcontroller;

    private VideoView videoView;
    private SurfaceHolder surfaceHolder;
    private String src, state;

    private CordovaActivity nowActivity;
    private Context context;

    private CallbackContext callbackContext;

    @Override
    public void initialize(CordovaInterface cordova, CordovaWebView webView) {
        super.initialize(cordova, webView);
        this.webView = webView;
        nowActivity = (CordovaActivity)this.cordova.getActivity();
        context = this.cordova.getActivity().getApplicationContext();
    }

    @Override
    public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
        this.callbackContext = callbackContext;
        if (action.equals("create")) {
            Log.v(TAG, "**************Success 'create'**************");

            createVideoContainer();
        }

        else if (action.equals("open")) {
            Log.v(TAG, "**************Success 'open'**************");

            openVideoStream(args);
        }

        else if (action.equals("play")) {
            Log.v(TAG, "**************Success 'play'**************");

            playVideoStream(args);
        }

        else if (action.equals("stop")) {
            Log.v(TAG, "**************Success 'stop'**************");

            stopVideoStream(args);
        }

        else if (action.equals("pause")) {
            Log.v(TAG, "**************Success 'pause'**************");

            pauseVideoStream(args);
        }

        else {
            return false;
        }

        return true;
    }

    private void createVideoContainer() {
        state = mPlayerState.NONE;

        fraLayout = (FrameLayout) this.webView.getView().getParent();
        FrameLayout.LayoutParams fraLayoutParam = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        fraLayoutParam.setMargins(80, 80, 80, 80);

        videoView = new VideoView(cordova.getActivity());
        videoView.setLayoutParams(fraLayoutParam);
        videoView.setVisibility(View.VISIBLE);

        surfaceHolder = videoView.getHolder();

        surfaceHolder.addCallback(this);

        mcontroller = new MediaController(this.cordova.getActivity());
    }

    private void openVideoStream(JSONArray args) throws JSONException {
        String id = args.getString(0);
        src = args.getString(1);
        Log.v(TAG, "media::open() - id =" + id);
    }

    private void playVideoStream(JSONArray args) throws JSONException {
        String id = args.getString(0);
        Log.v(TAG, "media::play() - id =" + id);

        if(state == mPlayerState.IDLE) {
            // If 'prepared' is not completed, must again 'prepare'
        }
        else{
            mediaPlayer.start();
            state = mPlayerState.PLAYING;
        }
    }

    private void pauseVideoStream(JSONArray args) throws JSONException {
        String id = args.getString(0);
        Log.v(TAG, "media::pause() - EVENT_STATE -> PAUSED");

        mediaPlayer.pause();
        state = mPlayerState.PAUSED;
    }

    private void stopVideoStream(JSONArray args) throws JSONException {
        String id = args.getString(0);
        Log.v(TAG, "media::stop() - EVENT_STATE -> IDLE");

        mediaPlayer.stop();
        state = mPlayerState.IDLE;
        //videoView.setVisibility(View.INVISIBLE);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        Log.v(TAG, "*********************************************************media::surfaceCreated - Start MediaPlayer Object create : " + src);
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
        }
        else {
            mediaPlayer.reset();
        }

        state = mPlayerState.IDLE;

        try {
            String fileName = "android.resource://yongju.example.media/raw/sample";
            Uri fileUri = Uri.parse(fileName);

            mediaPlayer.setDataSource(context, fileUri); // for testing In local file
            mediaPlayer.setDisplay(holder);      // Call Screen
        } catch (IOException e) {
            e.printStackTrace();
        }

        mediaPlayer.setOnCompletionListener(completionListener);
        mediaPlayer.setOnVideoSizeChangedListener(sizeChangeListener);
        mediaPlayer.setOnPreparedListener(this);
        mediaPlayer.setScreenOnWhilePlaying(true);
        //mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

        mediaPlayer.prepareAsync();                      // Ready for loading Video
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        Log.v(TAG, "*********************************************************media::surfaceChanged");
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        Log.v(TAG, "*********************************************************media::surfaceDestroyed");
        mediaPlayer.release();
    }

    MediaPlayer.OnCompletionListener completionListener = new MediaPlayer.OnCompletionListener() {
        /**
         * Listener for playing video is completed
         * @param mediaPlayer : Now mediaPlayer that is controlled
         */
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
        }
    };

    MediaPlayer.OnVideoSizeChangedListener sizeChangeListener = new MediaPlayer.OnVideoSizeChangedListener() {
        @Override
        public void onVideoSizeChanged(MediaPlayer mediaPlayer, int width, int height) {
        }
    };

    @Override
    public void onPrepared(MediaPlayer mp) {
        Log.v(TAG, "*********************************************************media::prepare completed");
        state = mPlayerState.READY;
        mcontroller.setMediaPlayer(this);
        mcontroller.setAnchorView(videoView);
        mcontroller.setEnabled(true);

        cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (cordova.getActivity().isFinishing() == false) {
                    mcontroller.show();
                    mp.start();
                }

            }
        });
    }

    @Override
    public void start() {
        mediaPlayer.start();
    }

    @Override
    public void pause() {
        mediaPlayer.pause();
    }

    @Override
    public int getDuration() {
        return 0;
    }

    @Override
    public int getCurrentPosition() {
        return mediaPlayer.getDuration();
    }

    @Override
    public void seekTo(int pos) {
        mediaPlayer.seekTo(pos);
    }

    @Override
    public boolean isPlaying() {
        return mediaPlayer.isPlaying();
    }

    @Override
    public int getBufferPercentage() {
        return 0;
    }

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

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

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

    @Override
    public int getAudioSessionId() {
        return 0;
    }
}
          return mediaPlayer.getDuration();
        }

        @Override
        public void seekTo(int pos) {
            mediaPlayer.seekTo(pos);
        }

        @Override
        public boolean isPlaying() {
            return mediaPlayer.isPlaying();
        }

        @Override
        public int getBufferPercentage() {
            return 0;
        }

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

        @Override
        public boolean canSeekBackward() {

    return true;
    }

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

    @Override
    public int getAudioSessionId() {
        return 0;
    }
}

Plz tell me why.

A: You are trying to start MediaPlayer not from the main thread. Just call runOnUiThread function and everything should be alright.

A: activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //your implementetion
            }
        });


text:
Q: Spring @ComponentScan not detecting REST controller After searching various similar question on StackOverflow, I have determined that most people suffering from this issue are not properly scanning the module where their controller lives.  Some solutions call for combining the files that are to be scanned into the same module as the Application (which works), but I do not want to move any of my .java files.  Instead, I'd like to make @ComponentScan work.
I have the following project structure
Project
      |
      settings.gradle
      build.gradle
      module1
            |
            src/main/java/com.test.application
            |                                |
            |                                Application.java
            |                                SwaggerConfig.java
            build.gradle
      module2
            |
            src/main/java/com.test.service
            |                            |
            |                            Service.java
            |                            Controller.java
            build.gradle

Application.java
@SpringBootApplication
@ComponentScan("com.test")
public class Application {

  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }
}

Note here that I am scanning com.test in my component scan.  I can't find anything in the @ComponentScan documentation (or on StackOverflow) that would suggest I am using @ComponentScan incorrectly.
Controller.java
@RestController
@RequestMapping("/test")
public class GearParsingController {
  private SomeService someService;

  @Autowired
  public SomeController(SomeService someService) {
    this.someService = someService;
  }

  @GetMapping("/path")
  public ResponseEntity<String> getSomeService() {
    return new ResponseEntity<String>("Default message", HttpStatus.OK);
  }
}

Project build.gradle
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:2.1.6.RELEASE")
    }
}

subprojects {
    repositories {
        mavenCentral()
    }

    apply plugin: 'java'
    apply plugin: 'idea'
    apply plugin: 'org.springframework.boot'
    apply plugin: 'io.spring.dependency-management'
}

module1 build.gradle
dependencies {
    implementation project(':module2')

    implementation group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.1.6.RELEASE'
}

module2 build.gradle
dependencies {
    implementation group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.1.6.RELEASE'

    testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.5.0-RC2'
}

When I try to access my endpoints at localhost:8080/test/path I am met with:
{
    "timestamp": "2019-06-29T19:19:52.275+0000",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/test/path"
}

When launching the program in debug mode, I am given the following output:
2019-06-29 13:58:58.345  INFO 8272 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-06-29 13:58:58.387  INFO 8272 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-06-29 13:58:58.387  INFO 8272 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.21]
2019-06-29 13:58:58.522  INFO 8272 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-06-29 13:58:58.522 DEBUG 8272 --- [           main] o.s.web.context.ContextLoader            : Published root WebApplicationContext as ServletContext attribute with name [org.springframework.web.context.WebApplicationContext.ROOT]
2019-06-29 13:58:58.522  INFO 8272 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1786 ms
2019-06-29 13:58:58.544 DEBUG 8272 --- [           main] o.s.b.w.s.ServletContextInitializerBeans : Mapping filters: characterEncodingFilter urls=[/*], hiddenHttpMethodFilter urls=[/*], formContentFilter urls=[/*], requestContextFilter urls=[/*]
2019-06-29 13:58:58.545 DEBUG 8272 --- [           main] o.s.b.w.s.ServletContextInitializerBeans : Mapping servlets: dispatcherServlet urls=[/]
2019-06-29 13:58:58.583 DEBUG 8272 --- [           main] o.s.b.w.s.f.OrderedRequestContextFilter  : Filter 'requestContextFilter' configured for use
2019-06-29 13:58:58.583 DEBUG 8272 --- [           main] .s.b.w.s.f.OrderedHiddenHttpMethodFilter : Filter 'hiddenHttpMethodFilter' configured for use
2019-06-29 13:58:58.583 DEBUG 8272 --- [           main] s.b.w.s.f.OrderedCharacterEncodingFilter : Filter 'characterEncodingFilter' configured for use
2019-06-29 13:58:58.584 DEBUG 8272 --- [           main] o.s.b.w.s.f.OrderedFormContentFilter     : Filter 'formContentFilter' configured for use
2019-06-29 13:58:58.896 DEBUG 8272 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : 5 mappings in 'requestMappingHandlerMapping'
2019-06-29 13:58:58.990  INFO 8272 --- [           main] pertySourcedRequestMappingHandlerMapping : Mapped URL path [/v2/api-docs] onto method [public org.springframework.http.ResponseEntity<springfox.documentation.spring.web.json.Json> springfox.documentation.swagger2.web.Swagger2Controller.getDocumentation(java.lang.String,javax.servlet.http.HttpServletRequest)]
2019-06-29 13:58:59.045 DEBUG 8272 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Patterns [/**/favicon.ico] in 'faviconHandlerMapping'
2019-06-29 13:58:59.128  INFO 8272 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-06-29 13:58:59.146 DEBUG 8272 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : ControllerAdvice beans: 0 @ModelAttribute, 0 @InitBinder, 1 RequestBodyAdvice, 1 ResponseBodyAdvice
2019-06-29 13:58:59.257 DEBUG 8272 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Patterns [/webjars/**, /**] in 'resourceHandlerMapping'
2019-06-29 13:58:59.263 DEBUG 8272 --- [           main] .m.m.a.ExceptionHandlerExceptionResolver : ControllerAdvice beans: 0 @ExceptionHandler, 1 ResponseBodyAdvice
2019-06-29 13:58:59.442  INFO 8272 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
2019-06-29 13:58:59.481  INFO 8272 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
2019-06-29 13:58:59.519  INFO 8272 --- [           main] s.d.s.w.s.ApiListingReferenceScanner     : Scanning for api listing references

So, my question is: Why isn't ComponentScan detecting my REST controller?

A: Make your files this way:
Project build.gradle (removed spring plugin application to all module projects)

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:2.1.6.RELEASE")
    }
}

subprojects {
    repositories {
        mavenCentral()
    }

    apply plugin: 'java'
    apply plugin: 'idea'
}

module1 build.gradle (apply spring plugins and bootJar goal)

dependencies {
    implementation project(':module2')

    implementation group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.1.6.RELEASE'
}

apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

bootJar {
    baseName = 'module1'
    version = '0.0.1-SNAPSHOT'
}

module2 build.gradle (added jar goal)

dependencies {
    implementation group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.1.6.RELEASE'
}

jar {
    baseName = 'module2'
    version = '0.0.1-SNAPSHOT'
}

settings.gradle

include 'module1'
include 'module2'

Point is that we want second module built as normal jar and the main module as spring boot runnable. With that setup just gradle build and then gradle bootRun from main project folder.

A: I think if you want to pick up your controller from the "com.test" package use the basePackages option of the @ComponentScan:
@ComponentScan(basePackages = "com.test")

A: Your main application Application.java is under the directory com.test.application , which means that when the springboot application starts up by default the @SpringBootApplication annotation will look for beans and configurations under the packgae com.test.application . In the springboot documentation it is specified that we should place the Main application under the root package so that spring scans everything under it.

@SpringBootApplication is a convenience annotation that adds all of
  the following:

*

*@Configuration tags the class as a source of bean definitions for the    application context.

*@EnableAutoConfiguration tells Spring Boot to start adding beans    based on classpath settings, other beans, and various property
  settings.

*Normally you would add @EnableWebMvc for a Spring MVC app, but Spring    Boot adds it automatically when it sees spring-webmvc on the
  classpath. This flags the application as a web application and
  activates key behaviors such as setting up a DispatcherServlet.

*@ComponentScan tells Spring to look for other components,    configurations, and services in the hello package, allowing it to
  find the controllers.

So, to fix your issue try moving your main application to the root of your package
com.test or you could use the annotation @ComponentScan to specify which all packages are needed to be scanned like :
@ComponentScan(basePackages = "com.test")

A: According to Spring Boot convention, controllers have to be in the com.test.controller package.


text:
Q: Promotion of parameters during overloading I was studying about overloading and I am completely getting confused with promotions. I looked at few articles in SO (implicit conversion sequence in function overloading) and I am sure some more are available, but could not find the right article. I was also referring to  http://www.dcs.bbk.ac.uk/~roger/cpp/week20.htm.
I was looking at C++ Programming special edition by Stroustrup and came across following explanation.

Finding the right version to call from a set of overloaded functions
  is done by looking for a best match between the type of the argument
  expression and the parameters (formal arguments) of the functions. To
  approximate our notions of what is reasonable, a series of criteria
  are tried in order: 1 Exact match [2] Match using promotions;
  [3] Match using standard conversions [4] Match using user-defined
  conversions [5] Match using the ellipsis ......

void print(int);
void print(double);
void print(long);
void print(char);
void h(char c, int i, short s, float f)
{
    print(s); // integral promotion: invoke print(int)
    print(f); // float to double promotion: print(double)
}

I wrote below code. I was thinking that if I call the function with value of 1,  func1(long) will be called because promotion takes place. But I get error message "error: call of overloaded 'func1(int)' is ambiguous". It is not calling the function with even unsigned char type of variable.
Also if I pass call func1(3.4f), func1(double) is called and promotion takes place as per my expectation. Why 1 is not promoted to long int but why float is promoted to double? What integer promotions takeplace?
    void func1(unsigned char speed)
    {
        cout<<"Func1 with unsigned char: speed =" << speed <<" RPM\n";
    }

   void func1(long speed)
    {
        cout<<"Func1 with long Int: speed =" << speed <<" RPM\n";
    }

    void func1(double speed)
    {
        cout<<"Func1 with double: speed =" << speed <<" RPM\n";
    }

    int main(void)
    {
        func1(1);
        func1(3.4f);
        return(0);
    }

A: The standard specifies:

[C++11: 4.13/1]: ("Integer conversion rank")
Every integer type has an integer conversion rank defined as follows:

*

*[..]

*The rank of long long int shall be greater than the rank of long int, which shall be greater than the rank of int, which shall be greater than the rank of short int, which shall be greater than the rank of signed char.

*The rank of any unsigned integer type shall equal the rank of the corresponding signed integer type.

*[..]

which calls for ambiguity in your example.
As for func1(3.4f);, it's just a promotion from float to double, and that's the best match, since the other two overloaded methods have long and unsigned char.
Also check this table:

where a subclause specifies:

[conv.fpprom]: (7.7 Floating-point promotion )

*

*A prvalue of type float can be converted to a prvalue of type double. The value is unchanged.

*This conversion is called floating-point promotion.


text:
Q: Calculate the percentage or rows that are not NULL for each column in a table grouped by another column I have a regular table [customer_table] with some null values that looks like this
id | customer | country | col0 | col1 | col2 |
==============================================
1  | foo      | USA     | NULL | foo  | bar  |
2  | bar      | USA     | foo  | NULL | foo  |
3  | foo2     | CANADA  | bar  | col1 | NULL |
4  | bar2     | GERMANY | foo  | NULL | bar  |
5  | bar3     | CANADA  | foo  | foo  | bar  |
6  | bar4     | UK      | bar  | foo  | bar  |
7  | bar5     | UK      | bar  | bar  | bar  |

And I want to calculate the percentage of non-null values for each column grouped by country
country | col0%  | col1% | col2% |
==================================
USA     | 50%    | 50%  | 100%   |
GERMANY | 100%   | 0%   | 100%   |
CANADA  | 100%   | 100% | 50%    |
UK      | 100%   | 100% | 100%   |

This is what I tried to to
select TOTAL.[country],
[count_col0]*100/[count_total] as [col0%],
[count_col1]*100/[count_total] as [col1%]
from (
    (select [country], COUNT(*) as [count_total] from [customer_table]
     where [country] <> '' group by [country]) TOTAL
    left join
     (select [country], COUNT(*) as [count_col0] from [customer_table]
     where [country] <> '' and [col0] <> '' group by [country]) T_COL0
     on T_COL0.[country] = TOTAL.[country]
    left join
     (select [country], COUNT(*) as [count_col1] from [customer_table]
     where [country] <> '' and [col1] <> '' group by [country]) T_COL1
     on T_COL1.[country] = TOTAL.[country]
)

It works, but I have a lot of columns, and I don't think it is a good solution

A: Just use aggregation.  The simplest method is:
select country,
       count(col1) * 1.0 / count(*),
       count(col2) * 1.0 / count(*),
       count(col3) * 1.0 / count(*)
from customertable
group by country

A: DECLARE @customertable TABLE (country NVARCHAR(100), col1 BIGINT, col2 BIGINT, col3 BIGINT)

INSERT INTO @customertable
(country, col1, col2, col3)
    VALUES
    (N'USA', 0, null, 0)
    ,(N'USA', 0, null, 0)
    ,(N'USA', null, null, 0)
    ,(N'USA', 0, 0, null)
    , (N'CA', 0, null, 0)
    ,(N'CA', 0, null, 0)
    ,(N'CA', null, null, 0)
    ,(N'CA', 0, 0, null)
;WITH DistinctCountries AS (
SELECT DISTINCT Country
FROM @customertable
)

SELECT Country
, col1/(total*1.0) as [col1pct]
, col2/(total*1.0) as [col2pct]
, col3/(total*1.0) as [col3pct]
FROM DistinctCountries AS DistinctCountries
OUTER APPLY (
SELECT
  SUM(CASE WHEN col1 IS NULL THEN 0 ELSE 1 END) col1
  ,SUM(CASE WHEN col2 IS NULL THEN 0 ELSE 1 END) col2
  ,SUM(CASE WHEN col3 IS NULL THEN 0 ELSE 1 END) col3
  ,COUNT(1) as Total
FROM @customertable AS CountApply
WHERE CountApply.Country = DistinctCountries.Country
)MainCount

if you have a unique list of countries, probably best to do that.
if you have a ton of columns, probably best to create a dynamic SQL query to automatically create each CASE and tokenize it.. or .. a dynamic pivot query.

A: You are looking for a COUNT(DISTINCT xxx) / COUNT(*) pattern here.
Now, when you have lots of columns to cover you could look them up in the INFORMATION_SCHEMA.COLUMNS system table and generate your query you want to run like this:
SELECT
  'SELECT country'
UNION ALL
SELECT
      CONCAT(', (100 * COUNT(DISTINCT ', COLUMN_NAME, ')) / COUNT(*) AS [', COLUMN_NAME, '%]')
FROM  INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'customer_table'
      AND TABLE_SCHEMA = 'dbo'
      AND COLUMN_NAME NOT IN ('id', 'customer', 'country')
UNION ALL
SELECT
  'FROM dbo.customer_table GROUP BY country;'

Which would result in:
SELECT country
, (100 * COUNT(DISTINCT col0)) / COUNT(*) AS [col0%]
, (100 * COUNT(DISTINCT col1)) / COUNT(*) AS [col1%]
, (100 * COUNT(DISTINCT col2)) / COUNT(*) AS [col2%]
FROM dbo.customer_table GROUP BY country;


text:
Q: In itunes connect, can the app seller be different than the name on the associated bank account? I have a personal developer account and my friend is connecting his bank account to my apple development account.
Because I have developed the app so I want my name to be under the name of my app on app store, not my friend's name.
Can I still be the seller of the app even though payment is to my friend's bank account?

A: This seems like a legal arrangement that would be fine with Apple according to this section of the banking help:

Does the Account Holder Name field have to match the Legal Entity Name field?
No, the account holder name for your bank account doesn't have to match the legal entity name for your agreement.
The information you provide for the Account Holder Name field, though, should exactly match the name your bank has on file for your account. Make sure this is correct to avoid any issues with your payments. If you're not sure what name your bank has on file, check a recent bank statement or ask your bank.

My only recommendation would be to have a written contract with your friend lining out whatever agreement you have with them. Your entering banking information to Apple is a legal agreement, so you'll have a hard time getting any money back should you ever expect that once Apple pays the bank account you elected. As long as you control the account, you can update the bank (subject to 24 hours or more delay of course when you elect a change) but you'd likely not be able to claw back or get relief if you don't intend for them to get all the proceeds.
You would certainly be in hot water once the taxes are due on these funds since you are the seller no matter which bank receives the funds. I would pay someone to advise you alone on the banking and tax decisions before relinquishing any payments to an account you don't totally control.


text:
Q: How can I persist go 1.11 modules in a Docker container? I am migrating a Go 1.10 app to Go 1.11. This also includes migrating from dep to mod for managing dependencies.
As the application depends on a database, I am using a docker-compose to set up the local development environment. With Go 1.10 I simply mounted the local repository (including the vendor folder) into the correct location in the container's GOPATH:
web:
  image: golang:1.10
  working_dir: /go/src/github.com/me/my-project
  volumes:
    - .:/go/src/github.com/me/my-project
  environment:
    - GOPATH=/go
    - PORT=9999
  command: go run cmd/my-project/main.go

Since Go 1.11 ditches GOPATH (when using modules that is) I thought I could just do the following:
web:
  image: golang:1.11rc2
  working_dir: /app
  volumes:
    - .:/app
  environment:
    - PORT=9999
  command: go run cmd/my-project/main.go

This works, but every time I docker-compose up (or any other command that calls through to the Go tool) it will resolve and re-download the dependency tree from scratch. This does not happen (rather only once) when I run the command outside of the container (i.e. on my local OS).
How can I improve the setup so that the Docker container persists the modules being downloaded by the go tool?

A: This is not mentioned in the wiki article on modules, but from reading the updated docs on the go tool, I found out that when using Go modules, the go tool will still use GOPATH to store the available sources, namely $GOPATH/pkg/mod.
This means that for my local dev setup, I can 1. define the GOPATH in the container and 2. mount the local $GOPATH/pkg/mod into the container's GOPATH.
web:
  image: golang:1.11rc2
  working_dir: /app
  volumes:
    - .:/app
    - $GOPATH/pkg/mod:/go/pkg/mod
  environment:
    - GOPATH=/go
    - PORT=9999
  command: go run cmd/my-project/main.go

A: You can use a volume instead of your local GOPATH. the docker-compose.yml is like:
version: '3'

services:
  web:
    image: golang:1.11
    working_dir: /app
    volumes:
        - .:/app
        - cache:/go
    environment:
        - PORT=9999
    command: go run cmd/my-project/main.go

volumes:
  cache:

The volume cache is going to persist all the changes on the GOPATH for the container.


text:
Q: Анимация цвета виджета, PyQt5 Есть такая анимация, подкиньте еще методов на примере этого кода.
import sys
from PyQt5.QtWidgets import QWidget, QApplication, QFrame, QPushButton, QGraphicsColorizeEffect
from PyQt5.QtCore import QPropertyAnimation
from PyQt5.QtGui import QColor

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()

        self.resize(500, 500)
        self.initUi()

    def initUi(self):
        self.color = QGraphicsColorizeEffect()
        self.color.setColor(QColor('black'))

        self.frame = QFrame(self)
        self.frame.setGeometry(100, 100, 100, 100)
        self.frame.setStyleSheet('background-color: black;')
        self.frame.setGraphicsEffect(self.color)

        self.button = QPushButton(self)
        self.button.setGeometry(250, 100, 100, 100)
        self.button.setText('Анимация')
        self.button.clicked.connect(self.Animation)

    def Animation(self):
        self.anim = QPropertyAnimation(self.color, b"color")
        self.anim.setDuration(3000)
        self.anim.setStartValue(QColor('black'))
        self.anim.setEndValue(QColor('red'))
        self.anim.start()

if __name__=="__main__":
    app = QApplication([])
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

A: Пример 1:
from PyQt5.QtWidgets import (QWidget, QApplication, QPushButton,
        QLabel, QHBoxLayout, QSizePolicy)
from PyQt5.QtGui import QColor
from PyQt5.QtCore import QPropertyAnimation, pyqtProperty
import sys

class MyLabel(QLabel):
    def __init__(self, text):
        super().__init__(text)

    def _set_color(self, col):
        palette = self.palette()
        palette.setColor(self.foregroundRole(), col)
        self.setPalette(palette)

    color = pyqtProperty(QColor, fset=_set_color)

class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        hbox = QHBoxLayout(self)
        self.button = QPushButton("Start", self)
        self.button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        hbox.addWidget(self.button)
        hbox.addSpacing(40)

        self.label = MyLabel("Hello World")
        font = self.label.font()
        font.setPointSize(35)
        self.label.setFont(font)
        hbox.addWidget(self.label)

        self.anim = QPropertyAnimation(self.label, b"color")
        self.anim.setDuration(2500)
        self.anim.setLoopCount(2)
        self.anim.setStartValue(QColor(0, 0, 0))
        self.anim.setEndValue(QColor(255, 255, 255))
        self.button.clicked.connect(self.anim.start)

if __name__ == "__main__":
    app = QApplication([])
    ex = Example()
    ex.setGeometry(300, 300, 380, 250)
    ex.setWindowTitle('Color anim')
    ex.show()
    app.exec_()

Пример 2:
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class BlinkButton(QPushButton):
    def __init__(self, *args, **kwargs):
        QPushButton.__init__(self, *args, **kwargs)
        self.default_color = self.getColor()

    def getColor(self):
        return self.palette().color(QPalette.Button)

    def setColor(self, value):
        if value == self.getColor():
            return
        palette = self.palette()
        palette.setColor(self.backgroundRole(), value)
        self.setAutoFillBackground(True)
        self.setPalette(palette)

    def reset_color(self):
        self.setColor(self.default_color)

    color = pyqtProperty(QColor, getColor, setColor)

class Widget(QWidget):
    def __init__(self):
        super(Widget, self).__init__()
        layout = QVBoxLayout(self)
        self.button_stop = BlinkButton("Stop")
        layout.addWidget(self.button_stop)

        self.button_start = QPushButton("Start", self)
        layout.addWidget(self.button_start)

        self.animation = QPropertyAnimation(self.button_stop, b"color", self)
        self.animation.setDuration(1000)
        self.animation.setLoopCount(100)
        self.animation.setStartValue(self.button_stop.default_color)
        self.animation.setEndValue(self.button_stop.default_color)
        self.animation.setKeyValueAt(0.1, QColor(0,255,0))

        self.button_start.clicked.connect(self.animation.start)
        self.button_stop.clicked.connect(self.stop)

    def stop(self):
        self.animation.stop()
        self.button_stop.reset_color()

if __name__ == "__main__":
    app = QApplication([])
    w = Widget()
    w.resize(300,200)
    w.show()
    app.exec_()


text:
Q: Exclude some samplers in JMeter html dashboard report in non gui mode I have two http request samplers inside a Thread Group.
I would like to ignore the first sampler when I run the tests in non GUI mode (cli).
The main reason is to ignore the first sampler in the generated HTML report.
I still need the Sampler 1 to run under the hood even if I filter when running it in cli mode.

A: Send in non GUI extra parameter/JMeter property as -JignoreFirstSampler
Add JSR223 PostProcessor as a child of the first Sampler with code to ignore sampler in results:
    if (props.get("ignoreFirstSampler") != null) {
        prev.setIgnore()
    }

Sampler 1 will still executed, but won't be shown in report

A: *

*Put your HTTP Request samplers under the Transaction Controllers

*Click Tools -> Export transactions for report

*Amend generated jmeter.reportgenerator.exporter.html.series_filter property  value and remove "unwanted" transactions

*Run JMeter in non-GUI mode and provide this jmeter.reportgenerator.exporter.html.series_filter property via -J command-line argument like:
jmeter -Jjmeter.reportgenerator.exporter.html.series_filter="^(Sampler 2)(-success|-failure)?$" -n -t test.jmx -f -l result.jtl -e -o dashboard

*That's it, HTML Reporting Dashboard will contain only Sampler 2 transaction results
More information:

*

*Configuring JMeter

*Reporting configuration


text:
Q: How to create separate Pandas DataFrames for each CSV file and give them meaningful names? I've searched thoroughly and can't quite find the guidance I am looking for on this issue so I hope this question is not redundant. I have several .csv files that represent raster images. I'd like to perform some statistical analysis on them so I am trying to create a Pandas dataframe for each file so I can slice 'em dice 'em and plot 'em...but I am having trouble looping through the list of files to create a DF with a meaningful name for each file.
Here is what I have so far:
import glob
import os
from pandas import *

#list of .csv files
#I'd like to turn each file into a dataframe
dataList = glob.glob(r'C:\Users\Charlie\Desktop\Qvik\textRasters\*.csv')

#name that I'd like to use for each data frame
nameList = []
for raster in dataList:
    path_list = raster.split(os.sep)
    name = path_list[6][:-4]
    nameList.append(name)

#zip these lists into a dict

dataDct = {}
for k, v in zip(nameList,dataList):
    dataDct[k] = dataDct.get(k,"") + v
dataDct

So now I have a dict where the key is the name I want for each dataframe and the value is the path for read_csv(path):
{'Aspect': 'C:\\Users\\Charlie\\Desktop\\Qvik\\textRasters\\Aspect.csv',
 'Curvature': 'C:\\Users\\Charlie\\Desktop\\Qvik\\textRasters\\Curvature.csv',
 'NormalZ': 'C:\\Users\\Charlie\\Desktop\\Qvik\\textRasters\\NormalZ.csv',
 'Slope': 'C:\\Users\\Charlie\\Desktop\\Qvik\\textRasters\\Slope.csv',
 'SnowDepth': 'C:\\Users\\Charlie\\Desktop\\Qvik\\textRasters\\SnowDepth.csv',
 'Vegetation': 'C:\\Users\\Charlie\\Desktop\\Qvik\\textRasters\\Vegetation.csv',
 'Z': 'C:\\Users\\Charlie\\Desktop\\Qvik\\textRasters\\Z.csv'}

My instinct was to try variations of this:
for k, v in dataDct.iteritems():
    k = read_csv(v)

but that leaves me with a single dataframe, 'k' , that is filled with data from the last file read in by the loop.
I'm probably missing something fundamental here but I am starting to spin my wheels on this so I'd thought I'd ask y'all...any ideas are appreciated!
Cheers.

A: Are you trying to get all of the data frames separately in a dictionary, one data frame per key? If so, this will leave you with the dict you showed but instead will have the data from in each key.
dataDct = {}
for k, v in zip(nameList,dataList):
    dataDct[k] = read_csv(v)

So now, you could do this for example:
dataDct['SnowDepth'][['cola','colb']].plot()

A: Unclear why you're overwriting your object here I think you want either a list or dict of the dfs:
df_list=[]
for k, v in dataDct.iteritems():
    df_list.append(read_csv(v))

or
df_dict={}
for k, v in dataDct.iteritems():
    df_dict[k] = read_csv(v)


text:
Q: Eclipse RCP: Action "RESET_PERSPECTIVE" shows previously hidden menu entries Due to a migration from Eclipse 3.0 to 4.4, it was necessary to hide unnecessary menu entries like "open file" and "key assist".
I hide those by calling hideActionSet in my postWindowOpen method
public void postWindowOpen(IWorkbenchWindowConfigurer configurer)
{
    IWorkbenchWindow[] windows = PlatformUI.getWorkbench().getWorkbenchWindows();

    for(int i = 0; i < windows.length; ++i)
    {
        IWorkbenchPage page = windows[i].getActivePage();
        if(page != null)
        {
            page.hideActionSet("org.eclipse.ui.actionSet.keyBindings");
                page.hideActionSet("org.eclipse.ui.actionSet.openFiles");
        }
    }
}

This works fine so far. But when rearrange my perspective, then reset the perspective and then change to another perspective, the unnecessary menu entries show up again.
I tried fixing this by calling the same code in my perspectiveActivated and perspectiveChanged methods. The methods hideActionSet are reached, but they don't have an effect.
Here are those two methods:
public void perspectiveActivated(IWorkbenchPage page, IPerspectiveDescriptor perspective)
{
    if( perspective.getId().equals(m_PerspektivenID) || m_PerspektivenID.equals(STANDARDAKTION))
    {
        setEnabled( true );
    }
    else
    {
        setEnabled( false );
    }

    if(page != null)
    {
        page.hideActionSet("org.eclipse.ui.actionSet.keyBindings");
        page.hideActionSet("org.eclipse.ui.actionSet.openFiles");
    }
}

public void perspectiveChanged(IWorkbenchPage page, IPerspectiveDescriptor perspective, String changeId)
{
    if(changeId.equals(IWorkbenchPage.CHANGE_RESET_COMPLETE))
    {
        if(page != null)
        {
            page.hideActionSet("org.eclipse.ui.actionSet.openFiles");
            page.hideActionSet("org.eclipse.ui.actionSet.keyBindings");
        }
    }
}

A: Thank you, it worked. I just used to wrong ID. When you use the method hideActionSet you have to use the ID org.eclipse.ui.actionSet.openFiles, but when you want to hide them using activities you have to use org.eclipse.ui.edit.text.openLocalFile.
So in conclusion:

*

*hiding with hideActionSet: use The active contribution item identifier

*hiding with activities: use The active action definition identifier


text:
Q: What techniques to avoid conditional branching do you know? Sometimes a loop where the CPU spends most of the time has some branch prediction miss (misprediction) very often (near .5 probability.) I've seen a few techniques on very isolated threads but never a list. The ones I know already fix situations where the condition can be turned to a bool and that 0/1 is used in some way to change. Are there other conditional branches that can be avoided?
e.g. (pseudocode)
loop () {
  if (in[i] < C )
    out[o++] = in[i++]
  ...
}

Can be rewritten, arguably losing some readability, with something like this:
loop() {
  out[o] = in[i]  // copy anyway, just don't increment
  inc = in[i] < C  // increment counters? (0 or 1)
  o += inc
  i += inc
}

Also I've seen techniques in the wild changing && to & in the conditional in certain contexts escaping my mind right now. I'm a rookie at this level of optimization but it sure feels like there's got to be more.

A: The generalization of the example you give is "replace conditional evaluation with math"; conditional-branch avoidance largely boils down to that.
What's going on with replacing && with & is that, since && is short-circuit, it constitutes conditional evaluation in and of itself.  & gets you the same logical results if both sides are either 0 or 1, and isn't short-circuit.  Same applies to || and | except you don't need to make sure the sides are constrained to 0 or 1 (again, for logic purposes only, i.e. you're using the result only Booleanly).

A: At this level things are very hardware-dependent and compiler-dependent.  Is the compiler you're using smart enough to compile < without control flow?  gcc on x86 is smart enough; lcc is not.  On older or embedded instruction sets it may not be possible to compute < without control flow.
Beyond this Cassandra-like warning, it's hard to make any helpful general statements. So here are some general statements that may be unhelpful:

*

*Modern branch-prediction hardware is terrifyingly good.  If you could find a real program where bad branch prediction costs more than 1%-2% slowdown, I'd be very surprised.

*Performance counters or other tools that tell you where to find branch mispredictions are indispensible.

*If you actually need to improve such code, I'd look into trace scheduling and loop unrolling:

*

*Loop unrolling replicates loop bodies and gives your optimizer more control flow to work with.

*Trace scheduling identifies which paths are most likely to be taken, and among other tricks, it can tweak the branch directions so that the branch-prediction hardware works better on the most common paths.  With unrolled loops, there are more and longer paths, so the trace scheduler has more to work with

*I'd be leery of trying to code this myself in assembly.  When the next chip comes out with new branch-prediction hardware, chances are excellent that all your hard work goes down the drain.  Instead I'd look for a feedback-directed optimizing compiler.

A: An extension of the technique demonstrated in the original question applies when you have to do several nested tests to get an answer.  You can build a small bitmask from the results of all the tests, and the "look up" the answer in a table.
if (a) {
  if (b) {
    result = q;
  } else {
    result = r;
  }
} else {
  if (b) {
    result = s;
  } else {
    result = t;
  }
}

If a and b are nearly random (e.g., from arbitrary data), and this is in a tight loop, then branch prediction failures can really slow this down.  Can be written as:
// assuming a and b are bools and thus exactly 0 or 1 ...
static const table[] = { t, s, r, q };
unsigned index = (a << 1) | b;
result = table[index];

You can generalize this to several conditionals.  I've seen it done for 4.  If the nesting gets that deep, though, you want to make sure that testing all of them is really faster than doing just the minimal tests suggested by short-circuit evaluation.

A: GCC is already smart enough to replace conditionals with simpler instructions. For example newer Intel processors provide cmov (conditional move). If you can use it, SSE2 provides some instructions to compare 4 integers (or 8 shorts, or 16 chars) at a time.
Additionaly to compute minimum you can use (see these magic tricks):
min(x, y) = x+(((y-x)>>(WORDBITS-1))&(y-x))

However, pay attention to things like:
c[i][j] = min(c[i][j], c[i][k] + c[j][k]);   // from Floyd-Warshal algorithm

even no jumps are implied is much slower than
int tmp = c[i][k] + c[j][k];
if (tmp < c[i][j])
    c[i][j] = tmp;

My best guess is that in the first snippet you pollute the cache more often, while in the second you don't.

A: In my opinion if you're reaching down to this level of optimization, it's probably time to drop right into assembly language.
Essentially you're counting on the compiler generating a specific pattern of assembly to take advantage of this optimization in C anyway.  It's difficult to guess exactly what code a compiler is going to generate, so you'd have to look at it anytime a small change is made - why not just do it in assembly and be done with it?

A: Using Matt Joiner's example:
if (b > a) b = a;

You could also do the following, without having to dig into assembly code:
bool if_else = b > a;
b = a * if_else + b * !if_else;

A: I believe the most common way to avoid branching is to leverage bit parallelism in reducing the total jumps present in your code. The longer the basic blocks, the less often the pipeline is flushed.
As someone else has mentioned, if you want to do more than unrolling loops, and providing branch hints, you're going to want to drop into assembly. Of course this should be done with utmost caution: your typical compiler can write better assembly in most cases than a human. Your best hope is to shave off rough edges, and make assumptions that the compiler cannot deduce.
Here's an example of the following C code:
if (b > a) b = a;

In assembly without any jumps, by using bit-manipulation (and extreme commenting):
sub eax, ebx ; = a - b
sbb edx, edx ; = (b > a) ? 0xFFFFFFFF : 0
and edx, eax ; = (b > a) ? a - b : 0
add ebx, edx ; b = (b > a) ? b + (a - b) : b + 0

Note that while conditional moves are immediately jumped on by assembly enthusiasts, that's only because they're easily understood and provide a higher level language concept in a convenient single instruction. They are not necessarily faster, not available on older processors, and by mapping your C code into corresponding conditional move instructions you're just doing the work of the compiler.

A: Most processors provide branch prediction that is better than 50%. In fact, if you get a 1% improvement in branch prediction then you can probably publish a paper. There are a mountain of papers on this topic if you are interested.
You're better off worrying about cache hits and misses.

A: This level of optimization is unlikely to make a worthwhile difference in all but the hottest of hotspots. Assuming it does (without proving it in a specific case) is a form of guessing, and the first rule of optimization is don't act on guesses.


text:
Q: Laravel Database Eloquent Relation queries for one model with multiple tables I've defined a Model for multiple tables as seen here:
Laravel 4: can one model serve several DB tables?
I have many tables for the model Data:

*

*data_2000

*data_2001
...
And handle them in this model:
class Data extends \Eloquent {

    public function __construct($year, array $attributes = array())
    {
        parent::__construct($attributes);
        $this->table = 'data_' . $year;
    }

    public function country()
    {
        return $this->belongsTo('Country');
    }
}

There's a One To Many relation with Country
class Country extends \Eloquent {

    protected $table = 'countries';

    public function data($year)
    {
        return $this->hasMany('Data('.$year.')');
    }

    public function region()
    {
        return $this->belongsTo('Region');
    }
}

As I expected there's a missing argument if just return $this->hasMany('Data') so I tried $this->hasMany('Data('.$year.')') but of course it return an error of:

Class 'Data(2000)' not found

Is there a workaround to get all the Country->data from all the tables or just one table using eloquent's methods? Or should I just run multiple queries for all the years with a where('country_id', '=', $country->id)?
Thanks in advance, any ideas are appreciated.


text:
Q: Elixir: what is the meaning of nil I'm learning elixir and I was wondering if nil is the same as null in JavaScript, if not, what is the meaning?

A: They are similar, both are often used to denote the absence of a value. In JavaScript, !!null evaluates to false, while in Elixir, !!nil evaluates to false. Just like JavaScripts null, you can use nil as a "falsy" value in a boolean context, for instance:
if nil do
  IO.puts "foo"
else
  IO.puts "bar"
end

will print "bar"
I can't think of many differences between the two, other than perhaps a few corner cases. For instance, null > 0 evaluates to false in JavaScript, while nil > 0 evaluates to true in Elixir.


text:
Q: is there a way to compile a JavaScript string, store and use variables from the compiled string? I am trying to build an HTML preprocessor that would help me out with my electron project. I have looked at other preprocessors and none meets my expectations so I decided to create mine. Here is an example of the code format or syntax.
{{@import Button from './components/Out'}}

{{@Component {
    name: 'Button',
    useStrict: true,
    props: {
        name: '',
        className: '',
        values: ''
    }
}}}
    {{@include './index', {
        name: props.name
    }}}
    <button class={{props.className}}>{{{name}}}</button>

    {{@if (avatar !== null || avatar !== undefined) }}
        <li class={{`${props.name}`}}>
            this is a test {{avatar}}

        {{@each field in values}}

                {{field.name}}

                     power level: {{field.power}}

        {{/each}}
    {{/if}}

    <Button name="" text="" value="" href=""/>

{{/Component}}

//---- the problem is below; compiling the code and storing the values of each global variable
<@
    let avatar = 'My avatar is on the run';

    const values = [{name: 'Batman', power: '200kilowatts'}, {name: 'Spiderman', power: '60watts'}];

    const func = () => {
        let name = 'David';
        script = name;
    }
@>

I have parsed the entire file or code, and everything works fine but compiling that script.

NB: I used Esprima to extract the script's global variables.

First, I thought of using the window object to compile the script, that way, I can get each variable's value by calling window[variableName] I am using node js so I imported Jsdom but unfortunately it didn't work, window[variableName] kept returning undefined.
Then I thought of eval, but that also brought up issues because I can't make use of the variables in eval, so I thought of dynamically creating those variables first or saving them in the global object, but it certainly won't work, at least as far as I know.
Sorry for the long description.. the summary is, that I need to be able to get each variable's value after the string has been compiled. I have tried finding js-engines or js-compilers that can be installed with npm but not much luck with that. Also just in case, someone says they found a similar preprocessor, please, I have done my research and there isn't any similar. I placed a lot of functionality to this preprocessor and it's an important component for my electron project... So any help is perfect.... thank you for your time.

A: Here is a solution i come up with :

it allow to exec js code using Function and export variables using return, also ctx can be accessed within the code with this
at the end of the execution ctx looks like :
{
    "globalCtxVar": "testVar",
    "test1": "var",
    "test2": "const",
    "test3": "let"
}

So in the end it's the same as eval but with greater control of input/outputs since it's a function


text:
Q: Cursor change on icon-font characters I use entypo icon font for things like open and close buttons on a webpage. Classes like entypo-desiredcharacter are assinged to html elements, the icon itself is addes as a pseudo element. On hover, I do not want the cursor to change to the edit-text thing, but just stay the same. I tried
[class*="entypo-"], [class*="entypo-"]:before {
    cursor: pointer;
}

It didn't work. What else can I do?

A: well cursor: pointer will show a hand.  have you tried cursor:none - also why is it on :before, shouldn't it be on :hover?  Sorry if I misunderstand the question.


text:
Q: Sticky footer not updating in IE7 This is a link to apparently the "best" solution to a sticky footer (which only docks when there is little content on the page).
http://ryanfait.com/sticky-footer/
When you resize the window in any other browser (Firefox, chrome I tested with) the footer moves with the window. In IE7 it doesn't move, and you need to refresh the page to have it position itself correctly.
Google seemed to be able to do it, so I'm wondering, how have they managed to do this and I cant? Are they using JavaScript, or is there an elegant CSS solution I'm missing?

A: I've used Chris Coryier's solution before and never had any issues with IE: http://css-tricks.com/snippets/css/sticky-footer/
CSS
* { margin:0; padding:0; }

html, body, #wrap { height: 100%; }

body > #wrap {height: auto; min-height: 100%;}

#main { padding-bottom: 150px; }  /* must be same height as the footer */

#footer {
    position: relative;
    margin-top: -150px; /* negative value of footer height */
    height: 150px;
    clear:both;
}

/* CLEAR FIX*/
.clearfix:after {content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}
.clearfix {display: inline-block;}
/* Hides from IE-mac \*/
* html .clearfix { height: 1%;}
.clearfix {display: block;}
/* End hide from IE-mac */

HTML

A: This is the one I use, it has worked for me always.
http://www.cssstickyfooter.com/es/


text:
Q: Loop through each table in database and get first three digits of one column I am trying to create a table that will show me each table name, and the first three characters of the ID column (every table has this column), and then put that data into a table.  We are using this to help map dependencies in our Salesforce Org which is replicated onto SQL using dbAMP.  I adapted the code below as far as I could, and am looking for help to finish it.
UPDATE: The first half of the question is resolved, and the code now runs to give the first three characters of the ID.  I still could use help in converting this code to spool the results into one single table.
USE Salesforce
GO

IF OBJECT_ID('tempdb..#tempResults') IS NOT NULL
DROP TABLE #tempResults

CREATE TABLE #tempResults
(
[Object_ID] VARCHAR(3)
--, [org] VARCHAR(100)
, [Table_Name] VARCHAR(100)
)

DECLARE cur CURSOR FOR
SELECT
    'SELECT DISTINCT LEFT(' + QUOTENAME(c.COLUMN_NAME) + ',3) AS
[Object_ID], '''
--+ QUOTENAME(TABLE_CATALOG) + ' as [Org], '
+ QUOTENAME(TABLE_NAME) + ''' as [Table_Name] FROM '
+ QUOTENAME(TABLE_CATALOG) + '.' + QUOTENAME(TABLE_SCHEMA) + '.'  + QUOTENAME(TABLE_NAME)

FROM INFORMATION_SCHEMA.COLUMNS AS c
WHERE
c.[DATA_TYPE] IN ('nchar','varchar', 'nvarchar')
AND c.[CHARACTER_MAXIMUM_LENGTH] = 18
and c.TABLE_NAME not like '%upload%'
and c.TABLE_NAME not like '%Delta%'
and c.TABLE_NAME not like '%Update%'
and c.TABLE_NAME not like '%Previous%'
and C.COLUMN_NAME = 'ID'

DECLARE @cmd VARCHAR(MAX);
OPEN cur;

FETCH NEXT FROM cur INTO @cmd;
WHILE @@FETCH_STATUS = 0
BEGIN
    --PRINT @cmd
    INSERT INTO #tempResults
    EXEC(@cmd);
FETCH NEXT FROM cur INTO @cmd;
END

CLOSE cur;
DEALLOCATE cur;

SELECT * FROM #tempResults

I'm not getting the Column ID trimmed to the first 3 characters, and it's not outputting to a table.  I'm not that familiar with cursors so I'd appreciate any help.  Thanks,

A: You're really close. The way you've got your select written it's actually trimming the column name and then appending that 3-character column name to the string, rather than getting the first three characters from the actual data within the ID column.
Try updating your select so the LEFT brackets the QUOTENAME(c.COLUMN_NAME) inside the string, like below. This small change made your script work on my salesforce installation.
SELECT
    'SELECT DISTINCT LEFT(' + QUOTENAME(c.COLUMN_NAME) + ',3) AS '
    + QUOTENAME(TABLE_CATALOG + '.' + TABLE_SCHEMA + '.' + TABLE_NAME) + ' FROM '
    + QUOTENAME(TABLE_CATALOG) + '.' + QUOTENAME(TABLE_SCHEMA) + '.'
    + QUOTENAME(TABLE_NAME)
FROM INFORMATION_SCHEMA.COLUMNS AS c
WHERE
    c.[DATA_TYPE] IN ('nchar','varchar', 'nvarchar')
    AND c.[CHARACTER_MAXIMUM_LENGTH] = 18
    and c.TABLE_NAME not like '%upload%'
    and c.TABLE_NAME not like '%Delta%'
    and c.TABLE_NAME not like '%UPdate%'
    and c.TABLE_NAME not like '%Previous%'
    and C.COLUMN_NAME = 'ID'

Update to answer part two:
First you'll need a destination table - I've used a temporary table, but this will work just fine as a permanent table.
I've adjusted the code to output two columns instead of one: IDSubstring (your 3-character ID portion) and SourceTable (this is exactly the same information that you were using as a column name previously). This way we know which table the ID portion belongs to.
Then, inside the cursor, instead of just executing, we do this:
INSERT INTO #tempResults
EXEC(@cmd);

This will populate our table and give us selectable values.
CREATE TABLE #tempResults
(
    [IDSubstring] VARCHAR(3)
    , [SourceTable] VARCHAR(50)
)

DECLARE cur CURSOR FOR
SELECT
    'SELECT DISTINCT LEFT(' + QUOTENAME(c.COLUMN_NAME) + ',3) AS [IDSubstring], '''
    + QUOTENAME(TABLE_CATALOG + '.' + TABLE_SCHEMA + '.' + TABLE_NAME) + ''' as [SourceTable] FROM '
    + QUOTENAME(TABLE_CATALOG) + '.' + QUOTENAME(TABLE_SCHEMA) + '.'
    + QUOTENAME(TABLE_NAME)
FROM INFORMATION_SCHEMA.COLUMNS AS c
WHERE
    c.[DATA_TYPE] IN ('nchar','varchar', 'nvarchar')
    AND c.[CHARACTER_MAXIMUM_LENGTH] = 18
    and c.TABLE_NAME not like '%upload%'
    and c.TABLE_NAME not like '%Delta%'
    and c.TABLE_NAME not like '%UPdate%'
    and c.TABLE_NAME not like '%Previous%'
    and C.COLUMN_NAME = 'ID'

DECLARE @cmd VARCHAR(MAX);
OPEN cur;

FETCH NEXT FROM cur INTO @cmd;
WHILE @@FETCH_STATUS = 0
BEGIN
    --PRINT @cmd
    INSERT INTO #tempResults
    EXEC(@cmd);
FETCH NEXT FROM cur INTO @cmd;
END

CLOSE cur;
DEALLOCATE cur;

SELECT * FROM #tempResults

Update 2
You're correct in assuming it's an issue with the '''
The ''' is there because we need to build our string with single quotes inside of it.
As examples:
SELECT '' returns nothing
while SELECT '''' returns '
And SELECT 'This is an example''' will return This is an example'
So the ''' are part of a larger string definition started with the initial ' before "This" and can be broken down this way - the first two single quotes are the single quote we want to print within the string and the third single quote is the string terminating quote. If you just run the select statement and look at what it outputs, you can see where each single quote has been inserted into the string.
Updated SELECT is below.
SELECT
    'SELECT DISTINCT LEFT(' + QUOTENAME(c.COLUMN_NAME) + ',3) AS [Object_ID], '''
    + QUOTENAME(TABLE_CATALOG) + ''' as [Org], '''
    + QUOTENAME(TABLE_NAME) + ''' as [Table_Name] FROM '
    + QUOTENAME(TABLE_CATALOG) + '.' + QUOTENAME(TABLE_SCHEMA) + '.'  + QUOTENAME(TABLE_NAME)
FROM INFORMATION_SCHEMA.COLUMNS AS c
WHERE
c.[DATA_TYPE] IN ('nchar','varchar', 'nvarchar')
AND c.[CHARACTER_MAXIMUM_LENGTH] = 18
and c.TABLE_NAME not like '%upload%'
and c.TABLE_NAME not like '%Delta%'
and c.TABLE_NAME not like '%Update%'
and c.TABLE_NAME not like '%Previous%'
and C.COLUMN_NAME = 'ID'


text:
Q: Preventing Duplicate Items in list (sharepoint 2007) Is it possible to restrict, creation of duplicate list item in the Sharepoint 2007,
using Javascript in content editor webpart to validate when an list item is added?

A: You can use the list web service via JavaScript/jQuery and validate if an item exists.
I would prefer doing this on an event recevier (lot easier) but I guess you don't have a access to deploy code ?
here are some samples using JS http://darrenjohnstone.net/2007/05/28/querying-a-sharepoint-list-with-JavaScript/
and here using jQuery http://weblogs.asp.net/jan/archive/2009/04/09/calling-the-sharepoint-web-services-with-jquery.aspx

A: It wouldn't be trivial, but you can use javascript to carry out a web service call to lookup all items with the same title.
Have a look at the SPServices JavaScript library on CodePlex.


text:
Q: How to solve this ambiguity with Ragel? I am trying to parse the following format: (identifier/)?identifier(/keyword)?, with the first identifier as well as the keyword optional.  A keyword may not be used as an identifier.  For example, if up is a keyword, then:

*

*simple matches the second identifier,

*first/second matches first as the first identifier, and second as the second one,

*second/up matches second as a second identifier and up as a keyword.

Using Ragel with Ruby, I have defined the following FSM:
%%{
  machine simple;

  keyword = "up";
  separator = '/';
  ident_char = any - separator;
  identifier = ident_char+ - keyword;

  action start_string { $start_string = p }

  action first_string { puts "First: #{get_string(data, p)}" }
  action second_string { puts "Second: #{get_string(data, p)}" }

  action keyword_string { puts "Keyword: #{get_string(data, p)}" }

  main := ( identifier >start_string %first_string separator )?
         :> identifier >start_string %second_string
          ( separator keyword >start_string %keyword_string )?
  ;

}%%

%% write data;

def get_string(data, p)
  data[$start_string...p].pack("c*")
end

def parse(data)
  data = data.unpack("c*")
  eof = pe = data.length

  %% write init;
  %% write exec;
end

parse("first/second")
puts("---")
parse("second/up")

This gives the following output:
$ ragel -R simple.rl ; ruby simple.rb
Second: first
---
Second: second
Keyword: up

which is incorrect, as the first part should be First: first Second: second, but expected due to the :> priority I have given.
I have tried different combination of priorities, but haven't been able to get the expected result.  Is there a way of solving this problem with Ragel (i.e. can this be solved without lookahead)?

A: Try this as your main machine:
two_idents = identifier >start_first %first_string . separator . (identifier >start_second %second_string);

main := (two_idents | identifier >start_first %first_string) . ( separator . keyword )?;

The trouble is that the "first identifier" shares a prefix with the "second identifier", so trying to do a guarded concatenation shortcuts the first machine.  The union actually describes the match you're trying to do.


text:
Q: CPU killed by SIGXCPU using OpenCL and mono I have got very similar problem to this one stated here : Intel CPU OpenCL in Mono killed by SIGXCPU (Ubuntu)
Essentially, I have a very simple C# application using OpenCL (through OpenCL.Net wrapper, but it shouldn't make a difference as it is merely wrapping native functions and nothing more). In the code I just build kernel and then allocate a big array of floats.
To be more specific my platform: It is Ubuntu 12.04, OpenCL 1.1 (with CUDA) and mono 3.0.3.
Problem: When running my code through mono i get CPU LIMIT EXCEEDED error
Few things:

*

*If I set a breakpoint (in monodevelop) somewhere between building the kernel and allocation it works..

*Changing array size to small one also makes it work

Strace doesn't show anything useful. I tried also passing a callback to ClBuildProgram (to note: if I comment out line with ClBuildProgram it works).
Any ideas?

A: That's what worked for me in the end.
There is a major problem with mono - it uses SIGXCPU for GC handling (which is strange btw). Unfortunately OpenCL uses it as well so it conflicts.
Workaround is to modify mono code.
Go to source directory and grep -r SIGXCPU . In my mono (3.0.3) there were 2 imporant files
./libgc/pthread_stop_world.c:#   define SIG_THR_RESTART SIGXCPU
./mono/metadata/sgen-os-posix.c:const static int restart_signal_num = SIGXCPU;
Replace SIGXCPU with SIGWINCH and recompile. One note is that I am not sure if it didn't break something, but for now looks OK and OpenCL problem is gone. If it breaks something (like gui) replace SIGWINCH with different signal that you have (signals.h for signals defs)