Q: mysql select top n max values How can you select the top n max values from a table?
For a table like this:
column1  column2
   1       foo
   2       foo
   3       foo
   4       foo
   5       bar
   6       bar
   7       bar
   8       bar

For n=2, the result needs to be:
3
4
7
8

The approach below selects only the max value for each group.
SELECT max(column1) FROM table GROUP BY column2

Returns:
4
8

A: For n=2 you could
SELECT max(column1) m
FROM table t
GROUP BY column2
UNION
SELECT max(column1) m
FROM table t
WHERE column1 NOT IN (SELECT max(column1)
                      WHERE column2 = t.column2)

for any n you could use approaches described here to simulate rank over partition.
EDIT:
Actually this article will give you exactly what you need.
Basically it is something like this
SELECT t.*
FROM
   (SELECT grouper,
          (SELECT val
           FROM table li
           WHERE li.grouper = dlo.grouper
           ORDER BY
                 li.grouper, li.val DESC
           LIMIT 2,1) AS mid
   FROM
      (
      SELECT DISTINCT grouper
      FROM table
      ) dlo
   ) lo, table t
WHERE t.grouper = lo.grouper
      AND t.val > lo.mid

Replace grouper with the name of the column you want to group by and val with the name of the column that hold the values.
To work out how exactly it functions go step-by-step from the most inner query and run them.
Also, there is a slight simplification - the subquery that finds the mid can return NULL if certain category does not have enough values so there should be COALESCE of that to some constant that would make sense in the comparison (in your case it would be MIN of domain of the val, in article it is MAX).
EDIT2:
I forgot to mention that it is the LIMIT 2,1 that determines the n (LIMIT n,1).

A: If you are using mySQl, why don't you use the LIMIT functionality?
Sort the records in descending order and limit the top n i.e. :
SELECT yourColumnName FROM yourTableName
ORDER BY Id desc
LIMIT 0,3

A: Starting from MySQL 8.0/MariaDB support window functions which are designed for this kind of operations:
SELECT *
FROM (SELECT *,ROW_NUMBER() OVER(PARTITION BY column2 ORDER BY column1 DESC) AS r
FROM tab) s
WHERE r <= 2
ORDER BY column2 DESC, r DESC;

DB-Fiddle.com Demo

A: This is how I'm getting the N max rows per group in MySQL
SELECT co.id, co.person, co.country
FROM person co
WHERE (
SELECT COUNT(*)
FROM person ci
WHERE  co.country = ci.country AND co.id < ci.id
) < 1
;

how it works:

*

*self join to the table

*groups are done by co.country = ci.country

*N elements per group are controlled by ) < 1 so for 3 elements - ) < 3

*to get max or min depends on: co.id < ci.id

*

*co.id < ci.id - max

*co.id > ci.id - min

Full example here:
mysql select n max values per group/
mysql select max and return multiple values
Note: Have in mind that additional constraints like gender = 0 should be done in both places. So if you want to get males only, then you should apply constraint on the inner and the outer select


Q: What is gradle version which should be used with 3.6.1 android studio My question is simple, with android studio 3.6.1, my existing project have stopped working, I have tried to update below two files only, but no use.
Please note I am not a developer, So I will really appreciate, if solution can be given in layman terms.
I am getting below errors-
Caused by: org.gradle.api.internal.artifacts.ivyservice.DefaultLenientConfiguration$ArtifactResolveException: Could not resolve all artifacts for configuration ':classpath'.
Caused by: org.gradle.internal.resolve.ModuleVersionResolveException: Could not resolve com.android.tools.build:gradle:3.6.0.
Caused by: org.gradle.internal.resolve.ModuleVersionResolveException: No cached version of com.android.tools.build:gradle:3.6.0 available for offline mode.
apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    buildToolsVersion '28.6.0'
    defaultConfig {
        applicationId "dhritiapps.tulsiramayan"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 5
        versionName "1.04"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
   // implementation 'com.firebase:firebase-client-android:2.5.2'
    implementation 'com.google.android.gms:play-services-ads:19.0.1'
    testImplementation 'junit:junit:4.13'
}

second file
buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.6.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

A: I think this error is because your dependencies in your second file (version 3.6.0)  aren't the same as your Android Studio version (version 3.6.1) .
Try changing your dependencies to:
dependencies {
    classpath 'com.android.tools.build:gradle:3.6.1'
}


Q: Appending extra toolbar in fragment view In my application on the dashboard, there is an application bar that looks something like the image below.

As shown in the image, I have a toolbar that currently shows the Navigation drawer.
From the navigation drawer, I can navigate to a fragment A that replaces the TAB area under the toolbar as shown in the image below.

Is there any way I can add two toolbars like this where I can show the navigation drawer icon and back button together inside a fragment?

A: There is no best way to achieve what you are looking for, considering it goes against the Android Design Guidelines. Although not explicitly stated, the navigation drawer icon and the back button icon are never displayed together.
The theory behind this design is that navigation should be intuitive and predictable, displaying two navigational icons next to each other detracts from an intuitive user interface. The back button should be displayed if there is something to go back to. Though, the need for persistent navigation can be addressed in two different ways. Take Google's Gmail app for example.
By default the NavigationView supports using a swipe from the left edge of the screen as a gesture to open the navigation drawer. In the Gmail app, the navigation drawer icon is show while you are in any one of your inboxes. As soon as a message is selected, the navigation drawer icon is replaced with the back button. Though, you will notice that you can still access the drawer using the gesture stated previously.

On larger screens, the Gmail app supports a miniature navigation drawer. This drawer can remain in view without the need to display to navigational icons. Though this is a little more difficult to implement with the current support library, if you are looking to, this answer may help.

Finally, to answer your question, there is no built-in way to display a back button and a navigation drawer icon together. If you need to do so, the only way would be to use a "work-around", as you currently are.
Though, the only change I would probably make is to use an ImageButton rather than an ImageView. Then you can set the style of the button using style="?android:attr/actionButtonStyle" to mimic the look of an ActionBar button.

A: Just to update, for the time being, to achieve the above what I have done is.
I added a layout to my fragment file where I draw a custom back button like this:
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimaryDark20"
    android:orientation="horizontal"
    android:padding="15dp"
    android:weightSum="3">
    <ImageView
        android:id="@+id/backButton"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_gravity="left"
        android:layout_weight="0.2"
        android:src="@drawable/delete_icon" />
</LinearLayout>

When a person clicks on backImage, I call popBackStack.
   imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getFragmentManager().popBackStack();
        }
    });

The above code gives me the desired functionality.
Note, for the above to work you need to make sure you are adding your fragmentTransaction to backstack as below
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.home_content_layout,NAME_OFYOUR_FRAGMENT,"nameOfYourFragment");
transaction.addToBackStack(null);
transaction.commit();


Q: How to update to specific R version on Linux (Red Hat/CentOS), keeping the previous version? Perhaps a more accurate title would be: "How to switch from in-place (EPEL) R to side-by-side (version-specific) R installation on Linux (Red Hat/CentOS)?
A (possibly typical) upgrading R on Linux story...
History:
At some point in the past, I updated the version of R on our RHEL/CentOS 7 server using the default version pulled down by the yum package manager at that time. For example, sudo yum install R to version 3.5.2 at some point in early 2019. By default, this installs R at /usr/lib64/R for all users and completely replaces the 3.4.x version that had previously been installed there. Shiny Server was already installed, configured to run as user shiny, and it picked up the new version of R without a hitch.
Situation:
A year later, it is now time to bite the bullet and update the version of R that is running on the Linux server. Running yum check-upgrade R I find that the version available is 3.6.0. I actually want to install 3.6.3 AND I don't want to break all of my apps that are running on 3.5.2, so I need to use a different method.  Following the instructions found at https://docs.rstudio.com/resources/install-r/, I download the 3.6.3 .rpm file and install it. By default, this installs R at /opt/R/3.6.3/, leaving the 3.5.2 version as is. However, as soon as I complete the Create a symlink to R step, none of my shiny apps work:
sudo ln -s /opt/R/3.6.3/bin/R /usr/local/bin/R
sudo ln -s /opt/R/3.6.3/bin/Rscript /usr/local/bin/Rscript

This should not be surprising.  My shiny apps all rely upon several R packages that have not yet been installed for this new version of R.  I can quickly get my apps working again on the previous version (3.5.2) by removing these symlinks until after I've installed the necessary packages in the new version:
sudo rm /usr/local/bin/R
sudo rm /usr/local/bin/Rscript

Error messages in my shiny app log files (at /var/log/shiny-server/<app name>-<user>-<datetime>.log) confirm that the apps had failed to launch due to missing packages. To update the R packages in the shared library folder, I need to run the new version of R as sudo: sudo -i /opt/R/3.6.3/bin/R and install the necessary packages, e.g.,  install.packages(c("shiny","devtools","rmarkdown","shinydashboard","tidyverse")) in R.
Now that the R packages are installed, I can re-create the symlinks:
sudo ln -s /opt/R/3.6.3/bin/R /usr/local/bin/R
sudo ln -s /opt/R/3.6.3/bin/Rscript /usr/local/bin/Rscript

I verify that my apps are working with the new version of R.
Now I have some questions:
Question 1: After completing these steps, R --version still returns the old version (3.5.2).  But when I logged back in the following day, it opens 3.6.3.  Why?  Do I need to run a terminal command to get R --version to return the new version immediately or is opening a new terminal window the only way to achieve this?
Question 2: Running sudo R --version always returns the old version (3.5.2).  Running sudo which R returns /bin/R. Running more /bin/R reveals contents which state that it is "Shell wrapper for R executable." and has the "/usr/lib64/R" path hard-coded. I don't think I need this wrapper at this point. What is the recommended way to get these sudo commands to point to the new version?
I can make a backup copy of this file in my home directory (e.g., cp /bin/R ~/binR.backup) just in case, and then:

