Q:

Using Linq query when we get record by id how can i assign that value to another column?

Here I wrote simple where condition linq query I'm getting data from the database, but I want to assign that data to another column.
Employee
public class Employee
{
        public string Id{ get; set; }
        public string Name{ get; set; }
        public string Email{ get; set; }
}

Linq query:
public Employee GetEnqDetails(int EnqId)
{
    if (EnqId != null)
    {
        var x = from n in db.Employee
                where n.Id == EnqId
                select n;
        return x.FirstOrDefault();
    }
    else
    {
        return null;
    }
}

Here from Employee table whatever data I'm getting I want to assign that data to another class as
public class EmailContent
{
        public string Subject { get; set; }
        public string Body { get; set; }
}

Here subject =x.Name +"" x.Email  How can i assign that value

A:

So you are getting the Employee details from the method GetEnqDetails() you can create a new instance of the EmailContent with those details:
var employ = GetEnqDetails(101);
if (employ != null)
{
    EmailContent emc = new EmailContent() { Subject = String.Format("{0} {1}", employ.Name, employ.Email), Body = "" };
    // proceed with emc
}

If you don't want to use the filtered employee details, only the requirement is to instantiate the EmailContent with the employee details means you can change the method like the following:
public static EmailContent GetEnqDetails(string EnqId)
{
    if (EnqId != null)
    {
        return db.Employee.Where(n => n.Id == EnqId)
                          .Select(x => new EmailContent()
                          {
                              Subject = String.Format("{0} {1}",
                              x.Name, x.Email),
                              Body = ""
                          }).FirstOrDefault();
    }
    else
    {
        return null;
    }
}

Update as per the comment:
There is a DataType mismatch as specified in the comment, that is EnqId is int and n.Id is string. Please correct them accordingly. I just changed the parameter as string in my code. Because the comparison (if (EnqId != null)) is meaning less in the value is integer. So if you are forwarding with int remove the condition


Q:

How to use conditional statement in conjunction with group_concat?

I have written the following query which uses group_concat :
SELECT p.hostname AS Hostname,
GROUP_CONCAT(t2.status SEPARATOR ' :: ') AS Status,
GROUP_CONCAT(t3.error SEPARATOR ' :: ') AS Title
FROM table p
...
...
WHERE p.hostname regexp 'abc'
GROUP BY p.hostname;

I am getting the following output:
Hostname    Status                  Title
abc.com     PASS :: PASS :: PASS    Title1 :: Title12 :: Title3

I want to add conditional statement such that if it is all PASS :: PASS :: PASS then it should show only one value under status as PASS
If it has one or more FAIL such as PASS :: PASS :: FAIL then it should show only one value under status as FAIL.
Also, it should only show title corresponding to the FAIL. For example, if it is PASS :: PASS :: FAIL then the output should be
Hostname    Status  Title
abc.com     FAIL    title3

In case of multiple FAIL such as PASS :: FAIL :: FAIL the overall status should be FAIL. The title should have value Title2 :: Title3
Hostname    Status      Title
abc.com     FAIL        Title12 :: Title3

If all values for status is PASS then the title should have value NA
Hostname    Status  Title
abc.com     PASS    NA

A:

You can do it with CASE expressions for your conditions:
SELECT p.hostname AS Hostname,
  CASE COUNT(DISTINCT t2.status)
    WHEN 1 THEN MAX(t2.status)
    ELSE 'FAIL'
  END AS Status,
  CASE
    WHEN COUNT(DISTINCT t2.status) = 1 AND MAX(t2.status) = 'PASS' THEN 'NA'
    ELSE GROUP_CONCAT(CASE WHEN t2.status = 'FAIL' THEN t3.error END SEPARATOR ' :: ')
  END AS Title
FROM table p
............
WHERE p.hostname regexp 'abc'
GROUP BY p.hostname;

See a simplified demo.


Q:

Need help creating and installing capnpc-java (CapnProto for Java)

I have a project requiring the use of Cap'n Proto for Java. I have a Linux system and I've successfully installed the Cap'n Proto schema compiler as described here:
https://capnproto.org/install.html
Now following the installation instructions as described here: https://dwrensha.github.io/capnproto-java/index.html, I can't seem to figure out how to generate the capnpc-java plugin. The instructions here seem unclear:

You will need to install the latest release of the Cap’n Proto schema compiler. Then, running make should build capnpc-java.

Running make from where?  I did that from the $WORKDIR/capnproto-java directory but that doesn't work.
The other approach I did was to follow the cmake instructions from from $WORKDIR/capnproto-java/cmake/README.md but that didn't work either. According to that README.md:
mkdir build
cd build
cmake -DCAPNP_PKG_PATH=[path of Capnproto pkgconfig directory (with capnp.pc)] [path of CMakeLists.txt]
Where I set CAPNP_PKG_PATH to be the path of the $WORKDIR/capnproto/c++/pkgconfig directory, and the [path of CMakeLists.txt] to $WORKDIR/capnproto, where $WORKDIR is a directory on my system.
Can anyone help?  I'm not an expert on make system, Makefiles, or cmake. Where does the capnpc-java created?  When I do a which capnpc-java, nothing is showing up (I do however, can successfully which capnp, which is located in /usr/local/bin/)

A:

Looks like I figured it out after some trial and error. It's not straightforward from the README, but at the end of the day, I got the capnpc-java built. This is the approach I did:

Per https://capnproto.org/install.html, follow the instructions From Git
Go to $WORKDIR/capnproto-java/cmake. Follow the instructions in the README.md inside that cmake directory, under Using cmake.
When specifying -DCAPNP_PKG_PATH, specify the path from Step 1, but make sure to include capnp.pc. For example: cmake -DCAPNP_PKG_PATH=$WORKDIR/capnproto/c++/pkgconfig/capnp.pc $WORKDIR/capnproto/CMakeLists.txt
cd to $WORKDIR/capnproto and run make -j6
cd to $WORKDIR/capnproto-java and run make
capnpc-java is generated in $WORKDIR/capnproto-java.  Copy this to /usr/local/bin

I'm assuming this works.  I haven't run the capnp compile yet, but at least this answered my original question.


Q:

How to correctly use ft_string_indexer and ft_one_hot_encoder for multiple columns in SparkR

I have two questions:

How can I convert multiple categorical variables to a big matrix of dummy variables in spark?
How can I get the correct output with the one_hot_encoder and run a (logistic) regression?

I am stuck on how to use the ft_string_indexer and ft_one_hot_encoder to get the right tbl.
As an example, I have made the current dataframe:
library(sparklyr)
library(tidyverse)

sc <- spark_connect(master="yarn-client", spark_home =Sys.getenv("SPARK_HOME"), app_name = "sparklyr",
                    version = "2.1.2", hadoop_version = "2.6", config = configs)

df <- data.frame(
  a=rep(letters[1:4],5),
  b=rep(c("one", "two"), 10),
  y=rbinom(n=20,size=1,prob=0.5))

copy_to(sc, df, "df")

So df currently looks like this:
# Source:   table<df> [?? x 3]
# Database: spark_connection
   a     b         y
   <chr> <chr> <int>
 1 a     one       0
 2 b     two       1
 3 c     one       1
 4 d     two       0
 5 a     one       1
 6 b     two       0
 7 c     one       0
 8 d     two       1
 9 a     one       0
10 b     two       1
# ... with more rows

I run the following sequence of mutations and get the output as:
df2 <- tbl(sc, "df")
df2 %>%
    sdf_mutate(a_idx = ft_string_indexer(a)) %>%
    sdf_mutate(b_idx = ft_string_indexer(b)) %>%
    sdf_mutate(a_vec = ft_one_hot_encoder(a_idx)) %>%
    sdf_mutate(b_vec = ft_one_hot_encoder(b_idx)) %>%
    collect()

# A tibble: 20 x 7
   a     b         y a_idx b_idx a_vec     b_vec
   <chr> <chr> <int> <dbl> <dbl> <list>    <list>
 1 a     one       0     0     0 <dbl [3]> <dbl [1]>
 2 b     two       1     1     1 <dbl [3]> <dbl [1]>
 3 c     one       1     2     0 <dbl [3]> <dbl [1]>
 4 d     two       0     3     1 <dbl [3]> <dbl [1]>
 5 a     one       1     0     0 <dbl [3]> <dbl [1]>
 6 b     two       0     1     1 <dbl [3]> <dbl [1]>
 7 c     one       0     2     0 <dbl [3]> <dbl [1]>
 8 d     two       1     3     1 <dbl [3]> <dbl [1]>
 9 a     one       0     0     0 <dbl [3]> <dbl [1]>
10 b     two       1     1     1 <dbl [3]> <dbl [1]>
11 c     one       1     2     0 <dbl [3]> <dbl [1]>
12 d     two       0     3     1 <dbl [3]> <dbl [1]>
13 a     one       1     0     0 <dbl [3]> <dbl [1]>
14 b     two       0     1     1 <dbl [3]> <dbl [1]>
15 c     one       0     2     0 <dbl [3]> <dbl [1]>
16 d     two       0     3     1 <dbl [3]> <dbl [1]>
17 a     one       0     0     0 <dbl [3]> <dbl [1]>
18 b     two       1     1     1 <dbl [3]> <dbl [1]>
19 c     one       0     2     0 <dbl [3]> <dbl [1]>
20 d     two       0     3     1 <dbl [3]> <dbl [1]>

This output does not seem right to use in the ml_logistic_regression function. Any help on how to optimize the encoding and correct formatting of multiple columns and running a regression on it would be helpful!

A:

The logistic regression classifier requires one column as input so you need to engineer that one column from the encoded a_vec and b_vec. For that you can use the vector assembler like this:
features_idx = ft_vector_assembler(c("a_vec", "b_vec"))


Q:

Why am I getting an undesired output in my Array Queue program?

The program is an Array Based Queue I am attempting to program.
The puzzling output I am getting is:
Enqueuing 500
4199136 500
I cannot figure out why 4199136 is outputting, after the space in the Output function.
I know it is some sort of memory/array management issue I am making, but I can find the flaw. Any insight would be much appreciated.
The code is posted below in its entirety.
#include <iostream>
#include <iomanip>
#include <array>
#define MAX_SIZE 10

using namespace std;

class ABQ
{
    private:
        int a[MAX_SIZE];
        int count, front, back;
    public:

    ABQ()
    {
            front = -1;
            back  = -1;
            count = 0;
    }

    bool IsEmpty()
    {
        return(front == -1 && back == -1);
    }

    bool IsFull()
    {
        return (back + 1) % MAX_SIZE == front ? true : false;
    }

    void Enqueue(int n)
    {
        cout << "Enqueuing " << n << endl;

        if(IsFull())
        {
            cout << "Array Based Queue is FULL" << endl;
            return;
        }

        else
        {
            back = (back + 1) % MAX_SIZE;
        }

        a[back] = n;
    }

    void Dequeue()
    {
        if(IsEmpty())
        {
            cout << "Array Based Queue is EMPTY" << endl;
            return;
        }

        else if(front == back)
        {
            back = front = -1;
        }

        else
        {
            front = (front + 1) % MAX_SIZE;
        }
    }

    int Front()
    {
        if(front == -1)
        {
            {
                return -1;
            }
            return a[front];
        }

        return 0;

    }

    void Output()
    {
        count = (back + MAX_SIZE - front) % MAX_SIZE + 1;

        for(int i = 0; i < count; i++)
        {
            int index = (front + i) % MAX_SIZE;
            cout << a[index] << " ";
        }

        cout << endl << endl;
    }
};

int main()
{
       ABQ Q;
       Q.Enqueue(500);
       Q.Output();

       return 0;
}

A:

It's partly because your initial values for front and back are out of range for your array indexes, and partly because you don't handle front correctly.
After the call to Enqueue(500), front will still be -1 and back will be 0.  When you call Output, this will output two values, one at a[-1], which is Undefined Behavior, and the other at a[0].
Your Output function (and possibly other places) needs to not consider the value at a[front] as a valid element of the array.


Q:

calculate age from dob and given date in pandas and make age as zero if dob is missing in pandas

I have a data frame as shown below.
df:
cust_id         lead_date            dob
1               2016-12-25           1989-12-20
2               2017-10-25           1980-09-20
3               2016-11-25           NaN
4               2014-04-25           1989-12-20
5               2019-12-21           NaN

From the above I would like to calculate age as difference of lead_date with dob in years.
if dob is NaN then make age as 0.
Expected output:
cust_id         lead_date            dob              age
1               2016-12-25           1989-12-20       27
2               2017-10-25           1980-09-20       37
3               2016-11-25           NaN              0
4               2014-04-25           1989-12-20       25
5               2019-12-21           NaN              0

A:

You can do:
# convert to datetime type
df['lead_date'] = pd.to_datetime(df.lead_date)
df['dob'] = pd.to_datetime(df.dob)

df['age'] = (df.lead_date.dt.year - df.dob.dt.year).fillna(0)

Output:
   cust_id  lead_date        dob   age
0        1 2016-12-25 1989-12-20  27.0
1        2 2017-10-25 1980-09-20  37.0
2        3 2016-11-25        NaT   0.0
3        4 2014-04-25 1989-12-20  25.0
4        5 2019-12-21        NaT   0.0


Q:

Coredata in swift

Hello I am having an issue with core data in Swift, this doesn't show an error but also doesn't print anything when I believe it should be returning 'Joe' + 'pass' in console. Could anyone help please?
import UIKit
import CoreData

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    var appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

    var context:NSManagedObjectContext = appDel.managedObjectContext

    var newUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) as NSManagedObject

    newUser.setValue("Joe", forKey: "username")

    newUser.setValue("pass", forKey: "password")

    do {
     try context.save()
    } catch let error {
        print("Couldn't save user data")
        print(error)
    }

    let request = NSFetchRequest(entityName: "Users")
        request.returnsObjectsAsFaults = false

    do {
        var results = try context.executeFetchRequest(request)
        results = results as! [NSManagedObject]
        if results.count > 0 {
        for results in results {
            print(results)
            }}
    } catch let error as NSError {
        print(error)
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

A:

I finally realised what my issue was, I hadn't actually renamed by Entity to 'Users' I'd kept it as 'Entity' so when I was doing
let newUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) as NSManagedObject
let request = NSFetchRequest(entityName: "Users")

I should have actually have replaced both Users with 'Entity' which now fixes my issue, thanks I guess for your help anyway!


Q:

CodeIgniter not getting the resized image

This is the code which I am trying to run..
I have stored the image in images folder whose path is: C:\xampp\htdocs\ci\images, and is at the same level at that of the application folder
public function display(){
    $config['image_library'] = 'gd2';
    $config['source_image'] = '/images/mypic.jpg';
    $config['new_image']='/images/re_mypic.jpg';
    $config['create_thumb'] = TRUE;
    $config['maintain_ratio'] = TRUE;
    $config['width']    = 75;
    $config['height']   = 50;
    $this->load->library('image_lib', $config);
    $this->image_lib->resize();
}

I am not getting any error or something

A:

Add this and check your code errors
if ( ! $this->image_lib->resize()) {
    echo $this->image_lib->display_errors();
}


Q:

Combining a task (grunt-bump) to start after a prompt via the grunt-prompt task

With Grunt I'm running a task which bumps my version number in my package.json file. But I want to prompt the user which versions he/she want's to update. If it's a normal update you run a minor increment (x.+1.x), and when its a patch or hotfix it should run a (x.x.+1). For this I have 2 grunt tasks:
    /*
     * Bump the version number to a new version
     */

    bump: {
       options: {
         files: ['package.json'],
         updateConfigs: [],
         commit: true,
         commitMessage: 'Release v<%= pkg.version %>',
         commitFiles: ['package.json'],
         createTag: true,
         tagName: 'v<%= pkg.version %>',
         tagMessage: 'Version <%= pkg.version %>',
         push: true,
         pushTo: '<%= aws.gitUrl %>',
         gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d',
         globalReplace: false,
         prereleaseName: false,
         regExp: false
       }
     },

     /*
      * Prompt to see which bump should happen
      */

     prompt: {
       bumptype: {
         options: {
           questions: [
             {
               config: 'bump.increment',
               type: 'list',
               message: 'Bump version from ' + '<%= pkg.version %> to:',
               choices: [
                  {
                      value: 'patch',
                      name: 'Patch: Backwards-compatible bug fixes.'
                  },
                  {
                      value: 'minor',
                      name: 'Minor: Add functionality in a backwards-compatible manner.'
                  },
                ],
               }
             ],
            then: function(results) {
                 console.log(results['bump.increment']); // this outputs 'minor' and 'patch' to the console
             }
           }, // options
         } // bumptype
       }, // prompt

And after this I want to run it in a custom task like this:
grunt.registerTask('test', '', function () {
 grunt.task.run('prompt:bumptype');

// Maybe a conditional which calls the results of prompt here?
// grunt.task.run('bump'); // this is the bump call which should be infuenced by either 'patch' or 'minor'

});

But now as I run a $ grunt test command, I do get prompted and afterwards it's running the bump minor task no matter which option you choose.

The grunt bump option normally takes the following parameters:
$ grunt bump:minor
$ grunt bump:patch

So should you run a conditional in the prompt options or at the registerTask command?

A:

The grunt task can be added to the 'then' property of the grunt-prompt:
then: function(results) {

    // console.log(results['bump.increment']);

    // run the correct bump version based on answer
    if (results['bump.increment'] === 'patch') {
      grunt.task.run('bump:patch');
    } else {
      grunt.task.run('bump:minor');
    }

}


Q:

How to print text file left to right, and then upside down?

My goal for this program is to read a text file, print it normally, then print it flipped from left to right, and then flipped upside down.  I can print the original, however I'm unsure of how to read the file so it will print in the other two formats, and how to print in these formats.  I can only import the file once.
Here is an example output, if my description is inadequate.

The code as it is now:
import java.io.*;
import java.util.*;
public class Problem2
{
    public static void main(String[] args) throws IOException
    {
        File marge = new File("marge.txt");
        Scanner fileScan = new Scanner(marge);
        String original;
        while (fileScan.hasNext())
        {
            original = fileScan.nextLine();
            System.out.println(original);
        }
        String lefttoright;
        while (fileScan.hasNext())
        {
            lefttoright = fileScan.nextLine();
            System.out.println(lefttoright);
        }
        String upsidedown;
        while (fileScan.hasNext())
        {
            upsidedown = fileScan.nextLine();
            System.out.println(upsidedown);
        }
        fileScan.close();
    }
}

A:

Either use suggestion from YCF_L or use below solution.
import java.io.*;
import java.util.*;

public class Problem2 {
    public static void main(String[] args) throws IOException {
        File marge = new File("marge.txt");
        Scanner fileScan = new Scanner(marge);
        String original;
        while (fileScan.hasNext()) {
            original = fileScan.nextLine();
            System.out.println(original);
        }
        fileScan = new Scanner(marge);
        String lefttoright;
        while (fileScan.hasNext()) {
            lefttoright = fileScan.nextLine();
            StringBuffer sb = new StringBuffer(lefttoright);
            System.out.println(sb.reverse());
        }
        fileScan = new Scanner(marge);
        String upsidedown;
        Stack<String> list = new Stack<String>();
        while (fileScan.hasNext()) {
            upsidedown = fileScan.nextLine();
            list.push(upsidedown);
        }
        for (int i = 0; i <= list.size(); i++) {
            System.out.println(list.pop());
        }

        fileScan.close();
    }
}


Q:

How to collect elements of a collection basing on a result of some method?

Suppose we have a list of values sorted according to some ordering. We also have a map of elements mapped to these values. We want to obtain a collection of elements from the map in the same order as their keys are in the list. A straightforward method to do this is:
val order = Seq("a", "b", "c")
val map = Map("a" -> "aaa", "c" -> "ccc")

val elems = order.map(map.get(_)).filter(_.isDefined).map(_.get)

However the program needs to iterate over the collection three times. Is it possible to implement this functionality more efficiently? In particular, is it possible to do this with collect method?

A:

Well, a standard Scala map is also a PartialFunction, so you can use "collect".
val elems = order.collect(map)

A:

More generally you can use views; then the collection is only iterated once and all three operations are applied as you go:
order.view.map(map.get).filter(_.isDefined).map(_.get).force


Q:

MS Access 2010 SQL Top 3 Sales in Group by

I have a table with columns such as year, quarter, team and price. it shows every sale from the team. We have 10 teams in the firm.
I want to know for each quarter of each year, which three teams sold the most overall. So where am I stuck? At this point I grouped the total sales per team, per quarter, per year. Still missingt o only get the three best teams with highest sales. I got this so far:
SELECT
    a1.year,
    a1.quarter,
    a1.team,
    sum(a1.price) as Total

FROM
    tbl_sales a1

inner JOIN
    tbl_sales a2
        ON a1.year = a2.year
            and a1.quarter = a2.quarter
            and a1.team = a2.team
            and a1.price = a2.price
     where
           some restrictions here
GROUP BY
    a1.year,
    a1.quarter,
    a1.team

Something tells me I am close, that just a subquery with the top function will help but I just can't figure it out. Any help is very much appreciated :)
Thanks a lot!

A:

Try:
SELECT TOP 3
    a1.year,
    a1.quarter,
    a1.team,
    sum(a1.price) as Total

FROM
    tbl_sales a1

inner JOIN
    tbl_sales a2
        ON a1.year = a2.year
            and a1.quarter = a2.quarter
            and a1.team = a2.team
            and a1.price = a2.price
     where
           some restrictions here
GROUP BY
    a1.year,
    a1.quarter,
    a1.team

ORDER BY
    sum(a1.price) DESC

Edit, try the following, you might need additional criteria to ensure you get the correct resultset but this should return the top 3 of each quarter that is specified in the where clause, I don't know why you are using a self join so I left that out but it can be added back in if necessary:
SELECT TOP 3
    a1.year,
    a1.quarter,
    a1.team,
    sum(a1.price) as Total

FROM
    tbl_sales a1

WHERE
     'some restrictions here'
     AND a1.quarter = 1 --(or however quarters are identified)
     AND a1.year = 2015 --(or however years are identified)