*

*Delete /bin/R?

*Replace /bin/R with a symlink to the new version (e.g., sudo ln -s /opt/R/3.6.3/bin/R /bin/R)?

*Re-install the 'old' version into /opt/R/3.5.2/ using a .rpm the same way I installed 3.6.3, install packages there, and then remove the /usr/lib64/R version (e.g., sudo yum remove R)?

Links to similar questions that I looked at but didn't answer my questions:

*

*How to upgrade R in Linux

*Change path in Linux

*How can I load a specific version of R in Linux

A: Question 1: I'm not sure why, but having multiple versions of R on your PATH can lead to unexpected situations like this. /usr/local/bin is usually ahead of /usr/bin in the PATH, so I would've expected R 3.6.3 to be found. Perhaps it has to do with Question 2.
Question 2: Some distros (like CentOS/RHEL) don't put /usr/local/bin on the PATH by default when using sudo. See https://unix.stackexchange.com/questions/8646/why-are-path-variables-different-when-running-via-sudo-and-su for details. The answers there describe several ways to add /usr/local/bin to the PATH when using sudo -- for example, modifying secure_path in /etc/sudoers to include /usr/local/bin like:
Defaults    secure_path = /usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

With R 3.6.3 ahead of the default system R in the PATH, you shouldn't have to delete /bin/R or /usr/bin/R. But eventually, I'd recommend installing multiple side-by-side versions of R the same way, using https://docs.rstudio.com/resources/install-r/, so it's easier to manage. The next time you install a new R version, you can just replace the symlinks in /usr/local/bin. The default system R (from EPEL) is meant to be the only R on a system, with in-place upgrades.
If you want to replace the default R 3.5.2 with a side-by-side R 3.5.2 (or 3.5.3), you could install R 3.5 from https://docs.rstudio.com/resources/install-r/, install all necessary packages, and have Shiny Server use the new R 3.5. Then uninstall the R from EPEL (R-core or R-core-devel) to fully switch over. From there, you could even create symlinks to R in /usr/bin instead of /usr/local/bin, and not worry about adding /usr/local/bin to the sudo PATH.


Q: Detect if "enable system diagnostics" is checked for conditionals in pipeline file and scripts I need to use the "enable system diagnostics" checkbox state in the pipeline run UI.   How do I check if it was checked?  For both pipeline YAML file and in a bash script.

A:
Detect if “enable system diagnostics” is checked for conditionals in pipeline file and scripts

The answer is yes.
If we enable the checkbox "enable system diagnostics" in the pipeline run UI, we could get following info in the build log:
agent.diagnostic : true

So, we could use this variable for conditionals in pipeline file and scripts.
But, there is a little different from the Boolean variables we usually use. If we do not enable the checkbox enable system diagnostics, Azure devops will not create this variable to overwrite the variable sysytem.debug. So this variable does not exist at this time, we cannot directly determine whether its value is true or false. We could  judge whether this value exists to judge its result.
Below is my test bash scripts for this condition:
- bash: |
   if [ -z "$(agent.diagnostic)" ]
   then
         echo "enable system diagnostics is Unchecked"
   else
         echo "enable system diagnostics is Checked"
   fi
  displayName: 'enable system diagnostics'

A: This is equivalent to the System.Debug variable. As an environment variable, SYSTEM_DEBUG.


Q: Angularjs ui.routing - add attribute to input elements before rendering HTML into ui-view I am using angular js - ui.router concept for SinglePageApplication Development.
When I click Page 1 and Page 2 link, then its respective html page will be rendered into 'ui-view' div. I want to add 'data-ng-blur' attribute into respective html page(Sample.html, Sample2.html), input controls while click 'ui-sref' link. I have give Document ready events in
that both htmls, But that's not fired. So there is any option for add attributes for input elements in loading html before its respective Controller called by ui-router.

Page 1

Page 2

A: You can use the concept of interceptor of $httpProvider i guess
$httpProvider.interceptors

A: JQuery reference must be added before the angular js reference. If we add reference in this order, then document ready events fired of loaded htmls will be fired. Issue solved now.


Q: excel macro, need an algorithm to compare two lists I need to make a macro to compare two columns looking for duplicate cells.
I'm currently using this simple double for loop algorithm
for i = 0 To ColumnASize
   Cell1 = Sheet.getCellByPosition(0,i)

   for j = 0 to ColumnBSi
   Cell2 = Sheet.getCellByPosition(1,j)

   ' Comparison happens here

   Next j
Next i

However, as I have 1000+ items in each column this algorithm is quite slow and inefficient. Does anyone here know/have an idea for a more efficient way to do this?

A: If you want to ensure that no string in col A is equal to any string in col B, then your existing algorithm is order n^2. You may be able to improve that by the following:
1) Sort col A or a copy of it (order nlogn)
2)Sort col B or a copy of it (order nlogn)
3) Look for duplicates by list traversal, see this previous answer (order n).
That should give you an order nlogn solution and I don't think you can do much better than that.


Q: Tensorflow: How to make the model train using `tfrecords` but test using `feed_dict` I recently completed training a Linear Regression model using a csv data.
The result of the trained data shown here:

However, I'm still dumbfounded as to how to use the model.
How do i give the model an "x" value such that it returns me a "y" value?
Code:
with tf.Session() as sess:
# Start populating the filename queue.
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)
    sess.run(init)

    # Fit all training data
    for epoch in range(training_epochs):
        _, cost_value = sess.run([optimizer,cost])

        #Display logs per epoch step
    if (epoch+1) % display_step == 0:
        c = sess.run(cost)
        print( "Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c), \
            "W=", sess.run(W), "b=", sess.run(b))

    print("Optimization Finished!")
    training_cost = sess.run(cost)
    print ("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n')

    #Plot data after completing training
    train_X = []
    train_Y = []
    for i in range(n_samples): #Your input data size to loop through once
        X, Y = sess.run([col1, pred]) # Call pred, to get the prediction with the updated weights
        train_X.append(X)
        train_Y.append(Y)
    #Graphic display
    df = pd.read_csv("battdata2.csv", header=None)
    X = df[0]
    Y = df[1]
    plt.plot(train_X, train_Y, linewidth=1.0, label='Predicted data')
    plt.plot(X, Y, 'ro', label='Input data')
    plt.legend()
    plt.show()

    print("train_X -- -")
    print(train_X)
    print("X -- -")
    print(X)
    print("train_Y -- -")
    print(train_Y)
    print("Y -- -")
    print(Y)

    save_path = saver.save(sess,   "C://Users//Shiina//model.ckpt",global_step=1000)
    print("Model saved in file: %s" % save_path)

coord.request_stop()
coord.join(threads)

Link to ipynb and csv files here.

A: You basically want the inputs to be fed to the network using queue runners during training, but then during inference you want to input it through feed_dict. This can be done by using tf.placeholder_with_default(). So when the inputs are not fed through feed_dict, it will read from the queues, otherwise it takes from 'feed_dict'. Your code should be like:
col1_batch, col2_batch = tf.train.shuffle_batch([col1, col2], ...
# if data is not feed through `feed_dict` it will pull from `col*_batch`
_X = tf.placeholder_with_default(col1_batch, shape=[None], name='X')
_y = tf.placeholder_with_default(col2_batch, shape=[None], name='y')


Q: C++ : error : taking address of temporary [-fpermissive] So basically I'm having the error : taking address of temporary and I didn't exactly know why.
I tried to simplify the code to just focus on the issue itself . The error occurs on the adress array.
main.cpp has these lines below :
   CPerson Student1("Test1", "street1.", "15a", 12045, "Berlin", 15, 9, 1989);
   CPerson Student2("Test2", "street2", "27", 29031, "Milan", 27, 5, 1991);
   CPerson Student3("Test3", "street3", "3-5", 12345, "Paris", 3, 11, 1987);
   CPerson Student4("Test4", "street4", "23", 19885, "Tokyo", 19, 7, 1985);
   CPerson *Studenten[4] = { &Student1, &Student2, &Student3, &Student4 };
   CAddress *Adressen[4] = { &(Student1.getAddress()), &(Student2.getAddress()),
                           &(Student3.getAddress()), &(Student4.getAddress()) }; //Error occurs here

caddress.hpp :
class CAddress
{
public:
    CAddress() = default;
    void print() const;
    friend class CPerson;

    ~CAddress(){};

private:
    std::string Street;
    std::string HouseNr;
    unsigned Zipcode;
    std::string City;
};

CPerson.hpp
class CPerson
{
public:
  CPerson() = default;
  CPerson(std::string m_Name, std::string m_Street,
          std::string m_HouseNr, unsigned m_Zipcode,
          std::string m_City, int m_Day, int m_Month, int m_Year);
  CAddress getAddress();
  void print() const;
  ~CPerson(){};

private:
  unsigned ID;
  std::string Name;
  CAddress Address;
  CDate Birthday;
};

CPerson.cpp
CPerson::CPerson(
    string m_Name,
    string m_Street,
    string m_HouseNr,
    unsigned m_Zipcode,
    string m_City,
    int m_Day, int m_Month, int m_Year)
{
    Name = m_Name;
    Address.Street = m_Street;
    Address.HouseNr = m_HouseNr;
    Address.Zipcode = m_Zipcode;
    Address.City = m_City;
    Birthday.Day = m_Day;
    Birthday.Month = m_Month;
    Birthday.Year = m_Year;
}

CAddress CPerson::getAddress()
{
    return this->Address;
}

I tried to delete the pointer on the array and the address on the elements of the array and it worked correctly but what I actually want is to work around it and leave the main as it is .


Q: Landing Page Built with Bootstrap 4 I have had a landing page built for me which is fairly simple layout. But the problem is the Banner Photo is swamping the page and I have to scroll to see completed page. Is there an adjustment I can make to HTML and/or CSS to reduce the height of the banner photo by about a third?

A: There are a lot of different approaches of doing this. I'll just show you one, that should perfectly fit your current page and needs.

(Inside your


Q: OCaml: How to construct a formatted string in pythonic way? All of these start from a simple idea: How to write python-style formatted string in ocaml.
pythoners could init a string as:
str = "this var: %s" % this_var
str2 = "this: %s; that: %s" % (this_var, that_var)

but ocaml's formatted string code as :
let str = Printf.sprintf "this var: %s" this_var
let str2 = Printf.sprintf "this: %s; that: %s" this_var that_var

I believed I can do sth to make the ocaml string formating code python-like
At first, I defined a function as below:
let (%) s x = Printf.sprintf s x

then, I can write directly as:
let str = "this: %s" % "sth"

but the simple function cannot handle more complex situations as two or more variables.
so I wanted to write a little complex function to make it perfectly simulate the python way.
I wrote it as below :
let (%) s li =
  let split_list = Str.full_split (regexp "%[a-z]") s in
  let rec fmt result_str s_list x_list = match s_list with
    | [] -> result_str
    | shd::stl -> match shd with
       | Text t ->  fmt (result_str^t) stl x_list
       | Delim d -> match x_list with
          | [] -> fmt result_str stl []
          | xhd::xtl -> fmt (result_str^(Printf.sprintf d xhd)) stl xtl
  in
  fmt "" split_list li

But the function just CANNOT work, because the type error and also ocaml's list cannot contains multiple types.
if you write sth like:  "name: %s; age: %d" % ["John"; 20] the ocaml compiler world laugh at the code and tell you some type ERROR.
Obviously, I must use Tuple to replace List. but I just do NOT konw how to tail-recursive a variable-length tuple.
any suggestion is welcomed. I have two question indeed.

*

*how to write a pythonic ocaml code to format string.

*If Ocaml cannot dynamically generate some string as format6 str and
pass it to sprintf? for code:
let s = "%s" in Printf.sprintf s "hello"
would generate ERROR info as:

Error: This expression has type string
  but an expression was expected of type
           ('a -> 'b, unit, string) format =
             ('a -> 'b, unit, string, string, string, string) format6

A: This is actually doable if your operator starts with a # character, since that character has a higher precedence than function application.
let (#%) = Printf.sprintf;;
val ( #% ) : ('a, unit, string) format -> 'a = <fun>
"Hello %s! Today's number is %d." #% "Pat" 42;;
- : string = "Hello Pat! Today's number is 42."

A: (1) I don't think there's a good way to do it that is going to be nicer than using Printf.sprintf directly. I mean, you can extend what you've already come up with:
let (%) = Printf.sprintf
let str3 = ("this: %s; that: %s; other: %s" % this_var) that_var other_var

which works, but is ugly because of the parentheses that are necessary for precedence.
(2) It's really hard to generate a format string at runtime because format strings are parsed at compile time. They may look like string literals, but they are actually a different type, which is "something format6". (it figures out whether you want a string or format string based on the inferred type) In fact, the exact type of a format string depends on what placeholders are in the format; that's the only way that it is able to type-check the number and types of format arguments. It's best not to mess with format strings because they are tied very heavily into the type system.

A: Why would one want to replace statically checked sprintf with some dynamic formatting?  OCaml's Printf is both compact in usage and safe at runtime. Compare that to C printf which is compact but unsafe and C++ streams which are safe but verbose. Python's format is no way better than C printf (except that you get exception instead of crashdump).
The only imaginable use-case is format string coming from external source. And it is usually better to move it to compile-time. If it is not possible, then only one needs to fallback to manual dynamic formatting with error-handling (as already said you cannot use Printf with dynamic format string). BTW one such case - internationalization - is covered with existing libraries. Generally, if one wants to dynamically combine multiple values of different types, then one has to wrap them with variants (like ['S "hello"; 'I 20]) and pattern-match at printing side.

A: You should check out OCaml Batteries Included's extended/extensible printf. I have the feeling that you can do what you want with it.

A:
If Ocaml cannot dynamically generate
  some string as format6 str and pass it
  to sprintf? for code:
let s = "%s" in Printf.sprintf s "hello"

What if we bypass the typing system...
external string_to_format :
 string -> ('a, 'b, 'c, 'd, 'e, 'f) format6 = "%identity"

let s = string_to_format "%s" in (Printf.sprintf s "hello" : string);;

I don't claim this to be the ultimate solution, but that's as far as I got after looking at the mailing list, http://pauillac.inria.fr/caml/FAQ/FAQ_EXPERT-eng.html#printf and ocaml's src.


Q: preventing users to create duplicate primary keys How would you prevent users to create duplicate primary keys?
My question is worded quite poorly so ill give an example to make it more clear (not sure how to put this in better words).
Let's say there are two users who are both trying to insert an item into our db. Now the ID (primary key) for this item is auto-incremented by 1 whenever a new item is inserted.
When two users try to insert an item into the db at the same time, the moment they insert the item, both items would be assigned with same ID but with different details and hence would cause a problem later when we look up that item b/c now there are two items with same ID.
How would you prevent this from Oracle?
Please comment if my question is not clear!


Q: Object binding for RESTful service using apache-cxf How to bind an object for RESTful service using Apache CXF?
I want to bind variables to an object from url params.

A: You could use @QueryParam. Take a look  here


Q: How do I convert list of strings to list of doubles in closure? How can I convert the values of 'mymap' to a list of Doubles instead of a list of Strings, at the same time as mymap is created?
(use '[clojure.string :only (join split)])
;(def raw-data (slurp "http://ichart.finance.yahoo.com/table.csv?s=INTC"))
;Downloaded and removed the first line
(def raw-data (slurp "table-INTC.csv"))

(def raw-vector-list
  (map
    #(split % #",")          ; anonymous map function to split by comma
    (split raw-data #"\n"))) ; split raw data by new line

(pr (take 1 raw-vector-list))

(def mymap
  (zipmap

    ;construct composite key out of symbol and date which is head of the list
    (map #(str "INTC-" %) (map first raw-vector-list))

    ;How do i convert these values to Double instead of Strings?
    (map rest raw-vector-list)))

(pr (take 1 mymap))

A: (def mymap
  (zipmap
    (map #(str "NAT-" %) (map first raw-vector-list))
    (map #(map (fn [v] (Double/parseDouble v)) %)
         (map rest raw-vector-list))))

(pprint (take 1 mymap))
-> (["NAT-1991-09-30" (41.75 42.25 41.25 42.25 3.62112E7 1.03)])

Another version
(def mymap
  (map (fn [[date & values]]
         [(str "NAT-" date)
          (map #(Double/parseDouble %) values)])
       ;; Drop first non-parsable element in raw-vector-list
       ;; ["Date" "Open" "High" "Low" "Close" "Volume" "Adj Close"]
       (drop 1 raw-vector-list)))

A: So for the tail/rest portion of this data. You are mapping an anonymous, map function, to a list of strings, and then mapping the type conversion to the elements in each sublist.
(def mymap
  (zipmap
   (map #(str "NAT-" %) (map first raw-vector-list))
   (map #(map (fn [v] (Double/parseDouble v)) %)
     (map rest raw-vector-list))))

How can I pull out the type conversion into a function like below...And then utilize my custom method?
(defn str-to-dbl [n] (Double/parseDouble n))

This code complains about nested #'s.
(def mymap
  (zipmap
   (map #(str "NAT-" %) (map first raw-vector-list))
   (map #(map #(str-to-double %)
     (map rest raw-vector-list))))


Q: Determining the memory size of a Heroku Dyno Worker from Ruby code? Is it possible to at lease estimate the total RAM of a Heroku Worker Dyno from Ruby code starting in it? I need this to use just the right number of processes via the https://github.com/salsify/delayed_job_worker_pool gem, so that the processes don't run out of memory.
I have noticed the following Environment variable provided for a Dyno: ENV[“HEROKU_RAM_LIMIT_MB”], and it appears to return correct values, but I'm not sure if it's "official" enough to rely on it. Does anybody know?


Q: Searching for keywords irrespective of special characters in dataframe I have a dataframe df with a column of some texts:
texts
This is really important(actually) because it has really some value
This is not at all necessary for it @ to get that

I want to perform a search and obtain the texts with keywords like "important(actually)", and it doesn't seem to work.
How do I to get that information?
I have used the following code:
df_filter=df[df.apply(lambda x: x.astype(str).str.contains(keyword, flags=re.I)).any(axis=1)]

But I am unable to get  such information.

A: Just escape the special characters in regex
df = pd.DataFrame({'texts': [
                             'This is really important(actually) because it has really some value',
                             'This is not at all necessary for it @ to get that']})

keyword = 'important(actually)'
df[df.apply(lambda x:
            x.astype(str).str.contains(
                re.escape(keyword), flags=re.I)).any(axis=1)]

Output:
    texts
0   This is really important(actually) because it ...

A: contains use regex and brackets are special chapter in regex
You can disable the regex by add regex=False:
    df_filter=df[df.apply(lambda x: x.astype(str).str.contains(keyword, regex=False)).any(axis=1)]


Q: How to set the cell color in jqGrid using attributes from the XML file? If have an XML file that jqGrid is reading. I want to set attributes in the class using attributes in the XML file. For example, given a file such as this:
<row id='0'>
  <cell class='type1'>2</cell>
  <cell class='type2'>2</cell>
</row>

I'd like the CSS to be such that the first cell has 'class="type1"' and the second cell to have 'class="type2"'.
I have been using cellattr_func to try and set these values, but it is only passed in the value of the cell, which isn't enough to determine the CSS class to be used in my use case. I've been inspecting the 'rawObject' parameter, which seems like it might have the information from the XML data attributes, but I don't know how to walk through the rawObject data structure successfully in Javascript to determine if what I want to do is possible or not.


Q: NullPointerException: Attempt to read from field StoreData.store_id on a null object reference Please help me where is the problem here and how to fix it. So I wont get null object. In my case, I'm sorry before I try to read other post too but make me little bit confused.
Here is my StoreHelper :
public StoreData getStore(String storeid) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor c = db.rawQuery("select * from " + TABLE_NAME + " where "
        + COL_STORE_ID + "=?", new String[]{storeid});
    StoreData data = null;
    System.out.println("This is the problem ");
    if (c.moveToFirst()) {
        data = new StoreData(
            c.getString(c.getColumnIndex(COL_STORE_ID)),
            c.getString(c.getColumnIndex(COL_ACCOUNT_ID)),
            c.getString(c.getColumnIndex(COL_KOTA_ID)),
            c.getString(c.getColumnIndex(COL_STORE_NAME)),
            c.getString(c.getColumnIndex(COL_STORE_MANAGER)),
            c.getString(c.getColumnIndex(COL_STORE_ADDRESS)),
            c.getString(c.getColumnIndex(COL_STORE_TELEPHONE)),
            c.getString(c.getColumnIndex(COL_STORE_GEO_LAT)),
            c.getString(c.getColumnIndex(COL_STORE_GEO_LONG)),
            c.getString(c.getColumnIndex(COL_STORE_LEADTIME)),
            c.getString(c.getColumnIndex(COL_STORE_MD)));
        db.close();
        c.close();
    }
    return data;
}

This is the StoreData:
public class StoreData {
    public int img;
    public String store_id;
    public String account_id;
    public String kota_id;
    public String store_name;
    public String store_manager;
    public String store_address;
    public String store_telephone;
    public String store_geo_lat;
    public String store_geo_long;
    public String store_leadtime;
    public String store_md;

    public StoreData(String storeid, String accountid, String kotaid, String storename, String storemanager,
                     String storeaddress, String storetelephone, String storegeolat, String storegeolong,
                     String storeleadtime, String storemd) {
        super();
        this.store_id = storeid;
        this.account_id = accountid;
        this.kota_id = kotaid;
        this.store_name = storename;
        this.store_manager = storemanager;
        this.store_address = storeaddress;
        this.store_telephone = storetelephone;
        this.store_geo_lat = storegeolat;
        this.store_geo_long = storegeolong;
        this.store_leadtime = storeleadtime;
        this.store_md = storemd;
    }
}

And this is where the error point is in the Activity
public void inCaseOffline() {

    StoreHelper sh = new StoreHelper(ctx);
    Log.i("ncdebug", "Store ID(incaseoffline): " + storeid);
    StoreData sd = sh.getStore(storeid);

    // temporary
    StoreInfo.storeid = sd.store_id;
    StoreInfo.storename = sd.store_name;
    StoreInfo.storeaddress = sd.store_address;
    StoreInfo.storetelephone = sd.store_telephone;
    StoreInfo.storemanager = sd.store_manager;

    Log.i("Data", sd.store_id + "<->" + sd.store_geo_lat + "," + sd.store_geo_long);

    TextView tvname = (TextView) findViewById(R.id.tvStoreInfoName);
    tvname.setText(sd.store_name);

    ProductsHelper helper = new ProductsHelper(ctx);
    StoreInfo.storeproducts = helper.getProducts();

    StoreInfo.storepromotions = new PromotionListData[0];

    DisplayCatHelper helperDisplayCat = new DisplayCatHelper(ctx);
    StoreInfo.storeDisplayCat = helperDisplayCat.getCategories();

    PromoCatHelper helperPromoCat = new PromoCatHelper(ctx);
    StoreInfo.storePromoCat = helperPromoCat.getCategories();

    CompetitorCatHelper helperCompetitorCat = new CompetitorCatHelper(ctx);
    StoreInfo.storeCompetitorCat = helperCompetitorCat.getCategories();

    add_overlay(StoreInfo.storename, new
            LatLng(Double.parseDouble(sd.store_geo_lat),
            Double.parseDouble(sd.store_geo_long)));
}

This is my log :
Process: com.apps.userinarts.mobilemerchpre, PID: 5308 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.apps.userinarts.mobilemerchpre/com.apps.userinarts.MobileMerchPre.StoresCheckinActivity}: java.lang.NullPointerException: Attempt to read from field 'java.lang.String com.apps.userinarts.MobileMerchPre.data.StoreData.store_id' on a null object reference
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                                at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                               Caused by: java.lang.NullPointerException: Attempt to read from field 'java.lang.String com.apps.userinarts.MobileMerchPre.data.StoreData.store_id' on a null object reference
                                                                                at com.apps.userinarts.MobileMerchPre.StoresCheckinActivity.inCaseOffline(StoresCheckinActivity.java:93)
                                                                                at com.apps.userinarts.MobileMerchPre.StoresCheckinActivity.onCreate(StoresCheckinActivity.java:83)
                                                                                at android.app.Activity.performCreate(Activity.java:6237)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                                at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

A: Simply because your query is returning a null cursor object.
So I would suggest two modification in your getStore function to avoid any crash issue.
This is a query to find a String object. So the query should look like this.
Cursor c = db.rawQuery("select * from " + TABLE_NAME + " where "
    + COL_STORE_ID + "='" + new String[]{storeid} + "'", null);

Look closely at the ' before and after the storeid you've provided as a parameter to the query.
And the other thing is you need to check for null value before you do any operation on your Cursor
// Check for null here and return if null
if(c == null) return null;

if (c.moveToFirst()) {
    //.. Your code
}

Add a check here too
public void inCaseOffline() {

    StoreHelper sh = new StoreHelper(ctx);
    Log.i("ncdebug", "Store ID(incaseoffline): " + storeid);
    StoreData sd = sh.getStore(storeid);

    // Add the null checking
    if(sd == null) {
        Toast.makeText(YourActivity.this, "Could not fetch information", Toast.LENGTH_LONG).show();
        return;
    }

    // .. Your code
}

Edit
You might consider having the getStore function to be modified like this
public StoreData getStore(String storeid) {
    // ... Database operation.

    // Initialize the StoreData here
    StoreData data = new StoreData();

    // ... Your code
    return data;
}

To achieve the initialization, add an empty constructor too in your StoreData class
public class StoreData {
    public int img;
    public String store_id;
    public String account_id;
    public String kota_id;
    public String store_name;
    public String store_manager;
    public String store_address;
    public String store_telephone;
    public String store_geo_lat;
    public String store_geo_long;
    public String store_leadtime;
    public String store_md;

    public StoreData() {
        // Empty constructor
    }

    // ... The other constructer
}


Q: Bold text on webpages when "Bold Text" iOS settings enabled I would like to increase the font weight of the text content in the webpage when the iOS "Bold Text" settings is enabled. But, I'm not able to find any documentation about it online.

A: I believe this has to do with the system-ui font. I've made a quick Codepen to check it out. If you enable the "Bold Text" option on iOS it will change the font weight for the p that uses the system-ui as its font-family. And you can see that the p with the custom font, Poppins, isn't bold.


Q: Mac OSX - Get all running application list with memory usage I am very new to develop mac osx application using xcode. I am trying to get all running  application list with their memory usage.
Can any body help me in this case.
Please help me.
Thanks in advance.

A: It will help you to get list of running application :
for (NSRunningApplication *app in [[NSWorkspace sharedWorkspace] runningApplications]) {
        NSLog(@"%@",[app localizedName]);
    }

A: You may get the cpu usage as:
- (NSString*) get_process_usage:(int) pid
{
    NSTask *task;
    task = [[NSTask alloc] init];
    [task setLaunchPath:@"/bin/ps"];

     NSArray *arguments;
     arguments = [NSArray arrayWithObjects: @"-O",@"%cpu",@"-p",[NSString stringWithFormat:@"%d",pid], nil];
     [task setArguments: arguments];

     NSPipe *pipe;
     pipe = [NSPipe pipe];
     [task setStandardOutput: pipe];

     NSFileHandle *file;
     file = [pipe fileHandleForReading];

     [task launch];

     NSData *data;
     data = [file readDataToEndOfFile];

     NSString *string;
     string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];

     NSString* temp = [string stringByReplacingOccurrencesOfString:@"PID  %CPU   TT  STAT      TIME COMMAND" withString:@""];

     NSMutableArray* arr =(NSMutableArray*) [temp componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
     [arr removeObject:@""];

     [string release];
     [task release];

     if([arr count]>=2)
         return [arr objectAtIndex:1];

     else
        return @"unknown";

 }


Q: Detecting Available Network Adapters With Python I want to detect the available network interfaces that is connected to a DHCP and got an IP from it. I am using following script to generate the list of available adapters.
import psutil
addrs = psutil.net_if_addrs()
all_network_interfaces = addrs.keys()
available_networks = []
for value in all_network_interfaces:
    if addrs[value][1][1].startswith("169.254"):
        continue
    else:
        available_networks.append(value)
print(available_networks)

The ones that starts with 169.254 are the adapters that is using Automatic Private IP Addressing (APIPA) so I want to filter them out. When I connect with an Ethernet cable, this script shows the related adapter, if I also connect over WiFi while ethernet is still connected, it adds the WiFi to the list. However, after disconnecting from the WiFi, WiFi adapters still holds the IP and still exists in the list. I think that it is a problem( maybe feature) with my adapter card. What is the best way to bypass this and obtain only the adapters with DHCP connection?

A: With psutil.net_if_stats() to get only up and running network interfaces:
import psutil

addresses = psutil.net_if_addrs()
stats = psutil.net_if_stats()

available_networks = []
for intface, addr_list in addresses.items():
    if any(getattr(addr, 'address').startswith("169.254") for addr in addr_list):
        continue
    elif intface in stats and getattr(stats[intface], "isup"):
        available_networks.append(intface)

print(available_networks)

Sample output:
['lo0', 'en0', 'en1', 'en2', 'en3', 'bridge0', 'utun0']

A: There is a python package get-nic which gives NIC status, up\down, ip addr, mac addr etc

pip install get-nic

from get_nic import getnic

getnic.interfaces()

Output: ["eth0", "wlo1"]

interfaces = getnic.interfaces()
getnic.ipaddr(interfaces)

Output:
{'lo': {'state': 'UNKNOWN', 'inet4': '127.0.0.1/8', 'inet6': '::1/128'}, 'enp3s0': {'state': 'DOWN', 'HWaddr': 'a4:5d:36:c2:34:3e'}, 'wlo1': {'state': 'UP', 'HWaddr': '48:d2:24:7f:63:10', 'inet4': '10.16.1.34/24', 'inet6': 'fe80::ab4a:95f7:26bd:82dd/64'}}

Refer GitHub page for more information: https://github.com/tech-novic/get-nic-details


Q: How to fix mismatch processor architecture, unexpected e_machine, due to a .so file I have a Xamarin android project and am currently using Visual Studio 2015.
Inside of my MainActivity.cs, I have the following code:
Com.Alk.Sdk.SharedLibraryLoader.LoadLibrary("alksdk", this);

which then goes into:
// Metadata.xml XPath method reference: path="/api/package[@name='com.alk.sdk']/class[@name='SharedLibraryLoader']/method[@name='loadLibrary' and count(parameter)=2 and parameter[1][@type='java.lang.String'] and parameter[2][@type='android.content.Context']]"
        [Register ("loadLibrary", "(Ljava/lang/String;Landroid/content/Context;)Z", "")]
        public static unsafe bool LoadLibrary (string p0, global::Android.Content.Context p1)
        {
            if (id_loadLibrary_Ljava_lang_String_Landroid_content_Context_ == IntPtr.Zero)
                id_loadLibrary_Ljava_lang_String_Landroid_content_Context_ = JNIEnv.GetStaticMethodID (class_ref, "loadLibrary", "(Ljava/lang/String;Landroid/content/Context;)Z");
            IntPtr native_p0 = JNIEnv.NewString (p0);
            try {
                JValue* __args = stackalloc JValue [2];
                __args [0] = new JValue (native_p0);
                __args [1] = new JValue (p1);
                bool __ret = JNIEnv.CallStaticBooleanMethod  (class_ref, id_loadLibrary_Ljava_lang_String_Landroid_content_Context_, __args);
                return __ret;
            } finally {
                JNIEnv.DeleteLocalRef (native_p0);
            }
        }

The problem I am having is that when it calls the JNIEnv.CallStaticBooleanMethod, it throws this exception:
[ERROR] FATAL UNHANDLED EXCEPTION: Java.Lang.UnsatisfiedLinkError: dlopen failed: "/data/data/com.pai.rp/app_lib/libalksdk.so" has unexpected e_machine: 3
--- End of managed Java.Lang.UnsatisfiedLinkError stack trace ---
java.lang.UnsatisfiedLinkError: dlopen failed: "/data/data/com.pai.rp/app_lib/libalksdk.so" has unexpected e_machine: 3
at java.lang.Runtime.load0(Runtime.java:908)
at java.lang.System.load(System.java:1542)
at com.alk.sdk.SharedLibraryLoader.loadLibrary(SharedLibraryLoader.java:44)
at com.pai.rp.MainActivity.n_onCreate(Native Method)
at com.pai.rp.MainActivity.onCreate(MainActivity.java:30)
at android.app.Activity.performCreate(Activity.java:6973)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2946)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3064)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1659)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6823)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1557)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)

From what I've been able to research I've found that

*

*e_machine: 3 indicates the expected arch is Intel 80386 (ELF Headers).

*When using a Google Nexus 10 emulator it seems to work, however when
I use the Galaxy Tab E (ARM) through USB debugging, it crashes and gives me
this error.
So the question is, how do I correct this?


Q: Combine 2 functions into 1 How can i combine this functions. Basically, when if the checkbox is clicked, something happens and if the page loads and if the checkbox is already clicked, the same thing happens as the second function.
        $(document).on("click", ".dimensions", function() {
            var size = $('.td-hide');
            if ($('input#dimensions').is(':checked')) {
            size.show();
            $('.single-select-sm').css('width','148px')
            } else {
            size.hide();
            $('.single-select-sm').css('width','230px')
            }
        });
        $(function() {
            var size = $('.td-hide');
            if ($('input#dimensions').is(':checked')) {
            size.show();
            $('.single-select-sm').css('width','148px')
            } else {
            size.hide();
            $('.single-select-sm').css('width','230px')
            }
        });

A: var myFunc = function()
{
            var size = $('.td-hide');
            if ($('input#dimensions').is(':checked')) {
            size.show();
            $('.single-select-sm').css('width','148px')
            } else {
            size.hide();
            $('.single-select-sm').css('width','230px')
            }
}

$(document).on("click", ".dimensions", function() {
    myFunc();
}

$(function() {
    myFunc();
}


Q: Letter to word assignment I'm practicing programming in C sharp and i'm trying to write a program that will ask for a letter value from the user and output a word value eg. the user inputs the letter "a" and gets the word "apple". What would be the best code for this?  Cheers.

A: Hint: use a Dictionary.
var dict = new Dictionary<char, string>() {
  {'a', "apple"},
  {'b', "box"},
  // ......
  {'z', "zebra"}
};

dict['a']; // apple


Q: TimerTask runs one more time after I call timer.cancel() method TimerTask runs one more time after I call timer.cancel() method.
I don't need TimerMethod to be executed after I call stopBusTimer() method.
Can somebody explain why is it happening?
busTimer = new Timer();
    busTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            TimerMethod(mSelectedRoute);
        }
    }, 0, Consts.BUS_TIMER_INTERVAL);

 private void stopBusTimer() {
    if (busTimer != null) {
        busTimer.cancel();
        busTimer.purge();
        busTimer = null;
        Log.v(LOG_TAG, "stop BusTimer");
    }
}

A: The cancel method will stop all following executions, but not the current one. It your method execution takes a long time, then it is possible by the time you call cancel, the method has already begun executing.
The best way to make sure the method does not execute is to call cancel from within the run() function itself.


Q: Getting a Mod_Security error When i install captcha plugin on my website and try to login, m getting Error:
An appropriate representation of the requested resource could not be found on this server. This error was generated by Mod_Security.


Q: ML assignment operation everyone, what is difference between the following assignments in ML,
val n = 5;

and
n := 1;

A: The former is a declaration of a new, immutable variable. The latter is how you re-assign the value of a reference cell.


Q: Scheduling playback of AudioWorkletNode I'm working with soundtouchjs-audio-worklet in order to change the tempo/pitch of audio files that have been read into a buffer. The library creates a worklet that can process these buffers, and gives me an AudioWorkletNode to control it. What I need to do is schedule the playback of multiple AudioWorkletNodes so that different audio files can be on a "timeline" of sorts.
I know the AudioBufferSourceNode has a when parameter in it's start() function that you can use to schedule the playback of the node. But AudioWorkletNode doesn't seem to be scheduleable; it just immediately begins playback upon connect()ing it.
I could use setTimeout() to delay calling connect(), but I don't think the timing will be accurate enough. Does anyone know of a way to schedule playback of an AudioWorkletNode? Or an accurate way to connect it at the exact right time?

A: There is no built-in way to schedule an AudioWorkletProcessor but it's possible to use the global currentTime variable to build it yourself. The processor would then look a bit like this.
class ScheduledProcessor extends AudioWorkletProcessor {
    constructor() {
        super();

        this.port.onmessage = (event) => this.startTime = event.data;
        this.startTime = Number.POSITIVE_INFINITY;
    }

    process() {
        if (currentTime < this.startTime) {
            return true;
        }

        // Now it's time to start the processing.
    }
}

registerProcessor('scheduled-processor', ScheduledProcessor);

It can then be "scheduled" to start when currentTime is 15 like this:
const scheduledAudioNode = new AudioWorkletNode(
    audioContext,
    'scheduled-processor'
);

scheduledAudioNode.port.postMessage(15);


Q: Upgrade Hibernate 3.6 to hibernate 4.3.6 on jboss 6.0.0 AS getting java.lang.NoClassDefFoundError: org/hibernate/classic/Session We are upgrading hibernate 3.6 to hibernate 4.3.6 in our application and we are using hibernate JPA 2.0 in Jboss 6.0.0. We have excluded jpa components and other JBoss components and bundled our own libs (i.e jpa hibernate etc) after deploying  and starting the Jboss.
We get :
17:50:31,788 ERROR [AbstractKernelController] Error installing to Real: name=vfs:///C:/Jboss/jboss-6.0.0.Final/server/XXXXXX/deploy/XXXXXX-6.4.1.ear state=PreReal mode=Manual requiredState=Real: org.jboss.deployers.spi.DeploymentException: Error deploying XXXXXXEJB3.jar: org/hibernate/classic/Session
at org.jboss.ejb3.deployers.Ejb3Deployer.deploy(Ejb3Deployer.java:194) [:6.0.0.Final]
at org.jboss.ejb3.deployers.Ejb3Deployer.deploy(Ejb3Deployer.java:60) [:6.0.0.Final]
at org.jboss.deployers.vfs.spi.deployer.AbstractSimpleVFSRealDeployer.deploy(AbstractSimpleVFSRealDeployer.java:56) [:2.2.0.GA]
at org.jboss.deployers.spi.deployer.helpers.AbstractSimpleRealDeployer.internalDeploy(AbstractSimpleRealDeployer.java:62) [:2.2.0.GA]
at org.jboss.deployers.spi.deployer.helpers.AbstractRealDeployer.deploy(AbstractRealDeployer.java:55) [:2.2.0.GA]
at org.jboss.deployers.plugins.deployers.DeployerWrapper.deploy(DeployerWrapper.java:179) [:2.2.0.GA]
at org.jboss.deployers.plugins.deployers.DeployersImpl.doDeploy(DeployersImpl.java:1832) [:2.2.0.GA]
at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1550) [:2.2.0.GA]
at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1603) [:2.2.0.GA]
at org.jboss.deployers.plugins.deployers.DeployersImpl.install(DeployersImpl.java:1491) [:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:379) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:2044) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:1083) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractController.executeOrIncrementStateDirectly(AbstractController.java:1322) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1246) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1139) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:939) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:654) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.deployers.plugins.deployers.DeployersImpl.change(DeployersImpl.java:1983) [:2.2.0.GA]
at org.jboss.deployers.plugins.deployers.DeployersImpl.process(DeployersImpl.java:1076) [:2.2.0.GA]
at org.jboss.deployers.plugins.main.MainDeployerImpl.process(MainDeployerImpl.java:679) [:2.2.0.GA]
at org.jboss.system.server.profileservice.deployers.MainDeployerPlugin.process(MainDeployerPlugin.java:106) [:6.0.0.Final]
at org.jboss.profileservice.dependency.ProfileControllerContext$DelegateDeployer.process(ProfileControllerContext.java:143) [:0.2.2]
at org.jboss.profileservice.dependency.ProfileDeployAction.deploy(ProfileDeployAction.java:151) [:0.2.2]
at org.jboss.profileservice.dependency.ProfileDeployAction.installActionInternal(ProfileDeployAction.java:94) [:0.2.2]
at org.jboss.kernel.plugins.dependency.InstallsAwareAction.installAction(InstallsAwareAction.java:54) [jboss-kernel.jar:2.2.0.GA]
at org.jboss.kernel.plugins.dependency.InstallsAwareAction.installAction(InstallsAwareAction.java:42) [jboss-kernel.jar:2.2.0.GA]
at org.jboss.dependency.plugins.action.SimpleControllerContextAction.simpleInstallAction(SimpleControllerContextAction.java:62) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.action.AccessControllerContextAction.install(AccessControllerContextAction.java:71) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractControllerContextActions.install(AbstractControllerContextActions.java:51) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:379) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:2044) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:1083) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractController.executeOrIncrementStateDirectly(AbstractController.java:1322) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1246) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1139) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:939) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:654) [jboss-dependency.jar:2.2.0.GA]
at org.jboss.profileservice.dependency.ProfileActivationWrapper$BasicProfileActivation.start(ProfileActivationWrapper.java:190) [:0.2.2]
at org.jboss.profileservice.dependency.ProfileActivationWrapper.start(ProfileActivationWrapper.java:87) [:0.2.2]
at org.jboss.profileservice.dependency.ProfileActivationService.activateProfile(ProfileActivationService.java:215) [:0.2.2]
at org.jboss.profileservice.dependency.ProfileActivationService.activate(ProfileActivationService.java:159) [:0.2.2]
at org.jboss.profileservice.bootstrap.AbstractProfileServiceBootstrap.activate(AbstractProfileServiceBootstrap.java:112) [:0.2.2]
at org.jboss.profileservice.resolver.BasicResolverFactory$ProfileResolverFacade.deploy(BasicResolverFactory.java:87) [:0.2.2]
at org.jboss.profileservice.bootstrap.AbstractProfileServiceBootstrap.start(AbstractProfileServiceBootstrap.java:91) [:0.2.2]
at org.jboss.system.server.profileservice.bootstrap.BasicProfileServiceBootstrap.start(BasicProfileServiceBootstrap.java:132) [:6.0.0.Final]
at org.jboss.system.server.profileservice.bootstrap.BasicProfileServiceBootstrap.start(BasicProfileServiceBootstrap.java:56) [:6.0.0.Final]
at org.jboss.bootstrap.impl.base.server.AbstractServer.startBootstraps(AbstractServer.java:827) [jboss-bootstrap-impl-base.jar:2.1.0-alpha-5]
at org.jboss.bootstrap.impl.base.server.AbstractServer$StartServerTask.run(AbstractServer.java:417) [jboss-bootstrap-impl-base.jar:2.1.0-alpha-5]
at java.lang.Thread.run(Unknown Source) [:1.6.0_31]
 Caused by: java.lang.NoClassDefFoundError: org/hibernate/classic/Session