GROUP BY
    a1.year,
    a1.quarter,
    a1.team

ORDER BY
    sum(a1.price) DESC

UNION ALL

SELECT TOP 3
    a2.year,
    a2.quarter,
    a2.team,
    sum(a2.price) as Total

FROM
    tbl_sales a2

WHERE
    'some restrictions here'
    AND a2.quarter = 2
    AND a2.year = 2015

GROUP BY
    a2.year,
    a2.quarter,
    a2.team

ORDER BY
    sum(a2.price) DESC

UNION ALL

SELECT TOP 3
    a3.year,
    a3.quarter,
    a3.team,
    sum(a3.price) as Total

FROM
    tbl_sales a3

WHERE
    'some restrictions here'
    AND a3.quarter = 3
    AND a3.year = 2015

GROUP BY
    a3.year,
    a3.quarter,
    a3.team

ORDER BY
    sum(a3.price) DESC

UNION ALL

SELECT TOP 3
    a1.year,
    a1.quarter,
    a1.team,
    sum(a1.price) as Total

FROM
    tbl_sales a4

WHERE
    'some restrictions here'
    AND a4.quarter = 4
    AND a4.year = 2015

GROUP BY
    a4.year,
    a4.quarter,
    a4.team

ORDER BY
    sum(a4.price) DESC

As you can see there is basically no difference between the tables except the where clause, you aren't limited to a union of just those 4 tables, it is just an example but just keep in mind that if you need to cover more quarters you will need to add more tables to be unioned. This can get very unwieldy as it requires you to keep adding tables to the union as time goes on.


Q:

Getting key from returned array

I'm working in WooCommerce, but my question is related to basic PHP foreach statements.
I have a function that returns a multidimensional array.  The topmost dimension, the key string is what I need. If you've familiar, $order->get_items();.
The order_item_id is stored as the key like this:
'488' => Array( /* Array stuffs */ )

That 488 is what I need.  It wouldn't be a problem if the function I'm working with's foreach statement was:
foreach ($items as $k => $v)

Where I could just use $k, but it's set up as:
foreach ($items as $item)

Is there a way to set the value of the key in the array and pass it along as a parameter?
UPDATE:
Here is the function as it works.
foreach($order_items as $item) {
    $product = $order->get_product_from_item($item);
    $gc_enabled = get_post_meta($product->id, 'ignite_gift_enabled', true);
    if ( ! $gc_enabled)
        continue;
    $coupon_prefix = get_post_meta($product->id, '_coupon_prefix', true);
    if ( ! $coupon_prefix)
        $coupon_prefix = '';
    for ($x = 1; $x <= $item['qty']; $x++) {
        $new_coupon = $this->adjust_voucher( $coupon_prefix, $mode, $msg_details, $order_id, $order_item_id, $product->id );
    }
}

$order_items is an array of items, the keys of which I need to pass along to other functions referenced, specificaly adjust_voucher.

A:

Just change the foreach syntax to be foreach($items as $key => $item).  This would give you access to $key while not impacting any existing code in the loop which relies on $item.


Q:

FDD or SCD deployment using VS 2017

How do I package .net core application as 'a framework-dependent deployment (FDD)' or 'a self-contained deployment (SCD)' using Visual Studio 2017 (IDE) ? I am aware on how this can be done through dotnet CLI / command line.

A:

See Visual Studio and Self Containing Deployments
Setting the <RuntimeIdentifier>XXX</RuntimeIdentifier> property in your .csproj makes it self-contained.  Not setting <RuntimeIdentifier> makes it framework-dependent.

A:

It seems this feature is not available at the momnet. I created a feature request at suggestions.


Q:

Either json or Soap to exchange data in my project?

I am doing a car rental software, in which a front end back end are there, where the back end will do the accounting part. I have to send some data like customer name, amount, currency etc. to account engine to prepare the ledgers. I am confused whether to use json or soap for information exchange between front and back ends. ur suggestions are precious. thank u..

A:

Use JSON for data serialization.  It's clean, simple, compact, widely supported, and understands data types.  Use SOAP only if you like pain.  It is a bloated sack of cruft built upon another bloated sack of cruft.

A:

Use JSON.
My argument is that JSON maps directly to and from native data types in common scripting languages.
If you use Python, then None <-> null, True <-> true, False <-> false, int/float <-> Number, str/unicode <-> String, list <-> Array and dict <-> Object. You feel right at home with JSON.
If you use PHP, there should be similar mappings.
XML is always a foreign language for any programming language except Scala.


Q:

PHP preg_match creating empty arrays

I am using the following code:
foreach ($_POST as $key => $value) {
    (preg_match("/^._box_(\d+)_5$/", $key, $matches));
    //$prodid[] = $matches[1];
    $firephp->log($matches, 'matches');
    };

This code is working on the following information being $_POSTed from the previous page:
array(
['clin'] =>
['clinmail'] =>
['quest_3'] =>
['quest_7'] =>
['quest_8'] =>
['quest_9'] =>
['quest_10'] =>
['quest_15'] =>
['quest_16'] =>
['hosp'] => 8
['user'] => 16
['a_box_15_5'] => 2
['a_box_16_5'] => 2
['b_box_1_5'] => '$0.00'
['b_box_29_5'] => 1
)

The problem is I get the following result:
matches: array()
matches: array()
matches: array()
matches: array()
matches: array()
matches: array()
matches: array()
matches: array()
matches: array()
matches: array()
matches: array()
matches: array('0'=>'a_box_15_5', '1'=>'15')
matches: array('0'=>'a_box_16_5', '1'=>'16')
matches: array('0'=>'b_box_1_5', '1'=>'1')
matches: array('0'=>'b_box_29_5', '1'=>'29')

I don't want it matching the first 11 positions. I only want the results that actually match what I'm looking for, which in this case is that last four $_POST's isn't that what preg_match is supposed to do? How can I limit it to just the matches?

A:

preg_match() works correctly: if there are no matches, $matches will be empty. But you're not doing anything different if there are no matches, you're always calling $firephp->log(), matches or not.
preg_match() returns 1 if the pattern matches, or 0 otherwise and false if an error occurred, so you can use that to see if there are matches, and only then call $firephp->log():
foreach ($_POST as $key => $value) {
    if (preg_match('/^._box_(\d+)_5$/', $key, $matches)) {
        $firephp->log($matches, 'matches');
    }
}


Q:

(AWS) Can't launch RDS in my chosen VPC

I'm following AWS's instructions Scenario 2: VPC with Public and Private Subnets and am having issues at the point I try to launch a DB server.
When I launch my instance, all is fine and I am able to assign it to my newly created VPC.  However, when it comes to launch the RDS, the only VPC available (on step 4, configure advanced settings) is the default VPC (ie not the one I created as per their instructions).
Has anyone any idea about this or indeed how to resolve it?

A:

RDS requires a little more setup than an EC2 instance if you want to launch it within a VPC.
Specifically, you need to create:

a DB subnet group within the VPC
a VPC security group for the RDS instance

The documentation is a little buried in the AWS RDS documents. It can be found here:
Creating a DB Instance in a VPC


Q:

Terminal keeps saying ./studio.sh not found in Linux Mint

When I run ./studio.sh I get this error for some reason:
`./studio.sh
 ./studio.sh: 1: ./studio.sh: which: not found
 ./studio.sh: 1: ./studio.sh: which: not found
 ./studio.sh: 1: ./studio.sh: which: not found
 ./studio.sh: 1: ./studio.sh: which: not found
 ./studio.sh: 1: ./studio.sh: which: not found
 ./studio.sh: 1: ./studio.sh: which: not found
 ./studio.sh: 1: ./studio.sh: which: not found
 ./studio.sh: 1: ./studio.sh: which: not found
 ./studio.sh: 1: ./studio.sh: which: not found
 ./studio.sh: 1: ./studio.sh: which: not found
 ERROR: Cannot start Android Studio
 Required tools are missing - check beginning of "./studio.sh" file for details.`

A:

Looks like you don't have the which tool installed.
It should be contained in the debianutils package.
Try to install:
sudo apt-get install debianutils
or reinstall:
sudo apt-get install --reinstall debianutils


Q:

(sharp) # sign in query string and SEO

I have a site Index.html and there is a categories menu generated from database. Menu consists of HTML anchors, but href attribute is always something like "Index.html#cat=xyz" because content of each category is generated through AJAX call.

From the AJAX side everything works, but I want to ask if for example Google or other search engine will index these links which contains # (sharp) sign. Thanks for answers.

A:

You're asking the wrong question.  If you want your links to be indexed, make them obvious to a crawler about the content.  Multiple links to the same page won't help your SEO efforts.  Consider creating a separate page for "contacts" "investor information" "careers" (or whatever your categories are) and publishing them.  Then your link becomes
careers

etc.  When a human sees this link (your actual end target) he'll be able to make a better choice whether or not it's the "right" result.


Q:

Nested Lazy Loading in Angular Routes

I created a facsimile of a project I am having issues in:
https://stackblitz.com/edit/angular-frlpmk
In this project, I have two lazy loaded modules:

Customers
Orders