at org.jboss.injection.PcEncInjector.<clinit>(PcEncInjector.java:48) [:1.7.17]
at org.jboss.injection.PersistenceContextHandler.loadXml(PersistenceContextHandler.java:73) [:1.7.17]
at org.jboss.ejb3.EJBContainer.processMetadata(EJBContainer.java:779) [:1.7.17]
at org.jboss.ejb3.Ejb3Deployment.processEJBContainerMetadata(Ejb3Deployment.java:471) [:1.7.17]
at org.jboss.ejb3.Ejb3Deployment.create(Ejb3Deployment.java:553) [:1.7.17]
at org.jboss.ejb3.deployers.Ejb3Deployer.deploy(Ejb3Deployer.java:177) [:6.0.0.Final]
... 49 more
Caused by: java.lang.ClassNotFoundException: org.hibernate.classic.Session from BaseClassLoader@5b3ba312{vfs:///C:/Jboss/jboss-6.0.0.Final/server/XXXXXX/conf/jboss-service.xml}
at org.jboss.classloader.spi.base.BaseClassLoader.loadClass(BaseClassLoader.java:480) [jboss-classloader.jar:2.2.0.GA]
at java.lang.ClassLoader.loadClass(Unknown Source) [:1.6.0_31]
... 55 more

Removed all the reference somewhere jboss bootstrap class loader looks for org/hibernate/classic/Session We couldn't find the reference . Please help me out.

A: This looks like the JBoss 6.0 EJB3 implementation is dependent upon the version of Hibernate that you have removed.
Why don't you upgrade to JBossAS 7.x for JPA 2.0 support?


Q: Python 2: insert existing list inside of new explicit list definition This may not be possible, but if it is, it'd be convenient for some code I'm writing:
ListOne = ['jumps', 'over', 'the']
ListTwo = ['The', 'quick', 'brown', 'fox', ListOne, 'lazy', 'dog!']

If I do this, I'll end up with ListOne being a single item being a list inside of ListTwo.
But instead, I want to expand ListOne into ListTwo, but I don't want to have to do something like:
ListOne = ['jumps', 'over', 'the']
ListTwo = ['The', 'quick', 'brown', 'fox']
ListTwo.extend(ListOne)
ListTwo.extend(['lazy', 'dog!']

This will work but it's not as readable as the above code.
Is this possible?

A: You can just use the + operator to concatenate lists:
ListOne = ['jumps', 'over', 'the']
ListTwo = ['The', 'quick', 'brown', 'fox'] + ListOne + ['lazy', 'dog!']

ListTwo will be:
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog!']

A: Another alternative is to use slicing assignment:
>>> ListOne = ['jumps', 'over', 'the']
>>> ListTwo = ['The', 'quick', 'brown', 'fox', 'lazy', 'dog!']
>>> ListTwo[4:4] = ListOne
>>> ListTwo
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog!']

A: >>> ListOne = ['jumps', 'over', 'the']
>>> from itertools import chain
>>> [x for x in chain(['The', 'quick', 'brown', 'fox'], ListOne, ['lazy', 'dog!'])]
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog!']

A: Why not concatenate?
>>> ListTwo = ['The', 'quick', 'brown', 'fox']
>>> ListOne = ['jumps', 'over', 'the']
>>> ListTwo + ListOne
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the']
>>> ListTwo + ListOne + ['lazy', 'dog!']
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog!']


Q: Laravel group by not working if only one key exists? I have this following code:
        $groupedRates = $result->rates->groupBy('minimum_age');

when I try to return it, I get this:
  "rates": [
                [
                    {
                        "id": 1,
                        "cpf_scheme_id": 1,
                        "minimum_age": 0,
                        "minimum_wage": 0,
                    },
                    {
                        "id": 2,
                        "cpf_scheme_id": 1,
                        "minimum_age": 0,
                        "minimum_wage": 750,
                    }
                ]
            ]

however, if I were to add one more key, it returns an associative array as expected.
  "rates": {
                "0": [
                    {
                        "id": 1,
                        "cpf_scheme_id": 1,
                        "minimum_age": 0,
                        "minimum_wage": 0,
                    },
                    {
                        "id": 2,
                        "cpf_scheme_id": 1,
                        "minimum_age": 0,
                        "minimum_wage": 750,
                    }
                ],
                "50": [
                    {
                        "id": 4,
                        "cpf_scheme_id": 1,
                        "minimum_age": 50,
                        "minimum_wage": 100,
                    }
                ]
            }

How do I fix this? It will break apis if it returns an associative array sometimes and a normal array other times!


Q: Can NSNotificationCenter be used between different frameworks to communicate? An app can make internal use of NSNotificationCenter for different parts to communicate with each other, but can this be extended such that different frameworks can use it to communicate on iOS?

A: In the same app, frameworks all get executed on the same process. They just locate at different places in memory allocated by the app.
On the same running process, NSNofitcationCenter can communicate with each other no matter which framework the sender or receiver locates at.
If you are talking about app and its extension, they run on different process and thus NSNofitcationCenter can not send notification to each other. You have to use CFNotificationCenter


Q: How can I edit and transfer output tables from R? I am working with R for analyzing data for my research paper. I have run some regressions and marginal effects and would like to get the output in a format that I can include in my research paper (best would be tables as images). How can I do this?
I have tried using the sumtable() command, but it only provides a table that summarizes the overall data that I am using and not the specific regressions or the marginal effect output.
I have also used htmlreg() but as far as I know it is only for regressions, and I do not know how to transfer the html output into my word document where I am writing the paper.


Q: Compare date and hour together I am using Amazon Redshift . In my tables I have two columns (Date and Hour) ,along with other columns with values like
requestdate  requesthour
2016-10-10     1
2016-10-10     2
 ...          ...

Now I want to compare two dates with hours (day between 2016-10-1005 && 2016-11-1109) . Generally comparing with qyery like
Where date>=xxxx && date<=yyyy && hour>=hhhh && hour<hhhh

will give incomplete results . Can I do something which can be useful here , I tried certain things after searching the web like concat , to_timestamp but could not come up with proper query .
Can anyone help here?

A: Here is one explicit way:
where (date > xxxx or (date = xxxx and hour >= hhhh)) and
      (date < yyyy or (date = yyyy and hour < hhhh))

Another method would use date arithmetic:
where date + hour * interval '1 hour' >= xxxx + hhhh * interval '1 hour' and
      date + hour * interval '1 hour' < yyyy + hhhh * interval '1 hour'

A: You can cast your date + hour to timestamp and let database to compare them
select (requestdate ||' '|| requesthour ||':00:00')::timestamp  between ('2016-10-10 05:00:00')::timestamp and ('2016-08-01 04:00:00')::timestamp  from bbt


Q: Outer margins in pairs() function I have too much whitespace around the outside of my pairs() plot. How can one control the outer margins in a pairs() plot?
Changing oma for example does nothing (i.e. par(oma=c(0,0,0,0)) makes no difference).

A: tl;dr use oma as an argument within your pairs() call.
As usual, it's all in the documentation, albeit somewhat obscurely. ?pairs states:

Also, graphical parameters can be given as can arguments to
            ‘plot’ such as ‘main’.  ‘par("oma")’ will be set
            appropriately unless specified.

This means that pairs() tries to do some clever stuff internally to set the outer margins (based on whether a main title is requested); it will ignore external par("oma") settings, only paying attention to internal settings.  The "offending" line within the code of stats:::pairs.default is:
  if (is.null(oma))
        oma <- c(4, 4, if (!is.null(main)) 6 else 4, 4)

Thus setting oma within the call does work:
par(bg="lightblue")  ## so we can see the plot region ...
z <- matrix(rnorm(300),ncol=3)
pairs(z,oma=c(0,0,0,0))


Q: How to make a multi-user file server system with PHP? I'm just looking a big picture idea here; I can google specifics once provided with guidelines.
I want to make a relatively simple file hosting website such as dropbox or skydrive for mainly pedagogical reasons.
Making a multi-user login and registration system with PHP and MySQL is pretty straight forward, but how would I go about managing file directories and permissions for each user?

A: There are probably hundreds of ways to do this, but this is what I would do:

*

*They should never have a direct download path as it can be abused.

*All files could be stored in the same place.

*File names should be changed to unique ids to avoid dupilcates.

*Store the file name, unique id, and user id in a database.

*When they visit the page for the unique id, you can do your checks and display the file info.

*You will then pass the file to them rather than having them download it directly.

*Their user page would show file names and links to those pages, etc.

I hope that is a good jumping off point.

A: At its simplest: Store files somewhere in any hierarchy you want in a location that's not simply publicly accessible through the web server. Store meta information about each file in a database. In said database, store who the owner of the file is. Write a script that allows people to download those files (see readfile), require that users are logged in and that only owners of files can them.


Q: What's the correct way of waiting for detached threads to finish? Look at this sample code:
void OutputElement(int e, int delay)
{
    this_thread::sleep_for(chrono::milliseconds(100 * delay));
    cout << e << '\n';
}

void SleepSort(int v[], uint n)
{
    for (uint i = 0 ; i < n ; ++i)
    {
        thread t(OutputElement, v[i], v[i]);
        t.detach();
    }
}

It starts n new threads and each one sleeps for some time before outputting a value and finishing. What's the correct/best/recommended way of waiting for all threads to finish in this case? I know how to work around this but I want to know what's the recommended multithreading tool/design that I should use in this situation (e.g. condition_variable, mutex etc...)?

A: Don't detach, but instead join:
std::vector<std::thread> ts;

for (unsigned int i = 0; i != n; ++i)
    ts.emplace_back(OutputElement, v[i], v[i]);

for (auto & t : threads)
    t.join();

A: And now for the slightly dissenting answer.  And I do mean slightly because I mostly agree with the other answer and the comments that say "don't detach, instead join."
First imagine that there is no join().  And that you have to communicate among your threads with a mutex and condition_variable.  This really isn't that hard nor complicated.  And it allows an arbitrarily rich communication, which can be anything you want, as long as it is only communicated while the mutex is locked.
Now a very common idiom for such communication would simply be a state that says "I'm done".  Child threads would set it, and the parent thread would wait on the condition_variable until the child said "I'm done."  This idiom would in fact be so common as to deserve a convenience function that encapsulated the mutex, condition_variable and state.
join() is precisely this convenience function.
But imho one has to be careful.  When one says:  "Never detach, always join," that could be interpreted as:  Never make your thread communication more complicated than "I'm done."
For a more complex interaction between parent thread and child thread, consider the case where a parent thread launches several child threads to go out and independently search for the solution to a problem.  When the problem is first found by any thread, that gets communicated to the parent, and the parent can then take that solution, and tell all the other threads that they don't need to search any more.
For example:
#include <chrono>
#include <iostream>
#include <iterator>
#include <random>
#include <thread>
#include <vector>

void OneSearch(int id, std::shared_ptr<std::mutex> mut,
                   std::shared_ptr<std::condition_variable> cv,
                   int& state, int& solution)
{
    std::random_device seed;
//     std::mt19937_64 eng{seed()};
    std::mt19937_64 eng{static_cast<unsigned>(id)};
    std::uniform_int_distribution<> dist(0, 100000000);
    int test = 0;
    while (true)
    {
        for (int i = 0; i < 100000000; ++i)
        {
            ++test;
            if (dist(eng) == 999)
            {
                std::unique_lock<std::mutex> lk(*mut);
                if (state == -1)
                {
                    state = id;
                    solution = test;
                    cv->notify_one();
                }
                return;
            }
        }
        std::unique_lock<std::mutex> lk(*mut);
        if (state != -1)
            return;
    }
}

auto findSolution(int n)
{
    std::vector<std::thread> threads;
    auto mut = std::make_shared<std::mutex>();
    auto cv = std::make_shared<std::condition_variable>();
    int state = -1;
    int solution = -1;
    std::unique_lock<std::mutex> lk(*mut);
    for (uint i = 0 ; i < n ; ++i)
        threads.push_back(std::thread(OneSearch, i, mut, cv,
                          std::ref(state), std::ref(solution)));
    while (state == -1)
        cv->wait(lk);
    lk.unlock();
    for (auto& t : threads)
        t.join();
    return std::make_pair(state, solution);
}

int
main()
{
    auto p = findSolution(5);
    std::cout << '{' << p.first << ", " << p.second << "}\n";
}

Above I've created a "dummy problem" where a thread searches for how many times it needs to query a URNG until it comes up with the number 999.  The parent thread puts 5 child threads to work on it.  The child threads work for awhile, and then every once in a while, look up and see if any other thread has found the solution yet.  If so, they quit, else they keep working.  The main thread waits until solution is found, and then joins with all the child threads.
For me, using the bash time facility, this outputs:
$ time a.out
{3, 30235588}

real    0m4.884s
user    0m16.792s
sys 0m0.017s

But what if instead of joining with all the threads, it detached those threads that had not yet found a solution.  This might look like:
    for (unsigned i = 0; i < n; ++i)
    {
        if (i == state)
            threads[i].join();
        else
            threads[i].detach();
    }

(in place of the t.join() loop from above).  For me this now runs in 1.8 seconds, instead of the 4.9 seconds above.  I.e. the child threads are not checking with each other that often, and so main just detaches the working threads and lets the OS bring them down.  This is safe for this example because the child threads own everything they are touching.  Nothing gets destructed out from under them.
One final iteration can be realized by noticing that even the thread that finds the solution doesn't need to be joined with.  All of the threads could be detached.  The code is actually much simpler:
auto findSolution(int n)
{
    auto mut = std::make_shared<std::mutex>();
    auto cv = std::make_shared<std::condition_variable>();
    int state = -1;
    int solution = -1;
    std::unique_lock<std::mutex> lk(*mut);
    for (uint i = 0 ; i < n ; ++i)
        std::thread(OneSearch, i, mut, cv,
                          std::ref(state), std::ref(solution)).detach();
    while (state == -1)
        cv->wait(lk);
    return std::make_pair(state, solution);
}

And the performance remains at about 1.8 seconds.
There is still (sort of) an effective join with the solution-finding thread here.  But it is accomplished with the condition_variable::wait instead of with join.
thread::join() is a convenience function for the very common idiom that your parent/child thread communication protocol is simply "I'm done."  Prefer thread::join() in this common case as it is easier to read, and easier to write.
However don't unnecessarily constrain yourself to such a simple parent/child communication protocol.  And don't be afraid to build your own richer protocol when the task at hand needs it.  And in this case, thread::detach() will often make more sense.  thread::detach() doesn't necessarily imply a fire-and-forget thread.  It can simply mean that your communication protocol is more complex than "I'm done."


Q: sas difference between sum and +? data whatever;
 infile '';
 input price cost;
 <statement>;
run;

In <statement>, what's the difference between using total = sum(total,cost) and total = total + cost ?

A: You'd probably have trouble with either of those if you actually including it after the input statement.
The information that ProgramFOX posted is correct, but if you're asking about the difference between these three statements, there's a little more to it:
total = sum(total,cost);
total + cost;

The second of these implies a retain total; statement and will also treat nulls as zero.  You run into the null problem when you're using this type of expression:
total = total + cost;

A: The differnce can be seen below:
If you want to calculate cumulative total , you should use sum statement.
total = sum(total,cost) /* its a sum function */
total+cost /* its a sum statement,the form is variable+expression */
Here :
"total" specifies the name of the accumulator variable, which contains a numeric value.
1) The variable(total in this case) is automatically set to 0 before SAS reads the first observation. The variable's value is retained from one iteration to the next, as if it had appeared in a RETAIN statement.
2) To initialize a sum variable to a value other than 0, include it in a RETAIN statement with an initial value.
and
"Cost" is an expression
1) The expression is evaluated and the result added to the accumulator variable.
2) SAS treats an expression that produces a missing value as zero.
A sum statement is differ from a sum function in a way that a sum statement retains the value which it has calculated earlier.
However,
The sum statement is equivalent to using the SUM function and the RETAIN statement, as shown here:
retain total 0;
total=sum(total,cost);