The customers module in turn lazy loads the Address module:
const routes: Routes = [
  {
    path: '',
    component: CustomerListComponent,
    children: [
            {
                path: 'addresses',
                loadChildren: './address/address.module'
            },
        ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class CustomersRoutingModule { }

The error I get from this JIT program (through stackblitz) is:
errors.js:55 ERROR Error: Uncaught (in promise): Error: No NgModule metadata found for 'undefined'.
Error: No NgModule metadata found for 'undefined'.

When I run this project with aot, I get:
ERROR Error: Uncaught (in promise): Error: Cannot find module './address/address.module'.
Error: Cannot find module './address/address.module'.
    at webpackAsyncContext (eval at ../../../../../src/$$_lazy_route_resource lazy recursive (main.bundle.js:6), <anonymous>:14:25)
    at SystemJsNgModuleLoader.loadAndCompile (core.js:6558)
    at SystemJsNgModuleLoader.load (core.js:6542)
    at RouterConfigLoader.loadModuleFactory (router.js:4589)
    at RouterConfigLoader.load (router.js:4569)
    at MergeMapSubscriber.eval [as project] (router.js:2061)
    at MergeMapSubscriber._tryNext (mergeMap.js:128)
    at MergeMapSubscriber._next (mergeMap.js:118)
    at MergeMapSubscriber.Subscriber.next (Subscriber.js:92)
    at ScalarObservable._subscribe (ScalarObservable.js:51)
    at webpackAsyncContext (eval at ../../../../../src/$$_lazy_route_resource lazy recursive (main.bundle.js:6), <anonymous>:14:25)
    at SystemJsNgModuleLoader.loadAndCompile (core.js:6558)
    at SystemJsNgModuleLoader.load (core.js:6542)
    at RouterConfigLoader.loadModuleFactory (router.js:4589)
    at RouterConfigLoader.load (router.js:4569)
    at MergeMapSubscriber.eval [as project] (router.js:2061)
    at MergeMapSubscriber._tryNext (mergeMap.js:128)
    at MergeMapSubscriber._next (mergeMap.js:118)
    at MergeMapSubscriber.Subscriber.next (Subscriber.js:92)
    at ScalarObservable._subscribe (ScalarObservable.js:51)
    at resolvePromise (zone.js:809)
    at resolvePromise (zone.js:775)
    at eval (zone.js:858)
    at ZoneDelegate.invokeTask (zone.js:421)
    at Object.onInvokeTask (core.js:4740)
    at ZoneDelegate.invokeTask (zone.js:420)
    at Zone.runTask (zone.js:188)
    at drainMicroTaskQueue (zone.js:595)
    at ZoneTask.invokeTask [as invoke] (zone.js:500)
    at invokeTask (zone.js:1517)

It is not able to find the Address module, and when I look at the webpack output, Custmers.module is there but not address:
 ** NG Live Development Server is listening on localhost:1234, open your browser on http://localhost:1234/ **
Date: 2018-03-15T17:08:51.053Z
Hash: 9a854b91e6ee905379c5
Time: 7314ms
chunk {customers.module} customers.module.chunk.js () 22.1 kB  [rendered]
chunk {inline} inline.bundle.js (inline) 5.79 kB [entry] [rendered]
chunk {main} main.bundle.js (main) 25.6 kB [initial] [rendered]
chunk {orders.module} orders.module.chunk.js () 14.8 kB  [rendered]
chunk {polyfills} polyfills.bundle.js (polyfills) 553 kB [initial] [rendered]
chunk {styles} styles.bundle.js (styles) 37.8 kB [initial] [rendered]
chunk {vendor} vendor.bundle.js (vendor) 9.5 MB [initial] [rendered]

I think webpack is not able to find this module. Is there a proper way to nest a lazy loaded module in another? Alternatively, is there a way to manually tell webpack about this module?
Added this repo: https://github.com/jdell64/ngNestedLazyLoads

A:

I think your routes should be like this:
const routes: Routes = [
    {
        path: '',
        component: CustomerListComponent
    },
    {
        path: 'addresses',
        loadChildren: 'app/customers/address/address.module#AddressModule'
    }
];


Q:

How do I notice time zone changes in Android?

One can listen for all kind of configuration changes by configuring android:configChanges in the AndroidManifest.xml and act accordingly in the activity's onConfigrationChanged method (Android docs).
What I didn't find so far is however a handler that acts on time zone changes. This could for example happen if the user often crosses time zones after a journey and wants to see his application contents in the local time of the country where he's in.
Is the only possibility I have here really to check TimeZone.getDefault() regularily myself and adapt my times accordingly?

A:

Listen for the broadcasted Intent: android.intent.action.TIMEZONE_CHANGED


Q:

When a destructor is called and what is used for in this example?

Can anyone tells me what the destructor does in this code? a call example:
"
int year = 2012;
string hello = "Hello";
cout << format("% world! The year is %\n") << hello << year;

"
I dont get the idea of a destructor with "while" . . . why do we need it? this should print: "Hello world! The year is 2012" . . . if I understand well, so the destructor is called when a "throw" is called that means in the end of the str ?
TempFormat format(const char*) {
  return TempFormat(const char*);
}

class TempFormat {
  const char* str;
public:
  TempFormat(const char* str) : str(str) {}

  friend Format& operator<<(ostream& os, TempFormat& f) {
    return Format(f.str, os);
  }
};

class Format {
  const char* str;
  ostream& os;
public:
  Format(const char* str, ostream& os) : str(str), os(os) {}

  template<class T>
  Format& operator<<(const T& t) {
    while(*str && *str != '%'){
      os << *str;
      str++;
    }
    if (*str != '%') {
      throw std::exception();
    }
    os << t;
    while(*str && *str != '%'){
      os << *str;
      str++;
    }
    return *this;
  }

  ~Format() {
    while(*str && *str != '%'){
      os << *str;
      str++;
    }
    if (*str == '%') {
      throw std::exception();
    }
  }
};

A:

The destructor merely checks that all the '%' in the format strings have been processed. If the string contains more '%' than the object received arguments, the destructor throws an exception.
Edit: The line cout << format("% world! The year is %\n") << hello << year; is very devious because none of the << operators here are classical ostream& operator<<(ostream&, type) overloads.

The first << is actually Format& operator<<(ostream&, TempFormat&), which returns a Format object. It's also an abomination that returns a local variable by reference, and takes a nameless temporary variable by non-constant reference. Does it even compile? Its prototype should probably be Format operator<<(ostream&, TempFormat const&) instead. But without Return Value Optimization (or a good move constructor), it would throw.
The second '<<' is actually Format's insertion operator Format& Format::operator<<(const T&), with the string type.
The third '<<' is actually Format's insertion operator Format& Format::operator<<(const T&), with the int type.

Since the Format object is a temporary, it's destroyed at the end of the line, after its operator<< has been called twice. And since it contained exactly two '%', its destructor doesn't throw.


Q:

change extension and move file, using vb.net

I have the following code, which changes the extension of a txt to doc, and then moves it (from d:\1 to d:\2). The extension changes successfully, but it does not move, and I get an error

Cannot create a file when that file already exists.

Please suggest.
For Each filePath In Directory.GetFiles("D:\1", "*.txt")
    File.Move(filePath, Path.ChangeExtension(filePath, ".doc"))
Next
Dim filesToMove = From f In New DirectoryInfo("d:\1").EnumerateFiles("*.doc")
For Each f In filesToMove
    f.MoveTo("d:\2")
Next

A:

This will check for an existing file of the same name and delete it first (you may want to handle this differently). It will then move and rename in one call to File.Move
Dim directory1 = "D:\1"
Dim directory2 = "D:\2"
For Each oldFileName In Directory.GetFiles(directory1, "*.txt")
    Dim newFileName = Path.ChangeExtension(oldFileName, ".doc").Replace(directory1, directory2)
    If File.Exists(newFileName) Then File.Delete(newFileName)
    File.Move(oldFileName, newFileName)
Next


Q:

Had to shim my double top plate -- how should I secure the trusses?

I am building a new detached garage, and one corner of the footing was about 1.5" low. To address this, I installed shims between the two top plates, as shown below. The size of the shim increases from left to right to make up the space. This way, the final height is level all the way around the building.

Now I need to secure the trusses to the top plate. For all the other trusses, I was able to use uplift screws from inside.
For the four trusses shown, I installed the screws from above -- otherwise they would not have been long enough to grab the truss. The manufacturer's documentation (pdf) indicates this is allowable:

Is this sufficient? Do I also need to connect down to the plate below? How?

A:

This is the solution I went with, one of two suggest by the inspector:

The double top plate acts as a diaphragm to distribute load, so it needs to be solid. I used strips of plywood of increasing thickness to shim up and fill the gap.
As Jack suggested, I also screwed up into the trusses from the bottom, and used hurricane ties on the truss I couldn't get to from the bottom.
The inspector's other suggestion was to add a stud below each truss.


Q:

Follow-up of search values from first column in html table using JS?

This is my follow-up question of this... See here. I have a jscript(courtesy of hex494D49), searching values from first column.
All I need is, when the values is searching by the user, the table headers will also displayed and if the values is not store. There's a message will display like this "No results found". How to do that?
Here's the JSfiddle file with html
Here's the JScript:
document.getElementById('term').onkeyup = function(){
var term = this.value;
var column = 0;
var pattern = new RegExp(term, 'g');
var table = document.getElementById('dataTable');
var tr = table.getElementsByTagName('TR');
for(var i = 0; i < tr.length; i++){
  var td = tr[i].getElementsByTagName('TD');
  for(var j = 0; j < td.length; j++){
    if(j == column && td[j].innerHTML == term){
      console.log('Found it: ' + td[j].innerHTML);
      tr[i].style.display = 'block';
      return;
      alert('Found it: ' + td[j].innerHTML);
    }else{
      tr[i].style.display = 'none';
    }
  }
}
};

A:

This would be the table markup. As you can see, I added thead, tbody and tfoot groups

<input type="text" name="term" id="term" autocomplete = "off" />

        Example No.
        Column 1
        Column 2

        345678917
        Test 1
        one_test1@gmail.com

        3512376894
        Test 2
        two.test2@hotmail.com

Default CSS for the markup above. Next step would be merging the following with the rest of your CSS.
table thead {
    display: table-row-group;
}

table tbody {
    display: table-row-group;
}

table tbody tr {
    display: none;
}

And finally the JavaScript snippet using getElementsByTagName() method
// JavaScript
document.getElementById('term').onkeyup = function(){
  var term = this.value;
  var column = 0;
  var msg = 'No results found!';
  var pattern = new RegExp(term, 'g');
  var table = document.getElementById('dataTable');
  var tr = table.getElementsByTagName('TR');

  for(var i = 0; i < tr.length; i++){
    var td = tr[i].getElementsByTagName('TD');
    for(var j = 0; j < td.length; j++){
      if(j == column && td[j].innerHTML == term){
        tr[i].style.display = 'table-row';
        table.tFoot.innerHTML = '';
        return;
      }else{
        tr[i].style.display = 'none';
        table.tFoot.innerHTML = msg;
      }
    }
  }
};

Working jsFiddle | Version without tfoot jsFiddle

The same as above but using rows[] and cells[] collection
HTML

<input type="text" id="search" autocomplete = "off" />

            Product
            Manufacturer
            Price
            InStock

            MacBook Air
            Apple
            $456
            85

            Arc GIS
            ESRI
            $4556
            15

            3ds MAX
            Aurodesk
            $6556
            359

            Windows 7
            Micorsoft
            $256
            2567

CSS
table thead {
    display: table-row-group;
}
table tbody tr {
    display: none;
}

JavaScript
document.getElementById('search').onkeyup = function(){
    var table = document.getElementById('table'),
        tr = table.rows, td,
        term = this.value.toLowerCase(), column = 0, i, j,
        message = document.getElementById('message');

    for(i = 1; i < tr.length; i++){
        td = tr[i].cells;
        for(j = 0; j < td.length; j++){
            if(j == column && td[j].innerHTML.toLowerCase() == term){
                tr[i].style.display = 'table-row';
                message.innerHTML = '';
                return;
            }else{
                tr[i].style.display = 'none';
                message.innerHTML = 'No results found!';
            }
        }
    }
};

Working jsFiddle If you won't use thead and tbody in your table here is another version jsFiddle
I case you want to search all columns, just change this line
if(j == column && td[j].innerHTML.toLowerCase() == term){

to this one
if(td[j].innerHTML.toLowerCase() == term){

And finally, if you want to have more flexible search try the version below
document.getElementById('search').onkeyup = function(){
    var table = document.getElementById('table'),
        tr = table.rows, td,
        term = this.value.toLowerCase().trim(), column = 0, i, j,
        message = document.getElementById('message'),
        pattern = new RegExp(term, 'gi');

    for(i = 1; i < tr.length; i++){
        td = tr[i].cells;
        for(j = 0; j  0 && td[j].innerHTML.match(pattern)){
                tr[i].style.display = 'table-row';
                message.innerHTML = '';
                return;
            }else{
                tr[i].style.display = 'none';
                message.innerHTML = 'No results found!';
            }
        }
    }
};

Working jsFiddle


Q:

Out of memory error when parallelizing merge sort

I try to parallelize my merge sort implementation: http://pastebin.com/2uMGjTxr.
I want to create as many threads as Java-VM can provide. I want to determine the maximum number of possible threads using java.lang.Runtime.
So I came up with a class called MergeThread:
public class MergeThread implements Runnable{

    public int[] list;
    int sIndex, eIndex;

    public MergeThread(int[] pArray, int pStartIndex, int pEndIndex){
        list = pArray;
        sIndex = pStartIndex;
        eIndex = pEndIndex;
    }

    public void run(){
        list = mergeSort(list, sIndex, eIndex);
    }

    /**
     * Merges two sorted int array into one new sorted array.
     * @param lhs
     * @param rhs
     * @return
     */
    private static int[] merge(int[] lhs, int[] rhs) {
        int[] result = new int[lhs.length + rhs.length];

        int leftIndex = 0;
        int rightIndex = 0;
        while(leftIndex < lhs.length && rightIndex < rhs.length) {
            if(lhs[leftIndex] <= rhs[rightIndex]) {
                result[leftIndex + rightIndex] = lhs[leftIndex];
                leftIndex++;
            } else {
                result[leftIndex + rightIndex] = rhs[rightIndex];
                rightIndex++;
            }
        }

        while(leftIndex < lhs.length) {
            result[leftIndex + rightIndex] = lhs[leftIndex];
            leftIndex++;
        }

        while(rightIndex < rhs.length) {
            result[leftIndex + rightIndex] = rhs[rightIndex];
            rightIndex++;
        }

        return result;
    }

    /**
     * Sorts an array from index startIndex (inclusive) to endIndex (exclusive).
     * @param array
     * @param startIndex
     * @param endIndex
     * @return new array that is sorted
     */
    private static int[] mergeSort(int[] array, int startIndex, int endIndex) {
        int length = endIndex - startIndex;
        if(length == 0) {
            return new int[]{};
        }
        if(length == 1) {
            return new int[]{array[startIndex]};
        }

        int halfLength = length / 2;
        //int[] sortedLeftPart = mergeSort(array, startIndex, startIndex + halfLength);
        MergeThread m1 = new MergeThread(array, startIndex, startIndex + halfLength);
        Thread t1 = new Thread(m1);
        t1.start();
        //int[] sortedRightPart = mergeSort(array, startIndex + halfLength, endIndex);
        MergeThread m2 = new MergeThread(array, startIndex + halfLength, endIndex);
        Thread t2 = new Thread(m2);
        t2.start();
        try{
        t1.join();
        t2.join();
        }catch(InterruptedException e){}
        return merge(m1.list, m2.list);
    }
}

And a class that actually starts the process
import java.util.Random;

public class Aufg2 {
    public static Random random = new Random(100);

    public static void main(String[] args) {
        int[] array = createRandomArray(10000000);

        long time = System.currentTimeMillis();

        int[] sortedArray = sort(array);

        if(sortedArray.length != array.length || !isSorted(sortedArray)) {
            System.err.println("Failed to sort given array! :-(");
            return;
        }
        System.out.println("Success! Sorting took " + (System.currentTimeMillis() - time) + "ms.");
    }

    /**
     * Creates a randomly filled array of given length
     * @param length
     * @return
     */
    private static int[] createRandomArray(int length) {
        int[] result = new int[length];
        for(int i = 0; i < length; i++) {
            result[i] = random.nextInt();
        }
        return result;
    }

    /**
     * Checks whether a given int array is sorted in ascending order
     * @param array
     * @return true if the given int array is sorted; false otherwise.
     */
    private static boolean isSorted(int[] array) {
        for(int i = 1; i < array.length; i++) {
            if(array[i] < array[i-1]) {
                return false;
            }
        }
        return true;
    }

    /**
     * Sorts a given array (ascending order)
     * @param array
     * @return
     */
    private static int[] sort(int[] array){
        //TODO: use multiple threads to speed up the sorting
        MergeThread m = new MergeThread(array, 0, array.length);

        try{

        Thread t1 = new Thread(m);
        t1.start();
        t1.join();
        }catch(InterruptedException e){

        }
        return m.list;
    }
}

However this merge sort does not work. The console prints a lot of java.lang.OutOfMemmoryError's unable to create new native thread.
Later the message changes to something like java heap.
What do I have to change to get the merge sort working and how do I use java.lang.Runtime for that?

A:

The divide and conquer mechanism has you trying to create something like 5000000 threads - and each of those wants as default 256KB (IIRC) of stack memory. Still surprised why you get an OutOfMemmoryError?
Limit the number of threads by using a fixed size thread pool - experiment a bit with the number of threads in the pool, but anything much more than the number of cores in your system is very unlikely to improve performance (and may indeed reduce it).


Q:

Photoshop CS4 color profile weirdness

My color profile in Photoshop CS4 on Windows is always set to "Monitor RGB" when I startup photoshop, which gives me a weird color tone as shown in the screenshot below.
For example, this is how calculator looks like in Photoshop.
I can then go to View > Proof setup > Windows RGB to fix it. However every time I start Photoshop it is again wrong and I have to make this setting over and over again. How can I fix this forever?

A:

Step 1:
Choose a collection of default settings that best reflect your workflow
http://help.adobe.com/en_US/Photoshop/11.0/WS921B081D-C675-40ff-93AD-6A60C641A136.html


Q:

Rotation to a specific angle not working

I have a image of a cartoon face to rotate it just like as shaking head a little bit from left to right (as we do when hearing music) for a  specific duration of time like 5-7 seconds. So, i am doing the following:
-(void)rotation{

CABasicAnimation *rotate = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
[rotate setFromValue:[NSNumber numberWithFloat:0.0]];
[rotate setToValue:[NSNumber numberWithFloat:45]];
[rotate setDuration:5.0];
[rotate setAutoreverses:YES];
[rotate setTimingFunction:[CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionEaseInEaseOut]];

[[faceImage layer] addAnimation:rotate forKey:@"dangleFaceImage"];

}

But the image is spinning like a ball! I think my code is not correct at all. How can i do that rotation?

A:

You will have work on setting the anchor point of the layer. Place the anchor point of the layer containing the face at the lower mid bottom. The rotation will then take place from this point. Then it will appear that the head is tilting from the neck.


Q:

jsTree cancel Create node

I'm using context menu is jsTree and here's my code:
"contextmenu" : {
    "items": function ($node) {
        return {
            "create": {
                "separator_before": false,
                "separator_after": false,
                "label": "Créer",
                "action": function (data) {
                    var inst = $.jstree.reference(data.reference),
                        obj = inst.get_node(data.reference);
                    inst.create_node(obj, {}, "last", function (new_node) {
                        new_node.type = "child";
                        setTimeout(function () {
                            inst.edit(new_node);
                        }, 0);
                    });
                }
            },
            "Rename": {
                "separator_before": false,
                "separator_after": false,
                "label": "Renommer",
                "action": function (data) {
                    var inst = $.jstree.reference(data.reference),
                        obj = inst.get_node(data.reference);
                    inst.edit(obj);
                }
            },
            "Remove": {
                "separator_before": false,
                "separator_after": false,
                "label": "Supprimer",
                "action": function (data) {
                    var inst = $.jstree.reference(data.reference),
                        obj = inst.get_node(data.reference);
                    inst.delete_node(obj);
                }
            }
        };
    }
},

If I am renaming a node and I decide to cancel it, I just press the escape button and the node returns to its previous name.
If I want to create a node, it creates the node first and put it into editing mode. Now if I press escape, the editing mode is exited but the node remains. What I want to accomplish is if I'm in creation mode, and I press escape, it should remove the newly created node.
Any ideas on how I can do this?

A:

The node edit function itself accepts a callback as a second argument. The callback function when called, receives a boolean flag indicating if the user cancelled the edit.
inst.edit(new_node,"New node",function(node,bStatus,bCancelled){
    if(bCancelled){
        this.delete_node(node);
    }
});

The current node and the instance is also returned which can be used to delete the node.
Reference: https://www.jstree.com/api/#/?q=edit


Q:

How can I automate the exportation of a mySQL database using phpMyAdmin

Is it possible to automate the exportation of a single db using phpMyAdmin?
When I try creating the .sql file from an external script, like php, the resulting .sql file looks clean, but when imported causes problems in the application.
When I use phpMyAdmin to create a similar .sql file by using Export, the resulting .sql file Imports without causing any issues to my application.
The application is moodle 2.2, the MySQL version is 5.5, the phpMyAdmin version is 3.4.10.

A:

The best option is to make a script that executes database export with mysqldump and after that a cronjob to execute that script.


Q:

Bind event to jQuery.post and callbacks

I am using jQuery.post a lot in my project and every time the browser sends a post request, I want to show a preloader while the request is in process and then stop the preloader when i get the reply form the server:
var params = {'action':'get_customer_info', 'customerID':4};

preloader.start();
$.post('ajax/url', params, function(response){
    preloader.stop();

    responseHandler(response);
});

Instead of adding the preloader.start() and preloader.stop() lines every time I call jQuery's post, I'd like to bind/trigger events on before the jQuery.post as well on the success/fail handlers.
I know how to bind and trigger events in general, but I'm not sure how I would do this with the $.post and handlers.
How do I do this?

A:

You could set up the global ajax events, that way the preloader shows on every ajax request
$(document).ajaxSend(function() {
    preloader.start();
}).ajaxComplete(function() {
    preloader.stop();
});

Or you could create your own post function
function post(url, params) {
    preloader.start();
    return $.post('ajax/url', params, function(response){
        preloader.stop();
    });
}

To be used like
post('ajax/url', params).done(function(response) {
    responseHandler(response);
});


Q:

simple command line xquery

I'm trying to find a simple cli command to do xquery from linux shell. What I'd like is to avoid external dependencies that I need to install (using fedora 18).
What I already found is saxon and xqilla that I can install through yum. I can use them  if nothing else but they are not in the base system. What I hoped to find is something like the java internal class for doing xslt processing (com.sun.org.apache.xalan.internal.xsltc.cmdline.Transform).
One other idea I have is use XSLT to transform the document to the desired xquery result but one-liners would not be possible.
example of what I can do with xqilla (but searching for another utility):
$ xqilla -i TEST-com.ecample.testcase.MyTestCase.xml <(echo '/testsuite/@failures + /testsuite/@errors')

UPDATE: not exactly the question I had but I settled on perl XML::Twig being installed by default and giving me the flexibility to implement complicated logic with perl. That also led to a nice speed boost because there is no need to fork a process for each XML file.

A:

For XQuery 1 there is my Xidel. Works like this:
 $ xidel TEST-com.ecample.testcase.MyTestCase.xml -e 'xquery version "1.0"; /testsuite/@failures + /testsuite/@errors'

Completely dependency free, but not in the base system, not java, and it has no support for XML schemas...

A:

Edit: I just noticed that you said you already found Saxon. I'll leave my answer anyway just in case the example helps anyone in the future.

You can run Saxon (XQuery) from the command line. You can do this by pointing to a file that has the XPath/XQuery using -q or you can pass the query string directly using -qs.
Here's an example of using -qs to process a simple XPath:
input.xml
<a>
  <b id="x"/>
  <b id="z"/>
  <b id="x"/>
</a>

Saxon command line (I used Saxon9-HE to test with)
java -cp "saxon9he.jar" net.sf.saxon.Query -s:"input.xml" -qs:"/a/b[@id='x']" -o:"results.xml"

results.xml
<b id="x"/><b id="x"/>

Note: I could've made my output well-formed by changing the -qs to something like this:
-qs:"<results>{/a/b[@id='x']}</results>"

For more command line options, look here: http://www.saxonica.com/html/documentation/using-xquery/commandline.html

A:

There is no XQuery processor bundled in the JDK, so you will have to install one separately. It's not clear why you see that as a problem.


Q:

Spoils of War Passive

The item Relic Shield currently has the following passive:
UNIQUE - SPOILS OF WAR: Basic attacks execute minions below 200 health. Killing a minion heals the nearest allied champion for 2% of your maximum health and grants them gold equal to the kill plus 5. This effect requires a nearby allied champion to trigger. Recharges every 30 seconds, up to a maximum of 2 charges.
How does the gold allocation work between a champion that has this item and a nearby allied champion? Does the ally champion get all of the gold, or do both champions get the kill bounty plus the other champion gets 5 gold?
In other words, if I am a support, is it beneficial for me and my ADC partner if I steal the last hits if I have a charge available (gold wise)?

A:

Killing a minion grants the person that kills it gold for that minion, this item does not affect that.
This item does allows you to grant gold to a nearby allied champion equal to the amount YOU get for killing + 5 when you do last hit a minion.  This is useful for champions trying to help out in last hitting minions in a duo lane. However, Spoils of War serves no benefit if there are no nearby champions
With other items "nearby" for friendly effects is 1100 range where "nearby" for detrimental effects is 700 range. This leads me to believe the range on Spoils of War is 1100 but I will investigate later.


Q:

CSS bootstrap button modification. Color only changes half when hover

I don't know what's wrong with my CSS. I'm trying to create a new class called "btn-success2" with new colors by modifying default bootstrap colors. I'm trying to set my hover color to white but it only changes half of it. The top part is still the same green color.
My code as below:
.btn-success2:hover,
.btn-success2:focus,
.btn-success2:active,
.btn-success2.active,
.btn-success2.disabled,
.btn-success2[disabled] {
  color: #ffffff;
  background-color: #fff;
  *background-color: #fff;
}

.btn-success2:active,
.btn-success2.active {
  background-color: #6cc334 \9;
}

jsfiddle: https://jsfiddle.net/ms4uk83e/

A:

You had:         background-position: 0 -15px;
Change the -15px to 30.
.btn:hover, .btn:focus {
    background-position: 0 -30px;
}


Q:

ExtJS 4.2.1 TreePanel do not refresh how I want

I am working with a treePanel with ExtJS 4.2.1.
My problem is quite delicate to explain.
I have two buttons, a tree button and a clear button.
When I click my tree button, it shows a treePanel with checkNodes so you can check some nodes. I have a valid button in my treepanel to valid the selection. Once you have clicked this button, the checked nodes (precisely leaves but that is a detail) will be added to a panel. This panel is a grid and it's the list of the nodes you have checked. No problem with this grid. I don't have any problem with this button and my grid, and when I click the valid button the checked nodes are correctly listed in my grid panel.
When I click the clear button, which is not in my tree panel it clears all my selection, my grid becomes empty and all the nodes from my tree becomes unchecked (like if you were starting from the beginning).
It works when I do it for the first time. I can check nodes, click on the valid button and it will correctly add my items to my grid panel (I never have any problem with my grid panel which list my checked nodes). If I click my clear button the list becomes empty. Then if I click on my tree button, the tree panel appears and if I expand it I can see that the selection is reinitialized, all the nodes are unchecked.
THE PROBLEM : if I do the same operation a second time it seems to work great, but the tree panel is not visualy reinitialised. I click on the tree button, the treepanel appears and when I expand it I see that the nodes I precedently checked are still checked. The problem is that when I want to consult my checked nodes with some console.log(currentChild.data.checked) I can see that the checked value is false.
So it seems to work with the data, but my tree panel is not correctly refreshed (only when I do the operation more than one time).
I don't know if my problem is correctly explained.
Here is a part of the concerned code.
var uncheck = false;
button.on('click', function(){
        var treeSelector = createTree('stAddAction.do?action=product_tree_selector', 550, 490, '', 'lbl_st_tree_selection_empty', true, 'productlist');
        treeSelector.on('load', function( node, records, successful, eOpts ){
            if ( uncheck ){
                node.tree.root.cascadeBy(function(currentChild){
                    if ( currentChild.data.checked ){
                        currentChild.data.checked = false;
                        currentChild.raw.checked = false;
                        currentChild.triggerUIUpdate();
                        console.log(currentChild);
                    }
                });
            }
            uncheck = false;
        });
        buttonClear.on('click', function(){

           uncheck = true;
           treeSelector.store.proxy.url = "stAddAction.do?action=product_tree_selector";
           treeSelector.store.load(treeSelector.getRootNode());
           treeSelector.store.sync();
           treeSelector.getView().refresh();
        });
});

Where is the problem? What could it be? Why does it work once but not twice?
Thank you

A:

You should be using the node's set method to change the value with the statement:
currentChild.set("checked", false);

here would be the full code:
var uncheck = false;
button.on('click', function(){
        var treeSelector = createTree('stAddAction.do?action=product_tree_selector', 550, 490, '', 'lbl_st_tree_selection_empty', true, 'productlist');
        treeSelector.on('load', function( node, records, successful, eOpts ){
            if ( uncheck ){
                node.tree.root.cascadeBy(function(currentChild){
                    if ( currentChild.data.checked ){
                        currentChild.set("checked", false);
                        console.log(currentChild);
                    }
                });
            }
            uncheck = false;
        });
        buttonClear.on('click', function(){

           uncheck = true;
           treeSelector.store.proxy.url = "stAddAction.do?action=product_tree_selector";
           treeSelector.store.load(treeSelector.getRootNode());
           treeSelector.store.sync();
           treeSelector.getView().refresh();
        });
});


Q:

Get Keycloak auth-server-url from request?

I want to create dynamic links to the profile and logout url:
 scheme://servername:port/auth/realms/realmname/protocol/openid-connect/logout
 scheme://servername:port/auth/realms/realmname/account

When using OIDC in the keycloak.json of the java-ee project the auth-server-url is stated:
{
  "realm": "master",
  "auth-server-url": "scheme://servername:port/auth",
  ...
}

Is there something like
request.getAuthServerUrl();

available to get
 auth-server-url

programmatically in Java from the request?
Would be nice, if i don't have to read from the file itself manually.
The keycloak.json must have already been read from by the application so this information might be available as an attribute of a Keycloak object.

A:

Solved it myself:
 var principal = (KeycloakPrincipal) request.getUserPrincipal();
 String issuer = principal.getKeycloakSecurityContext().getToken().getIssuer();

issuer now contains the desired url.
It is not actually the value which is stated in the keycloak.json, it is of the form
 scheme://server:port/auth/realms/realmname


Q:

IE or Firefox,which one has a more logical CSS handling?

i know that there is some rules and standards in css handling but i mean which one is closer to a human thinking.
for example :
when i give a DIV tag a height property of 100px i just want it to be 100px! but in Firefox i should work on min-height or max-width and so on !
there is many like this examlpe , i think IE read css more humanestic against Firefox.
i have several experiences in this case , your final nice design in IE can be a mess in Firefox thats because of the way they handle css.
Firefox act as a robot but IE act as a human-half robot !
its just my idea.
i will be glad to hear and learn from you proffesionals and other friends here.
thank you.

A:

You must be new to web design. Otherwise you wouldn't be calling IE the more humane browser. :)
I see your point but I don't agree with your conclusion. The difference in the box model you are referring to is the only instance where IE's approach actually makes more sense than the official standard. Otherwise, IE usually is the culprit introducing behaviour that drives you crazy.
Browsers have their differences. In rendering, Firefox is generally closer to what is the official W3C standard than IE. IE 8 is the first step towards true standards compatibility on a very wide level.
You will usually need to support every major browser, down to IE 7 or even IE 6. Don't make the mistake of ignoring either, you can't afford it. (Except maybe for IE 6 - it's a discussion in itself.)
A very valuable guide to the differences are the compatibility tables at quirksmode.
Invaluable tools to figure out rendering oddities are Firebug in Firefox, and the new developer toolbar in IE 8. Be sure to have them under your belt when you start working.


Q:

Skin receptors on finger tip

How many receptors do we have on our fingertipps per square centimeters? I found 2500 but do not find the source.
Is this correct?

A:

I'll assume you're only asking about mechanoreceptors, else it gets too murky.
Humans have four types of mechanoreceptors.

Meissner corpuscle, innervated by RA1 (rapidly adapting type 1) nerve fibers. There are 2 of the fibers per square millimeter in the monkey finger (my source does not list it for humans), with 10 to 20 Meissner corpuscles per axon, so 1000 to 2000 per square centimeter.
Merkel cell, at the end of SA1 (slowly adapting type 1) nerve fibres. I did not find a source for the adult human, but Kandell says that RA1 fibres are the "most numerous". So 2000 would be the upper limit for Merkel cells too. But here it gets complicated, because the actual mechanoreceptor is not a single Merkel cell, but a cluster of them.
and 4., Pacinian corpuscles and Ruffini endings (corresponding to RA2 and SA2 fibres) are much rarer. The whole hand has 2400 Pacinian corpuscles in the young and 300 in the elderly. Both of them only have one receptor per nerve fibre.

Given this information, 2500 is certainly in the right ballpark. I would trust that number.
Note that this doesn't mean that you can sense 2500 separate locations of pressure in a square centimeter of fingertip. The different mechanoreceptors sense different types and frequency of pressure, and the sensory fields overlap even within a single type of receptor.

 Kandel, Eric R., James H. Schwartz, and Thomas M. Jessell, eds. Principles of neural science. Vol. 4. New York: McGraw-hill, 2000.


Q:

Synchronizing Apple Watch and iPhone using Swift 3 and Realm

I need to Display and modify my data structure from both Apple Watch and iPhone.
The Database:
I am currently using a simple Realm Structure where I have an Object A and an Object B which can hold lots of A's.
So on iPhone the user can create a B and add A's and view of course all A's and B's.
I want the Apple watch to show all A's of the current B and give the users the chance to add new A's to their current B.
The way I have tried to do it:
I wanted to move the hole Realm file from iPhone to the watch or the other way. (That was a tip from the Internet)
iPhone Code:
    override func viewDidLoad() {
    super.viewDidLoad()

    if WCSession.isSupported() { //makes sure it's not an iPad or iPod
        let watchSession = WCSession.default()
        watchSession.delegate = self
        watchSession.activate()

        transferRealmFile()

        if  watchSession.isWatchAppInstalled {
            do {
                try watchSession.updateApplicationContext(["foo": "bar"])
            } catch let error as NSError {
                print(error.description)
            }
        }
    }
}
func transferRealmFile(){
    if let path = Realm.Configuration().fileURL {
        WCSession.default().transferFile(path, metadata: nil)
    }
}

WathcKit Extension:
  func session(_ session: WCSession, didReceive file: WCSessionFile) {

    //set the recieved file to default Realm file
    var config = Realm.Configuration()
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentsDirectory = paths[0]
    let realmURL = documentsDirectory.appendingPathComponent("data.realm")
    if FileManager.default.fileExists(atPath: realmURL.path){
        try! FileManager.default.removeItem(at: realmURL)
    }
    try! FileManager.default.copyItem(at: file.fileURL, to: realmURL)
    config.fileURL = realmURL
    Realm.Configuration.defaultConfiguration = config
}

Then I call transferRealmFile() every time I write to Realm. This works but I can't solve this Problems:
Problems:

It doesn't work if only watchKit App is started.
Apple Watch to iPhone doesn't work the same way. (I think I need to change the didRecived code, but I don't know what)

Question:
Do you know who to solve this 2 Problems or do you maybe know a better way to handle the situation or will the way we interact between iPhone an Watch change in WathcOS 3?

A:

With watchOS1 it was possible to use AppGroups to share resources (even your Realm database) between an iOS app and its Watch extension. However, Apple removed this in watchOS 2, so now the only way to share data between your iOS and watchOS apps is via WatchConnectivity. Have a look at this answer.
Sadly the WatchConnectivity framework requires the WCSession to be active on both devices for transferring data, so you can't really get around problem 1.
In my opinion it is a better solution to only communicate the changes between the two apps and not send the whole Realm file, since your Realm file can get quite big and hence sending it forward and backward can take a lot of time and resources, while just sending the changes should be way faster.


Q:

Convert string to uniqueidentifier when join is happening

I want to create a stored procedure but I get an error, after a while found out that "ret_payrollcalculationInfo" includes xml column and stored BankGuid and BankBranchGuid as string, not uniqueidentifier and couldn't Join to their tables.
<BankGuid>92434DE6-3D3C-43F1-A89E-869AE5456B07</BankGuid>
<BankBranchGuid>00000000-0000-0000-0000-000000000000</BankBranchGuid>
<PayrollItemGuid>482C44DD-ECFB-4B79-9118-86B681CC51C9</PayrollItemGuid>
<SalariedType>1</SalariedType>

I want to know if there is a way to cast uniqeidentifier when INNER JOIN is happening. here is some code...
CREATE PROCEDURE [dbo].[ret_PayrollCalculations_GetCalculationSummaries]
(
    @CalculationCommandGuid uniqueidentifier,
    @OperationalUnitIDs varchar(512)
)
AS
DECLARE @UnitIds TABLE([ID] INT primary key)
IF ISNULL(@OperationalUnitIDs, '') <> ''
    INSERT INTO @UnitIds SELECT Distinct [Column] FROM com_udfSplit(@OperationalUnitIDs, ',')

SELECT DISTINCT
    calculaion.[PersonnelNo],
    calculaion.[FullName],
    calculaion.[Amount],
    calcInfo.[AccountNo],
    calcInfo.[SalariedType],
    bank.[Title],
    branch.[Title]
FROM
    ret_PayrollCalculationCommands command INNER JOIN
    ret_vwPayrollCalculations calculaion ON command.[Guid] = calculaion.[CalculationCommandGuid] INNER JOIN
    ret_PayrollCalculationInfo calcInfo ON calculaion.[Guid] = calcInfo.[PayrollCalculationGuid] INNER JOIN
    gen_Banks bank ON calcInfo.[BankGuid]   = bank.[Guid] INNER JOIN
    gen_Branches branch ON calcInfo.[BankBranchGuid] = branch.[Title]
WHERE
command.[Guid] = @CalculationCommandGuid

A:

You can simply cast the VARCHAR value to a UNIQUEIDENTIFIER, for example:
CAST('482C44DD-ECFB-4B79-9118-86B681CC51C9' AS UNIQUEIDENTIFIER)

So your JOIN clauses become something like this:
ON command.[Guid] = CAST(calculaion.[CalculationCommandGuid] AS UNIQUEIDENTIFIER)


Q:

Collection being modified during loop when there is no way it can be C#

The following code's foreach statement throws an InvalidOperationException saying "Collection has been modified. Enumeration operation cannot execute." I don't see how this is possible, seeing as colors can never be modified after it's initialization.
Dictionary<Color, int> colorDictionary = new Dictionary<Color, int>();
//Put stuff in colorDictionary...
int currentBest = 257;
Color replaceColor = Color.Empty;
Dictionary<Color, int>.KeyCollection colors = colorDictionary.Keys;
foreach (Color c in colors)
{
    if (colorDictionary[c] == 0)
    {
        continue;
    }
    if (ColorDistance(color, c) < currentBest)
    {
        replaceColor = c;
        colorDictionary[c]--;
    }
}

A:

I don't see how this is possible, seeing as colors can never be modified after it's initialization.

It's a view on the dictionary's keys... and you're modifying the dictionary here:
colorDictionary[c]--;

Admittedly that's not actually adding or removing any keys - but it's modifying the dictionary, and the key enumerator is basically sensitive to that.
The simplest fix would be just to create a copy:
IEnumerable<Color> colors = colorDictionary.Keys.ToList();


Q:

Missing build.xml when creating project with ClickStart?

I am using Eclipse EE version and CloudBees plugin to create a ClickStart JBoss 7 project. However, I am not very familiar with the EE version of Eclipse, and used Netbeans to edit my JSP.
Then I used CloudBees SDK to run and deploy my new project but it failed (the command prompt):

D:\Personel\Java EE\HelloCloudBees>bees run
ERROR: java.io.FileNotFoundException: D:\Personel\Java
  EE\HelloCloudBees\build.xml (The system cannot find the file
  specified)

I found no build.xml file in my folder. How can I create it?

A:

bees run command expect an ant-based project structure, so the build.xml. As documented

CloudBees project commands are only available for applications
  generated using the Bees wizard (on the web), built using the
  CloudBees SDK style.

This is more or less some legacy stuff, as is now superseded by ClickStart. Equivalent command would be bees app:run but require your app to first be packaged as a WAR and only support the default tomcat6 runtime. So for your specific use-case would be simpler to package and deploy on a local JBoss 7 server. To deploy on RUN@Cloud, use bees app:deploy or just git push and let DEV@Cloud Jenkins build and deploy for you (assuming you created app with a clickstart).
Also, there's no need to use Eclipse if you're familiar with NetBeans.


Q:

Position all agenda files in tabbar group emacs

I'm using tabbar to define groups of files.
Some are in the "Emacs buffer" group, others are in the "Dired" group and all others, ATM, are in the "User buffer" group.
I would like to add another group for when I'm using the agenda files -
Instead of having the files all appear in the "User buffer" and litter my tabs view, I would like them to appear in a destined group called "Agenda buffers".
How could that be done?
At the moment this is my configuration:
(defun tabbar-buffer-groups ()
  "Return the list of group names the current buffer belongs to.
This function is a custom function for tabbar-mode's tabbar-buffer-groups.
This function group all buffers into 3 groups:
Those Dired, those user buffer, and those emacs buffer.
Emacs buffer are those starting with “*”."
  (list
   (cond
    ((string-equal "*" (substring (buffer-name) 0 1)) "Emacs Buffer")
    ((eq major-mode 'dired-mode) "Dired")
    ((eq major-mode 'sr-mode) "Dired")
    (t "User Buffer")
    )))

(setq tabbar-buffer-groups-function 'tabbar-buffer-groups)

A:

Add a condition to the function as follows:
(defun tabbar-buffer-groups ()
  "Return the list of group names the current buffer belongs to.
This function is a custom function for tabbar-mode's tabbar-buffer-groups.
This function group all buffers into 3 groups:
Those Dired, those user buffer, and those emacs buffer.
Emacs buffer are those starting with “*”."
  (list
   (cond
    ((string-equal "*" (substring (buffer-name) 0 1)) "Emacs Buffer")
    ((member (buffer-file-name) (mapcar 'expand-file-name org-agenda-files)) "Agenda")
    ((eq major-mode 'dired-mode) "Dired")
    ((eq major-mode 'sr-mode) "Dired")
    (t "User Buffer")
    )))


Q:

Stop Process on Network Machine with .Net

In my project, I am going to do that :
There is a server in restaurant, and some pos machines which are running on Windows XP called Radiant systems. There will be a .exe on server, and this .exe will stop running some process on Radiant Poses. It is possible with .Net Remoting. But it requires to write an .exe on the Radiant Poses, but I dont want to do that. Think there is no problem on network access on Main Server in restaurant and Radiant Poses in restaurant. Is it possible to do that without using .Net Remoting?

A:

One way could be, to use Remoting to call a KillProcess() method that would in turn call the Process.Kill method to kill a process. This article is worth looking at.


Q:

Convergence in $L^1$ and uniformly bounded $L^4$ norm implies $L^2$ convergence

Suppose that $f_n$ and $f$ are $L^1$ functions in a measure space $(X, \mu)$ with $\mu(X) < \infty$ such that $f_n \to f$ in $L^1$. Further, suppose that $$C = \sup_n \int |f_n|^4 < \infty.$$ That is, the $L^4$ norms of the $f_n$ are "uniformly bounded." I am told that this implies $f_n, f \in L^2$, and $f_n \to f$ in $L^2$, but I can't prove this last part.
I can prove $\int |f|^4 \leq C$. (Apply Fatou's lemma to a subsequence of $f_n$ which converges pointwise to $f$.) I can also prove that $f_n$ and $f$ are both $L^2$ (All $L^2$ functions with finite support are automatically $L_1$, and $f_n^2$ and $f^2$ are $L^2$.) I don't see how to deal with $||f_n - f||_2$. I don't see how the fourth powers are supposed to come into the picture.
From $\{f_n\}$ is uniformly integrable if and only if $\sup_n \int |f_n|\,d\mu < \infty$ and $\{f_n\}$ is uniformly absolutely continuous? I can see that my sequence is uniformly integrable, and I've vaguely heard of the Vitali convergence theorem, but I suspect that there is an easier way to prove this.

A:

I don't think we need $\mu(X)<\infty.$
Lemma:  Let $g:X\to [0,\infty)$ be measurable. Then
$\int_X g^2\,d\mu \le \int_X g\,d\mu +\int_X g^4\,d\mu.$
Proof: Let $A=\{x: g(x)\le 1\},$ $B =\{x: g(x)> 1\}.$ Then
$$\int_X g^2\,d\mu = \int_A g^2\,d\mu + \int_B g^2\,d\mu \le \int_A g\,d\mu + \int_B g^4\,d\mu\le \int_X g\,d\mu + \int_X g^4\,d\mu.$$
In our problem we have $f_n\to f$ in $L^1,$ which implies $\int_X |f_n|\,d\mu$ is uniformly bounded. We also know $\int_X |f_n|^4\,d\mu$ is uniformly bounded. By the lemma, $\int_X |f_n|^2\,d\mu$ is uniformly bounded.
As pointed out in the OP, the a.e. pointwise convergence of some subsequence $f_{n_k}$ to $f$ then shows $\int_X |f|^p\,d\mu<\infty$ for $p=1,2,4$ (Fatou's Lemma).
We thus have, by Cauchy-Schwartz,
$$\tag 1 \int_X |f_n-f|^2\,d\mu = \int_X |f_n-f|^{1/2}\cdot |f_n-f|^{3/2}\,d\mu$$ $$ \le \left ( \int_X |f_n-f|\,d\mu \right )^{1/2}\left ( \int_X |f_n-f|^3\,d\mu \right )^{1/2}.$$
Now
$$\int_X |f_n-f|^3\,d\mu = \int_X |f_n-f|\cdot |f_n-f|^2\,d\mu$$ $$ \le \left ( \int_X |f_n-f|^2\,d\mu \right )^{1/2}\left ( \int_X |f_n-f|^4\,d\mu \right )^{1/2}.$$
Insert the last inequality into $(1)$ and do some canceling to get
$$\left (\int_X |f_n-f|^2\,d\mu  \right )^{3/4}\le \left ( \int_X |f_n-f|\,d\mu \right )^{1/2}\left ( \int_X |f_n-f|^4\,d\mu \right )^{1/4}.$$
On the right we have terms $\to 0$ times terms that are uniformly bounded. It follows that $\int_X |f_n-f|^2\,d\mu\to 0$ as desired.


Q:

Elasticsearch query must not match text from field

I want to get the results that do not match "statusCode": 200
In order to match text from field you use
GET index01/_search?pretty
{
  "query":{
    "match":{
      "statusCode": 200
    }
  }
}

I tried something like this:
GET ucs_heartbeat/_search?pretty
{
  "query":{
    "match":{
      "statusCode":{
        "query": 200,
        "operator": "must_not"
      }
    }
  }
}

According to: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html

A:

Try this instead
GET ucs_heartbeat/_search?pretty
{
  "query": {
    "bool": {
      "must_not": [
        {
          "term": {
            "statusCode": 200
          }
        }
      ]
    }
  }
}


Q:

How can I prove that a sequence such that every converging subsequence coverges to the same limit, converges?

I want to claim that if $(x_n)_{n\in N}$ is a sequence, and there is $a$ such that if $(x_{n_k})$ converges, so $\lim x_{n_k} = a$ (it means that all converging subsequences have the same limit), then $(x_n)$ converges. (I don't really mind sequence of what.. could be numbers, could be a sequence in any Hilbert space).
Is my proposition even right?
Assume that a converging subsequence exists, if it helps. I think it should.
My intuition is YES, using some how that $\liminf =\limsup$ (Why is that right exactly? as explicitly as you could).
Does it also hold for weak convergence?
Thanks!
Added: assume it's bounded. I understood it is false if not bounded

A:

Here is a counterexample:
$$
a_n =
\begin{cases}
0, & n \mbox{ even }\\
n, & n \mbox{ odd }
\end{cases}
$$
However, as David Mitra points out, if you require boundedness, then the result should hold.

Let $a_n$ be a bounded sequence of real numbers such that every convergent subsequence converges to the same number $a$. Suppose toward contradiction it does not converge to $a$. Then there is an $\epsilon>0$ such that $|a_n - a|>\epsilon$ for infinitely many $n$.
Index these as $b_k$. This is a bounded sequence of real numbers, hence has a convergent subsequence. By construction, this convergent subsequence cannot converge to $a$. However, it is a subsequence of $a_n$. Contradiction.
(The proof is the same for such sequences in any compact metric space.)


Q:

Regex validation Allow only Character and space in Asp.net

hello every one i need a validation that can only validate to character and white space.. no mater how much space and character in text-box
i use this regexp validation below. but its only allow one space between two words but don`t allow the third space for third word.
([A-Za-z])+( [A-Za-z]+)
how to allow only characters and spaces in Regexp Validation?

A:

Try this:
([A-Za-z])+( [A-Za-z]+)*
                       ^^ here

* means to repeat the group zero or more times. If you need it to be one or more times, then use +. Another thing you can use [ ]+ instead of space to handle one or more consecutive spaces.
Also, if you need, you can use anchor ^ and $ around your regex. Like ^...regex...$


Q:

Custom message fetched from API in UIActivityViewController

I want my app users to share an link using an UIACtivityViewController. The link is not static and I have to fetch it from an api. I want to fetch this link as soon as someone presses a icon in UIActivityViewController but how I am doing it now is not working. The completionhandler of the request is always excuted at the end of the method fetchShareURL(). Could someone tell me how to fix this?
    import UIKit

    class ShareItemSource: NSObject, UIActivityItemSource {

        var objects : [AnyObject]?
        var shareURL : String?

        init(objects : [AnyObject]?){
            self.objects = objects
        }

        func fetchShareURL() -> Bool{
            //fetch share url from api

            let api = Api()
            let semaphore = dispatch_semaphore_create(0);
            let backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)
            dispatch_async(backgroundQueue, {

                api.export(self.groupObjList, receiptObjList: self.receiptObjList){ status, message, url in
                    dispatch_async(dispatch_get_main_queue(), {
                        self.shareURL = url

                        dispatch_semaphore_signal(semaphore);
                    })
                }

            });

            let delayInSeconds = 30.0;
            let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delayInSeconds * Double(NSEC_PER_SEC)))
            dispatch_semaphore_wait(semaphore, delayTime)

            if self.shareURL != nil{
                return true
            } else {
                return false
            }

        }

        @objc func activityViewControllerPlaceholderItem(activityViewController: UIActivityViewController) -> AnyObject {
            return ""
        }

        @objc func activityViewController(activityViewController: UIActivityViewController, itemForActivityType activityType: String) -> AnyObject? {
            if fetchShareURL() == true{
                return "Download files: "+self.shareURL!

            } else {
                return nil
            }

        }

        func activityViewController(activityViewController: UIActivityViewController, subjectForActivityType activityType: String?) -> String {
            return "title of share"
        }

        func activityViewController(activityViewController: UIActivityViewController, thumbnailImageForActivityType activityType: String?, suggestedSize size: CGSize) -> UIImage? {
            //do stuff
    }
}

A:

If data to be provided in a UIActivityView takes time to provide, use a UIActivityItemProvider. It is an NSOperation subclass and solves the whole problem in a completely coherent way. Indeed, this sort of situation is exactly what it is intended for. (And watch the WWDC 2015 video on advanced NSOperation, please.)


Q:

RubyMine doesn't recognize my Ruby installation path

I've made a custom sient installer of Ruby 2.0 with some gems and extras, my installer expands all the Ruby files to c:\Program Files (x86)\Ruby, the interpreter (ruby.exe) is in the Bin folder, all is as normally but just it's not an original installation, I expand the files and I add the registry keys to associate files by my own, I can run Ruby as normally ever I want.
Now, is the first time that I try the JetBrains RubyMine IDE, and I can't found a simple guide which explains how to set the Ruby directory, seems that this IDE assumes that the Ruby installation is original and maybe takes a registry value from the original Ruby installer to know the Path or something, I don't know, but just I didn't see any help about how to set the Ruby directory manually.
(I have the same problem for PyCharm)
Anyways I've tried to set it from the Ruby SDK and Gems option, the dialog-box says "select Ruby interpreter Path", but I'm on the Path and it's not recognized, I mean that the Ok button still disabled:

Then I'm missing the right option anywhere? or really a professional and expensive IDE like this doesn't has support just to specify the location of Ruby in these circunstance where an user does not use the original Ruby installer? I really will think not.

A:

In my experience it is more preferable to set your PATH environment variables appropriately instead of trying to locate executables on a per-app basis.
You can set your path so that the desired Ruby takes precedence over any other rubies and I am sure that RubyMine will pick it up (or just use ruby and let your PATH specify which to use).
On another note you might also want to have a look at a ruby version manager such as rbenv or RVM.
Update: Just tried to set manually a Ruby SDK in the latest version of RubyMine (6.3) and it worked as expected. I had, however, to expand the folder in which the binary resided (in your case bin), select the actual binary and then click OK. Have you tried that as well?


Q:

How to group and pivot(?) dataframe

I have a dataframe looking like this:
ID  Species Count
1   Pine    1000
1   Spruce  1000
2   Pine    2000
3   Pine    1000
3   Spruce  500
3   Birch   500

What i want is this:
    Pine    Spruce  Birch
ID  Count   Count   Count
1   1000    1000
2   2000
3   1000    500 500

So im trying:
a = df.groupby(['ID']).cumcount().astype(str)
newdf = df.set_index(['ID', a]).unstack(fill_value=0).sort_index(level=1, axis=1)

Which gives me:
ID  Count   Species Count   Species Count   Species
1   1000    Pine    1000    Spruce
2   2000    Pine
3   1000    Pine    500     Spruce  500 Spruce

How can i fix this?

A:

Simple pivot
df.pivot('ID','Species','Count')
Out[493]:
Species  Birch    Pine  Spruce
ID
1          NaN  1000.0  1000.0
2          NaN  2000.0     NaN
3        500.0  1000.0   500.0


Q:

Should rep earned on the main site carry over to its relative meta?

I feel that it is a bit unfair that rep doesn't carry over between the parent site and its meta. This is the case for every single one of the sites I've been a part in on the Stack Exchange Network. It makes little sense for someone with 5k+ rep to come to its site's meta and have just 1 rep. I know that at least some sites have rep being shared the other way around (meta->parent), but the fact that 0 rep whatsoever is shared from parent to meta seems somewhat illogical to me.

A:

On every site except for Stack Overflow, rep is shared from parent user (main site) to their respective per-site meta user.
However, Meta Stack Overflow is a little different. It's not a normal per-site meta, it's kinda like a capital of Stack Exchange. Thus, rep is independent of any Stack Exchange site you are active on. You earn your own rep here. However, this will soon change. Meta Stack Overflow will soon be a per-site meta only for Stack Overflow, and Meta Stack Exchange will take the role of being the capital.


Q:

variational problem related to an integral

Recently I came up with a type of variational problem in stochastic process.
It can be stated in the following way:
Given $a$ and $b$ positive, and an increasing function $f$ on $(0,1)$ (may be not strictly, but $f$ is possibly unbounded), which satisfies the following equation:
$$ \int_{0}^{1}H_{1}(f(\alpha))d\alpha=a ,$$
$$ \int_{0}^{1}H_{2}(f(\alpha))d\alpha=b .$$
where $H_1$ and $H_2$ are positive and increasing function.
In practice, we often need to consider the minimal of the functional $$ \int_{0}^{1}H(f(\alpha))d\alpha ,$$ where H is a function (may be not positive or increasing).
I want to know a general necessary condition for the minimal of the functional. Any comments will be appreciated.

A:

You question is too vague. If anything is allowed for $H$, of course, then the minimum is $-\infty$: take
$$
H_n = -n \mbox{ on } f((0,1)) \mbox{ and } 0 \mbox{ otherwise.}
$$
If you decide that you just want to avoid that, then you can that $H$ is bounded below, and then on whichever space you decide $H$  should be in, you can look for a minimising sequence...saying more than that in full generality is probably useless since you must have a space (or a set) in mind.
It is of course not a necessary condition: for a well tuned set of functions (depending on $f$) you can lift the lower bound requirement.