Q: Install node and npm using ant build.xml Could someone help to download node and ant from a URL and install them using ant build.xml?
I tried different ways. but it requires sudo privilege. but, it may/may not be available on the server. so, I need common support with normal user privilege.


Q: Divs in template are pushing page out of alignment I have, with advice from members here, attempted to create divs rather than a table for article layout template. I had reasonable success - the content displayed, but not correctly and it also scrambled the page - I had the comments module, which should sit below the article, pushed up on the right and the article content pushed left and down.  I'm posting the table code along with the divs in the hope that someone can assist (One issue, I think, is that there is a single column spanning 8 rows, 4 of which span 2 columns and 4 contain 2 columns, then below this is a further row which spans all 3 columns. I'm confused. For now I've retained the table, but I would really like to learn how to do this correctly. Any help would be appreciated.
Thanks,
Jude
Table:

        <?php echo $item->fields_by_id[3]->result; ?>
        Author:
        <?php echo $item->fields_by_id[1]->result; ?>

        Publisher:
        <?php echo $item->fields_by_id[2]->result; ?>

        Genre:
        <?php echo $item->fields_by_id[9]->result; ?>

        CRR Heat Rating:
        <?php echo $item->fields_by_id[11]->result; ?>

        <?php echo $item->fields_by_id[12]->result; ?>

        <?php echo $item->fields_by_id[10]->result; ?>

        <?php echo $item->fields_by_id[13]->result; ?>

        <?php echo $item->fields_by_id[4]->result; ?>

        <?php echo $item->fields_by_id[5]->result; ?>

Divs:

<?php echo $item->fields_by_id[3]->result; ?>

Author:

Publisher:

Genre:

CRR Heat Rating:

<?php echo $item->fields_by_id[12]->result; ?>

<?php echo $item->fields_by_id[10]->result; ?>

<?php echo $item->fields_by_id[13]->result; ?>

<?php echo $item->fields_by_id[5]->result; ?>

<?php echo $item->fields_by_id[1]->result; ?>

<?php echo $item->fields_by_id[2]->result; ?>

<?php echo $item->fields_by_id[9]->result; ?>

<?php echo $item->fields_by_id[11]->result; ?>

<?php echo $item->fields_by_id[4]->result; ?>

A: float makes that the element has no height anymore, which causes all kinds of 'funny' stuff. I think you are searching for display: table and display: table-cell. Otherwise you can use clear: left; or clear: both on the element that should be displayed under the left-floating elements.

To get the display: table and display: table-cell working, you'll have to remove one div-wrapper around each column.

<?php echo $item->fields_by_id[3]->result; ?>

Author:

Publisher:

Genre:

Then use the following CSS:
#article {
  display: table;
}

#article > div {
  display: table-cell;
}


Q: How to call versioned graph API services in Facebook .NET SDK? It seems that Facebook now wants us to call versioned endpoints of the Graph API. E.g., https://graph.facebook.com/v2.0/me...
Does the Facebook SDK for .NET make versioned calls? Do I/can I do something to specify the version?

A: Sanjeev got it, there is a parameter you can add to specify version:
FacebookClient fbClient = new FacebookClient();
fbClient.Version = "v2.2";
fbClient.Post("me/feed", new
{
    message = string.Format("Hello version 2.2! - Try #2"),
    access_token = "youraccesstokenhere"
});

If you are not specifying a version, it'll default to the oldest supported version:
https://developers.facebook.com/docs/apps/versions#unversioned_calls
Facebook will warn you that you are nearing end of support for that version.
Don't take any chances that the auto-upgrade to newer version will work, better to develop, test and deliver with the latest version.


Q: Application on spark using java langage I'm new on a spark , and I want to run an application on this framework using java language. I tried the following code :
  public  class Alert_Arret  {

  private static final SparkSession sparkSession = SparkSession.builder().master("local[*]").appName("Stateful Streaming Example").config("spark.sql.warehouse.dir", "file:////C:/Users/sgulati/spark-warehouse").getOrCreate();

    public static Properties Connection_db () {

            Properties connectionProperties = new Properties();
            connectionProperties.put("user", "xxxxx");
            connectionProperties.put("password", "xxxxx");
            connectionProperties.put("driver","com.mysql.jdbc.Driver");
            connectionProperties.put("url","xxxxxxxxxxxxxxxxx");

       return connectionProperties;
    }
   public static void GetData() {
        boolean checked = true;
        String dtable = "alerte_prog";
        String dtable2 = "last_tracking_tdays";
        Dataset<Row> df_a_prog = sparkSession.read().jdbc("jdbc:mysql://host:port/database", dtable, Connection_db());
       // df_a_prog.printSchema();
        Dataset<Row> track = sparkSession.read().jdbc("jdbc:mysql://host:port/database", dtable2, Connection_db());

        if (df_a_prog.select("heureDebut") != null && df_a_prog.select("heureFin") != null ) {
            track.withColumn("tracking_hour/minute", from_unixtime(unix_timestamp(col("tracking_time")), "HH:mm")).show()    }
    }
     public static void main(String[] args) {

     Connection_db();
     GetData();

    }
    }

when I run this code nothing is displayed and I get this:
   0/05/11 14:00:31 WARN ProcfsMetricsGetter: Exception when trying to compute pagesize, as a result reporting of ProcessTree metrics is stopped

  # A fatal error has been detected by the Java Runtime Environment:
   #  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x000000006c40022a,pid=3376, tid=0x0000000000002e84

I use IntelliJ IDEA and version of spark: 3.0.0.


Q: Creating an inner stroke of semi transparency on coloured squares? I am drawing different colored squares on canvas with a fixed size of 50px x 50px.
I have successfully added a transparent inner stroke of 5px to these colored squares but it seems like massive overkill the way I am doing it.
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, engine.cellSize, engine.cellSize);
ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
ctx.fillRect(this.x, this.y, engine.cellSize, engine.cellSize);
ctx.fillStyle = this.color;
ctx.fillRect(this.x + 5, this.y + 5, engine.cellSize - 10, engine.cellSize - 10);

Is there a better way than drawing 3 separate rectangles to achieve what I am after?

A: Yes!
You can use both a fill color inside your rectangle and a stroke color around your rectangle.
Here is code an a Fiddle: http://jsfiddle.net/m1erickson/myGky/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>

<script>
    $(function(){

      var canvas=document.getElementById("canvas");
      var ctx=canvas.getContext("2d");

      ctx.beginPath();
      ctx.fillStyle = "red";
      ctx.fillRect(100,100,50,50);
      ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
      ctx.fillRect(100,100,50,50);
      ctx.fillStyle = this.color;
      ctx.fillRect(105, 105, 40, 40);
      ctx.fill();

      ctx.beginPath();
      ctx.rect(160,102.5,45,45);
      ctx.fillStyle = 'rgb(163,0,0)';
      ctx.fill();
      ctx.lineWidth = 5;
      ctx.strokeStyle = 'rgb(204,0,0)';
      ctx.stroke();

    }); // end $(function(){});
</script>

</head>

<body>
   <canvas id="canvas" width=600 height=400></canvas>
</body>
</html>