text:
Q: Gridwise application of the bisection method I need to find roots for a generalized state space. That is, I have a discrete grid of dimensions grid=AxBx(...)xX, of which I do not know ex ante how many dimensions it has (the solution should be applicable to any grid.size) .
I want to find the roots (f(z) = 0) for every state z inside grid using the bisection method. Say remainder contains f(z), and I know f'(z) < 0. Then I need to

*

*increase z  if remainder > 0

*decrease z if remainder < 0

Wlog, say the matrix historyof shape (grid.shape, T) contains the history of earlier values of z for every point in the grid and I need to increase z (since remainder > 0). I will then need to select zAlternative inside history[z, :] that is the "smallest of those, that are larger than z". In pseudo-code, that is:
zAlternative =  hist[z,:][hist[z,:] > z].min()

I had asked this earlier. The solution I was given was
b = sort(history[..., :-1], axis=-1)
mask = b > history[..., -1:]
index = argmax(mask, axis=-1)
indices = tuple([arange(j) for j in b.shape[:-1]])
indices = meshgrid(*indices, indexing='ij', sparse=True)
indices.append(index)
indices = tuple(indices)
lowerZ = history[indices]

b = sort(history[..., :-1], axis=-1)
mask = b <= history[..., -1:]
index = argmax(mask, axis=-1)
indices = tuple([arange(j) for j in b.shape[:-1]])
indices = meshgrid(*indices, indexing='ij', sparse=True)
indices.append(index)
indices = tuple(indices)
higherZ = history[indices]

newZ = history[..., -1]
criterion = 0.05
increase = remainder > 0 + criterion
decrease = remainder < 0 - criterion
newZ[increase] = 0.5*(newZ[increase] + higherZ[increase])
newZ[decrease] = 0.5*(newZ[decrease] + lowerZ[decrease])

However, this code ceases to work for me. I feel extremely bad about admitting it, but I never understood the magic that is happening with the indices, therefore I unfortunately need help.
What the code actually does, it to give me the lowest respectively the highest. That is, if I fix on two specific z values:
history[z1] = array([0.3, 0.2, 0.1])
history[z2] = array([0.1, 0.2, 0.3])

I will get higherZ[z1] = 0.3 and lowerZ[z2] = 0.1, that is, the extrema. The correct value for both cases would have been 0.2. What's going wrong here?
If needed, in order to generate testing data, you can use something along the lines of
history = tile(array([0.1, 0.3, 0.2, 0.15, 0.13])[newaxis,newaxis,:], (10, 20, 1))
remainder = -1*ones((10, 20))

to test the second case.
Expected outcome
I adjusted the history variable above, to give test cases for both upwards and downwards. Expected outcome would be
lowerZ = 0.1 * ones((10,20))
higherZ = 0.15 * ones((10,20))

Which is, for every point z in history[z, :], the next highest previous value (higherZ) and the next smallest previous value (lowerZ). Since all points z have exactly the same history ([0.1, 0.3, 0.2, 0.15, 0.13]), they will all have the same values for lowerZ and higherZ. Of course, in general, the histories for each z will be different and hence the two matrices will contain potentially different values on every grid point.

A: I compared what you posted here to the solution for your previous post and noticed some differences.
For the smaller z, you said
mask = b > history[..., -1:]
index = argmax(mask, axis=-1)

They said:
mask = b >= a[..., -1:]
index = np.argmax(mask, axis=-1) - 1

For the larger z, you said
mask = b <= history[..., -1:]
index = argmax(mask, axis=-1)

They said:
mask = b > a[..., -1:]
index = np.argmax(mask, axis=-1)

Using the solution for your previous post, I get:
import numpy as np
history = np.tile(np.array([0.1, 0.3, 0.2, 0.15, 0.13])[np.newaxis,np.newaxis,:], (10, 20, 1))
remainder = -1*np.ones((10, 20))

a = history

# b is a sorted ndarray excluding the most recent observation
# it is sorted along the observation axis
b = np.sort(a[..., :-1], axis=-1)

# mask is a boolean array, comparing the (sorted)
# previous observations to the current observation - [..., -1:]
mask = b > a[..., -1:]

# The next 5 statements build an indexing array.
# True evaluates to one and False evaluates to zero.
# argmax() will return the index of the first True,
# in this case along the last (observations) axis.
# index is an array with the shape of z (2-d for this test data).
# It represents the index of the next greater
# observation for every 'element' of z.
index = np.argmax(mask, axis=-1)

# The next two statements construct arrays of indices
# for every element of z - the first n-1 dimensions of history.
indices = tuple([np.arange(j) for j in b.shape[:-1]])
indices = np.meshgrid(*indices, indexing='ij', sparse=True)

# Adding index to the end of indices (the last dimension of history)
# produces a 'group' of indices that will 'select' a single observation
# for every 'element' of z
indices.append(index)
indices = tuple(indices)
higherZ = b[indices]

mask = b >= a[..., -1:]
# Since b excludes the current observation, we want the
# index just before the next highest observation for lowerZ,
# hence the minus one.
index = np.argmax(mask, axis=-1) - 1
indices = tuple([np.arange(j) for j in b.shape[:-1]])
indices = np.meshgrid(*indices, indexing='ij', sparse=True)
indices.append(index)
indices = tuple(indices)
lowerZ = b[indices]
assert np.all(lowerZ == .1)
assert np.all(higherZ == .15)

which seems to work

A: z-shaped arrays for the next highest and lowest observation in history
relative to the current observation, given the current observation is history[...,-1:]
This constructs the higher and lower arrays by manipulating the strides of history
to make it easier to iterate over the observations of each element of z.
This is accomplished using numpy.lib.stride_tricks.as_strided and an n-dim generalzed
function found at Efficient Overlapping Windows with Numpy - I will include it's source at the end
There is a single python loop that has 200 iterations for history.shape of (10,20,x).
import numpy as np

history = np.tile(np.array([0.1, 0.3, 0.2, 0.15, 0.13])[np.newaxis,np.newaxis,:], (10, 20, 1))
remainder = -1*np.ones((10, 20))

z_shape = final_shape = history.shape[:-1]
number_of_observations = history.shape[-1]
number_of_elements_in_z = np.product(z_shape)

# manipulate histories to efficiently iterate over
# the observations of each "element" of z
s = sliding_window(history, (1,1,number_of_observations))
# s.shape will be (number_of_elements_in_z, number_of_observations)

# create arrays of the next lower and next higher observation
lowerZ = np.zeros(number_of_elements_in_z)
higherZ = np.zeros(number_of_elements_in_z)
for ndx, observations in enumerate(s):
    current_observation = observations[-1]
    a = np.sort(observations)
    lowerZ[ndx] = a[a < current_observation][-1]
    higherZ[ndx] = a[a > current_observation][0]

assert np.all(lowerZ == .1)
assert np.all(higherZ == .15)
lowerZ = lowerZ.reshape(z_shape)
higherZ = higherZ.reshape(z_shape)

sliding_window from Efficient Overlapping Windows with Numpy
import numpy as np
from numpy.lib.stride_tricks import as_strided as ast
from itertools import product

def norm_shape(shape):
    '''
    Normalize numpy array shapes so they're always expressed as a tuple,
    even for one-dimensional shapes.

    Parameters
        shape - an int, or a tuple of ints

    Returns
        a shape tuple

    from http://www.johnvinyard.com/blog/?p=268
    '''
    try:
        i = int(shape)
        return (i,)
    except TypeError:
        # shape was not a number
        pass

    try:
        t = tuple(shape)
        return t
    except TypeError:
        # shape was not iterable
        pass

    raise TypeError('shape must be an int, or a tuple of ints')

def sliding_window(a,ws,ss = None,flatten = True):
    '''
    Return a sliding window over a in any number of dimensions

    Parameters:
        a  - an n-dimensional numpy array
        ws - an int (a is 1D) or tuple (a is 2D or greater) representing the size
             of each dimension of the window
        ss - an int (a is 1D) or tuple (a is 2D or greater) representing the
             amount to slide the window in each dimension. If not specified, it
             defaults to ws.
        flatten - if True, all slices are flattened, otherwise, there is an
                  extra dimension for each dimension of the input.

    Returns
        an array containing each n-dimensional window from a

    from http://www.johnvinyard.com/blog/?p=268
    '''

    if None is ss:
        # ss was not provided. the windows will not overlap in any direction.
        ss = ws
    ws = norm_shape(ws)
    ss = norm_shape(ss)

    # convert ws, ss, and a.shape to numpy arrays so that we can do math in every
    # dimension at once.
    ws = np.array(ws)
    ss = np.array(ss)
    shape = np.array(a.shape)

    # ensure that ws, ss, and a.shape all have the same number of dimensions
    ls = [len(shape),len(ws),len(ss)]
    if 1 != len(set(ls)):
        error_string = 'a.shape, ws and ss must all have the same length. They were{}'
        raise ValueError(error_string.format(str(ls)))

    # ensure that ws is smaller than a in every dimension
    if np.any(ws > shape):
        error_string = 'ws cannot be larger than a in any dimension. a.shape was {} and ws was {}'
        raise ValueError(error_string.format(str(a.shape),str(ws)))

    # how many slices will there be in each dimension?
    newshape = norm_shape(((shape - ws) // ss) + 1)
    # the shape of the strided array will be the number of slices in each dimension
    # plus the shape of the window (tuple addition)
    newshape += norm_shape(ws)
    # the strides tuple will be the array's strides multiplied by step size, plus
    # the array's strides (tuple addition)
    newstrides = norm_shape(np.array(a.strides) * ss) + a.strides
    strided = ast(a,shape = newshape,strides = newstrides)
    if not flatten:
        return strided

    # Collapse strided so that it has one more dimension than the window.  I.e.,
    # the new array is a flat list of slices.
    meat = len(ws) if ws.shape else 0
    firstdim = (np.product(newshape[:-meat]),) if ws.shape else ()
    dim = firstdim + (newshape[-meat:])
    # remove any dimensions with size 1
    dim = filter(lambda i : i != 1,dim)
    return strided.reshape(dim)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Weird File.open behavior when using different closure types in Ruby I started learning Chef to manage our servers and I stumbled in a very weird (in my opinion) behavior in Ruby. I do not know Ruby so this might be just a misunderstanding from my part.
The error I was getting was
`delete': Permission denied - [some path]/metadata.json (Errno::EACCES)

Since I knew for sure that it was not actually about permissions, the next logical thing was to check for file locking. After digging a bit through the relevant code, I discovered that there is a method that produces a checksum for each file.

*

*load_root

*file_metadata

*checksum

*md5_checksum_for_file

*generate_md5_checksum_for_file

*checksum_file
def checksum_file(file, digest)
  File.open(file, 'rb') { |f| checksum_io(f, digest) }
end

def checksum_io(io, digest)
  while chunk = io.read(1024 * 8)
    digest.update(chunk)
  end
  digest.hexdigest
end

Having found that, I searched a bit and found an answer about closing files in Ruby and it seemed that the code was actually fine... but it was not. I tried to change the method to the
"block format" and it worked without error:
def checksum_file(file, digest)
  File.open(file, 'rb') do |f|
    checksum_io(f, digest)
  end
end

Can someone please explain the difference between the two versions of the code?
-- Edit --
It seems that this problem occurs only in Windows and maybe only when using the ruby provided by ChefDK 0.3.0 :

ruby 2.0.0p451 (2014-02-24) [i386-mingw32]

A: Answer of your question

Can someone please explain the difference between the two versions of the code?

*

*Block always return something so do end and and { ... } dose't really matter This is just personnel programming preference.

*There are two different convention with block i'm going to dispense
to you now and it up to you which religion you want to subscribe to.
First religion says that
when you have a single line or single line block you would use the curly braces And if you have a multi line block you would use do and end.
words.each { |word| puts word }  # single line or single line block

words.each do |word|  # multi line block
  puts word
  p 1
end

Second religion says that
If your block simply does something has side effect and you dont care about the return value you might put do and end
words.each do |word|
  puts word
end

where as if you do care about return value you would use  { ... }
back_words = words.map{ |word| word.reverse }

hope I answere your question !!!


text:
Q: Why does a deleted name create the following error from a linked list? I have a list called Assignment in which names appear (dropdown list).  These names are assigned certain values, they are in the same line. The names are defined in a worksheet called Input Data!
If I now delete a name like Green, John from the Input Data worksheet, then I get the following error in another worksheet (Evaluation). In this evaluation worksheet the values are evaluated by the following formula:
=ARRAY_CONSTRAIN(ARRAYFORMULA(SUM(IF((IF($B$2="dontcare",1,REGEXMATCH(Assignment!$E$3:$E$577,$B$2 &"*")))*(IF($B$3="dontcare",1,(Assignment!$E$3:$E$577=$B$3)))*(IF($B$4="dontcare",1,(Assignment!$D$3:$D$577=$B$4)))*(IF($B$5="dontcare",1,(Assignment!$F$3:$F$577=$B$5)))*(IF($B$6="dontcare",1,(Assignment!$B$3:$B$577=$B$6))),(Assignment!S$3:S$577)))), 1, 1)

The following error appears in the evaluation sheet:
Error:
During the evaluation of VLOOKUP the value "Green, John" was not found.

So my only question is, how to write a script that deletes the complete lines in the assignment list, if a line occurs with a name like Green, John, that is not in the input data list. short version: Example! Assignment sheet: line 7 Green, John -> check if Green, John is in sheet Input Data in row C! If Green, John is not in Input Data row C -> delete line 7 Green, John in Assignment!     .... That is basically my question!
example sheet with explanation: https://docs.google.com/spreadsheets/d/1OU_95Lhf6p0ju2TLlz8xmTegHpzTYu4DW0_X57mObBc/edit#gid=1763280488


text:
Q: How to reuse code So this is my reminder app screen shot, as you can see it has a + button and also a button. When the + button is cliked, a dialog with editText will be displayed.

 @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_add_task:
                mClickedPosition = -1;
                final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                LayoutInflater inflater = LayoutInflater.from(getActivity());
                View promptView = getActivity().getLayoutInflater().inflate(R.layout.dialog_with_edittext, null);
                Button cancel = (Button) promptView.findViewById(R.id.cancelBtn);
                Button save = (Button) promptView.findViewById(R.id.okBtn);
                task = (EditText) promptView.findViewById(R.id.task);
                time = (EditText) promptView.findViewById(R.id.time);
                date = (EditText) promptView.findViewById(R.id.date);
                final AlertDialog alert = builder.create();
                date.setOnClickListener(this);

                time.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        Fragment fragDialog = getActivity().getSupportFragmentManager().findFragmentByTag("TimePicker");
                        if (fragDialog == null) { // Fragment not added
                            FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
                            tp.show(ft, "TimePicker");
                        } else {
                            // already active
                        }
                    }
                });

                cancel.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        alert.dismiss();
                    }
                });

                save.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        String addTask = task.getText().toString();
                        String time1 = time.getText().toString();
                        String date1 = date.getText().toString();
                        if ((time1.trim().equals(""))|| (date1.trim().equals("") )|| (addTask.trim().equals(""))) {
                            Toast.makeText(getActivity(), " Not Completed", Toast.LENGTH_SHORT).show();
                        }
                        else {
                            if (adapter != null) {
                                if (mClickedPosition == -1) {
                                    adapter.add(iD, addTask, time1, date1);
                                    insertTask(addTask, time1, date1);
                                    listview.setAdapter(adapter);
                                    alert.dismiss();
                                    check();
                                    retrieveList(name);
                                }
                            }

                            Calendar alarm = Calendar.getInstance();
                            Calendar copy = (Calendar) alarm.clone();
                            alarm.set(Calendar.YEAR, year1);
                            alarm.set(Calendar.MONTH, month1);
                            alarm.set(Calendar.DAY_OF_MONTH, day1);
                            alarm.set(Calendar.HOUR_OF_DAY, hour1);
                            alarm.set(Calendar.MINUTE, min1);
                            int result = alarm.compareTo(copy);

                            if(result < 0) {
                                alarm.add(Calendar.DATE, 1);
                            }
                            else
                            {
                                Intent myIntent = new Intent(getActivity(), MyReceiver.class);
                                pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, myIntent, 0);
                                AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(getActivity().ALARM_SERVICE);
                                alarmManager.set(AlarmManager.RTC, alarm.getTimeInMillis(), pendingIntent);
                            }
                        }
                    }
                });

                alert.setView(promptView);
                alert.show();
                return true;

If the button is clicked, it will open dialog exactly same as the + button. My question now is, is there a way I can reuse the code so the code will look a bit shorter,  or I have to copy the code and paste to button onClick ?
Show you my full code of the activity. As you can see, most of the code are the same (+button, button and also the listView click)
http://pastebin.com/HEKcmVK3

A: You need to do it by create a custom dialog class and write the view method.
And then in both + and button click, create an instance of that class and show it.

A: You can create a method of this part of code and then just call the method inside the onclicklistener
String addTask = task.getText().toString();
String time1 = time.getText().toString();
String date1 = date.getText().toString();
if ((time1.trim().equals(""))|| (date1.trim().equals("") )|| (addTask.trim().equals(""))) {
    Toast.makeText(getActivity(), " Not Completed", Toast.LENGTH_SHORT).show();
}
else {
    if (adapter != null) {
        if (mClickedPosition == -1) {
            adapter.add(iD, addTask, time1, date1);
            insertTask(addTask, time1, date1);
            listview.setAdapter(adapter);
            alert.dismiss();
            check();
            retrieveList(name);
        }
    }

    Calendar alarm = Calendar.getInstance();
    Calendar copy = (Calendar) alarm.clone();
    alarm.set(Calendar.YEAR, year1);
    alarm.set(Calendar.MONTH, month1);
    alarm.set(Calendar.DAY_OF_MONTH, day1);
    alarm.set(Calendar.HOUR_OF_DAY, hour1);
    alarm.set(Calendar.MINUTE, min1);
    int result = alarm.compareTo(copy);

    if(result < 0) {
        alarm.add(Calendar.DATE, 1);
    }
    else
    {
        Intent myIntent = new Intent(getActivity(), MyReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, myIntent, 0);
        AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(getActivity().ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC, alarm.getTimeInMillis(), pendingIntent);
    }
}


text:
Q: Place dots where a word is misspelled I'm creating a web app in PHP where people can try to translate words they need to learn for school.
For example, someone needs to translate the Dutch word 'weer' to 'weather' in English, but unfortunately he types 'whether'. Because he almost typed the right word, I want to give him another try, with dots '.' on the places where he made a mistake:
Language A:   weer
Language B:   weather
Input:        whether
Output:       w..ther

Or, for example
Language A:   fout
Language B:   mistake
Input:        mitake
Output:       mi.take

Or:
Language A:   echt
Language B:   genuine
Input:        genuinely
Output:       genuinely (almost good, shorten the word a little bit)

But, if the input differs too much from the desired translation, I don't want to get output like ........
I heard about Levenshtein distance and I think I need an algorithm that is much like that one, but I don't know how to place dots on the right place instead of echoing how many operations are to be done.
So, how can I return the misspelled word with dots on the places where someone made a mistake?

A: First, take a look at the Levenshtein algorithm on wikipedia.
Then go on and look at the examples and the resulting matrix d on the article page:
                *k*     *i*     *t*     *t*     *e*     *n*
        >0       1       2       3       4       5       6
*s*      1      >1       2       3       4       5       6
*i*      2       2      >1       2       3       4       5
*t*      3       3       2      >1       2       3       4
*t*      4       4       3       2      >1       2       3
*i*      5       5       4       3       2      >2       3
*n*      6       6       5       4       3       3      >2
*g*      7       7       6       5       4       4      >3

The distance is found on lower right corner of the matrix, d[m, n]. But from there it
is now possible to follow backtrack the minimum steps to the upper left of of the matrix, d[1, 1]. You just go left, up-left, or up at each step whichever minimizes the path.
In the example above, you'd find the path marked by the '>' signs:
  s i t t i n g      k i t t e n
0 1 1 1 1 2 2 3    0 1 1 1 1 2 2 3
  ^       ^   ^      ^       ^   ^
  changes in the distance, replace by dots

Now you can find on the minimum path at which locations d[i,j] the distance changes (marked by ^ in the example above), and for those letters you put in the first (or second) word a dot at position i (or j respectively).
Result:
  s i t t i n g      k i t t e n
  ^       ^   ^      ^       ^   ^
  . i t t . n .      . i t t . n .

A: The terminology you are looking for is called "edit distance." Using something like Levenshtein distance will tell you the number of operations needed to transform one string into the other (insertions, deletion, substitutions, etc).
Here is a list of other "editing distance" algorithms.
Once you decide that a word is "close enough" (i.e. it doesn't exceed some threshold of edits needed), you can show where the edits need to occur (by showing dots).
So how do you know where to put the dots?
The interesting thing about the "Levenshtein distance" is it uses a M x N matrix with one word on each axis (see the sample matrix in Levenshtein article). Once you create the matrix, you can determine which letters require "additional edits" to be correct. That's where you put the dots. If the letter requires "no additional edits," you simply print the letter. Pretty cool.

A: I think you need to do a multi step process not just Levenshtein. First I would check if the input word is a form of target word. That would catch your 3rd example and also no worry about adding dots. You could also use this step to catch synonyms. The next step is to check the length difference of the two strings.
If the difference is 0 you can do a letter for letter comparison to place the dots. If you don't want to show all dots then you should keep a count of dots placed and once over the limit display some error message. (Sorry that was incorrect)
If the difference is shows the input is longer you need to check for a letter to be delete would fix the problem. Here you can use Levenshtein to see how close they are if they are too far away show your error message if it is in range you will need to do the steps of Levenshtein in reverse and mark the changes somehow. Not sure how you want to show that a letter needs deleted.
If the difference shows the input is shorter you can do use Levenshtein distance to see if the two words are close enough or show the error. Then do the steps in reverse again adding dots for insertions and dots for substitutions.
Actually the last two steps can be combined into one function that runs through the algorithm and remembers the insert delete or substitution and changes the output accordingly.


text:
Q: Difference between these object initializations in JavaScript Say I have a class Animal that I want to define in JavaScript. What are the advantages and disadvantages to declaring it as...
class Animal {
  constructor(type, noise) {
    this.type = type;
    this.noise = noise;
  }

  makeNoise() {
    console.log(this.noise);
  }
}

versus declaring it as...
function Animal(type, noise) {
  this.type = type;
  this.noise = noise;

  this.makeNoise = function () {
    console.log(this.noise);
  }
}

The only thing that I notice is different is that the latter example can actually have private members (declared using var, let, or const declarations), but that was all I could really see.


text:
Q: Random output of comments using a shortcode It is necessary to display comments on the page randomly using a shortcode. Now I output comments using a shortcode using the code:
add_action('wp_head', function (){
    global $postPage, $post;
    $postPage = $post;
});

add_shortcode('comments_block',function($attr, $content){
    global $post,$postPage;
    $savePost = $post;
    $post = $postPage;
    ob_start();
    comments_template();
    $output = ob_get_contents();
    ob_end_clean();
    $post = $savePost;
    return $output;
});

This displays the comments and below them a form for adding comments - everything is fine. But comments need to be displayed randomly (now they are standard by date).
I also tried to combine this code with the one presented here How can I show comments in random order? , but I don't have enough knowledge in this regard(
I will be grateful for any help in this regard.

A: Easy thing would be to override comment query and set orderby property to rand.
function wpse381090_comment_query_rand( $args ) {
    $args['orderby'] = 'rand';
    return $args;
}
add_filter('comments_template_query_args', 'wpse381090_comment_query_rand');


text:
Q: How to fetch data from mysql database using array dataset I am trying to fetch data from mysql database and php codeigniter using the data i already have in an array. but it seems am doing something wrong.
 $query = $this->db->query("select * from product_order where transaction_code='BfkA'");
            foreach ($query->result_array() as $row)
            {
                $p_id = $row['product_id'];
                $this->db->join('product_order', 'product_order.product_id = products.product_id');
                $this->db->where('products.product_id', $p_id);
                $res=$this->db->get('products');
            }
                return $res->result_array();

I want the output to be like this in my table

 Product Name	 Quantity

 shoe	 1

 bag	 4

 watch	 3

but i get

 Product Name	 Quantity

 shoe	 1

 shoe	 1

A: You could use where_in to replace the where method and use array_column to get the product_id array, then you could remove the foreach block :
$query = $this->db->query("select product_id from product_order where transaction_code='BfkA'");
$prod_ids = array_column($query->result_array(), 'product_id');

$this->db->join('product_order', 'product_order.product_id = products.product_id');
$this->db->where_in('products.product_id', $prod_ids);
$res = $this->db->get('products');
return $res->result_array();


text:
Q: "Relative dates" are showing future dates for "this" reference I am trying to get the monday and sunday (first and last day of week respectively, in Costa Rica). So, I did this:
    $now = new \DateTime();

    $monday = new \DateTime();
    $monday = $monday->modify("monday this week");

    $sunday = new \DateTime();
    $sunday = $sunday->modify("sunday this week");

    echo "timezone: " . date_default_timezone_get();
    echo "
";
    echo "now: " . $now->format('d/m/Y H:i');
    echo "
";
    echo "monday: " . $monday->format('d/m/Y H:i');
    echo "
";
    echo "sunday: " . $sunday->format('d/m/Y H:i');

The output is:
timezone: America/Costa_Rica
now: 26/10/2014 19:01
monday: 27/10/2014 00:00
sunday: 02/11/2014 00:00

But, how is possible that the currect week is pointing to future dates?

A: Try this:
$monday = new DateTime();
// create DateTime object with current time

$monday->setISODate($monday->format('o'), $monday->format('W'));
// set object to Monday this week

$sunday = clone $monday;
// clone DateTime object

$sunday->modify('+6 day');
// add 6 days to Monday, to get the Sunday

echo sprintf(
    'This week is stared on %s, and ended on %s.',
    $monday->format('Y-m-d'),
    $sunday->format('Y-m-d')
);
// just print out the result

demo


text:
Q: Please help identify these 2.0mm pitch wafer wire to board connectors Please help me find these 2.0mm pitched 6 pin connectors. They are used in this application for UART communication between a wifi module and the main board.
The closest thing I found was YYECOM YWPHB200 Series, but they don't seem to have the vertical style (top loading) connector or the matching plug.
I want to match these connectors for my project to replace the 2.4 GHz wifi module with one that supports 5 GHz WiFi and I'm not able to find who makes/sells them:

A: Thank you for providing clear and complete information. It allowed me to use my Connector Identification Utility that lists these possibilities:

*

*MANUF. - SERIES

*JST - PA

*JST - PA + PAF

*Molex - Micro-Lock 503660 + 503658

*Molex - Sherlock

A: For those that find this question later:
These are called "HY2.0 2.0mm Connectors".  The 4pin version seems to also be used by Arduino Grove sensors.  The HY2.0 connectors are made by many companies in China (LHE, Taihua, etc.) and can be purchased from aliexpress.  I also found someone on ebay selling the housing already wired once I knew the correct search terms.


text:
Q: powershell word to pdf I modified what someone else had on this forum, based on a successful use of powershell Excel to pdf with no success.  Any ideas on my failing in the following code?  My goal is to be able to convert an entire folder of doc and docx documents to pdf without opening the native applications.  Thanks in advance:
# Acquire a list of DOC files in a folder
$Word = New-Object -ComObject word.application
$path = "c:\Users\Desktop\Test"
$formats = "Microsoft.Office.Interop.Word.WdFixedFormatType" -as [type]
$Word.visible = $false
$fileTypes = "*.docx","*doc"
$Files = GET-CHILDITEM $path -include $fileTypes

Foreach ($File in $Files) {
    $filepath = Join-Path -path $path -childpath ($File.basename +".pdf")
    $Doc = $Word.open($File.fullname, 3)
    $Doc.Saved= $true
    "Converting $File to pdf ... $destPath"
    # Save this File as a PDF in Word 2010/2013
    $Doc.ExportAsFixedFormat($formats::wdTypePDF, $path)
    $Doc.FullName -replace '\.doc?$', '.pdf'
    $Doc.Close()
}
$Word.Quit()

A: $path = 'C:\tests'

$wd = New-Object -ComObject Word.Application
Get-ChildItem -Path $path -Include *.doc, *.docx -Recurse |
    ForEach-Object {
        $doc = $wd.Documents.Open($_.Fullname)
        $pdf = $_.FullName -replace $_.Extension, '.pdf'
        $doc.ExportAsFixedFormat($pdf,17,$false,0,3,1,1,0,$false, $false,0,$false, $true)
        $doc.Close()
    }
$wd.Quit()

This will Go trough the folder and then look for .doc and .docx files
It then opens each file creates a new save name and exports to PDF
You can learn more about the ExportAsFixedFormat from
https://msdn.microsoft.com/en-us/library/bb256835(v=office.12).aspx


text:
Q: How to switch to a new function in index.js I basically have a router.post() function in my index.js, and I want to, inside that function, call another router.post() function. Like this:
router.post('/checkregisfields', function(req, res, next) {
var x = req.body.email;
var p = req.body.password;
var p1 = req.body.passwordagain;
console.log(x);
var atpos = x.indexOf("@");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
    res.render('index', {title: 'nDoto', err2: 'Invalid Email Address!'});
    return false;
}
if (p1!=p){
    res.render('index', {title: 'nDoto', err2: 'Passwords do not match!'});
}

// If email and password are all okay, "redirect" to my other
// router.post('/regsubmit', function(req, res, next) function
// What is the syntax/command to "redirect" to another post function?

})

router.post('/regsubmit', function(req, res, next) {
});

A: Just factor the common code into a function that can be called from two places:
function regsubmit(req, res, next) {
   // code here
}

router.post('/regsubmit', regsubmit);

Then, you can call regsubmit(req, res, next) from your other route handler too.


text:
Q: Как сократить до одной строчки Мне известно, что эту часть кода можно сохранить до одной, строчки, но я не знаю, как, помогите нубу)
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")


text:
Q: How to use tfs commands in nant script? I want to get latest a folder of TFS source control using TFS get command option in my nant script.
I have followed that link - http://msdn.microsoft.com/en-us/library/fx7sdeyf.aspx
 <property name="TF" value=""C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\TF.exe"" />
 <Exec Command="$(TF) C:\TFS-Build\Get-App>TF.exe get $/Main/XYZ /all /overwrite /force /recursive /noautoresolve /noprompt"></Exec>

where "C:\TFS-Build\Get-App" is the mapping location of that folder($/Main/XYZ) i want to download.
Can anyone please help me to run this command in nant script?

A: <property name="TF" value=""C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\TF.exe"" />
 <Exec program="${TF}" workingdir="C:\TFS-Build\Get-App" commandline="get $/Main/XYZ /all /overwrite /force /recursive /noautoresolve /noprompt"></Exec>

Check this page for more details:EXEC Task


text:
Q: How to draw a scatter map using customized colors I am plotting a scatter map using six customized colors. I want the scatters with values between [-0.15, -0.05] plotted wiht the middle-four colors, and scatters out of the range plotted with the 1st and last color.
This is for plotting a scatter map. I have tried to using "levels" and "extend" arguments to realize what I want, but this works in m.contourf and doesn't work in m.scatter. I also tried with "vmin" and "vmax" arguments in m.scatter, but the result is not satisfying.
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
from mpl_toolkits.basemap import Basemap

def plot_scatter():
    fig = plt.figure(figsize=(6,4))
    ax_0 = plt.gca()

    colors = ['lightskyblue', 'deepskyblue', 'dodgerblue', 'royalblue', 'mediumblue', 'navy']
    cmap = mpl.colors.ListedColormap(colors[::-1]) # let deeper blues indicates smaller values

    m = Basemap(llcrnrlon=113.7, llcrnrlat=22.35, urcrnrlon=114.7, urcrnrlat=22.9,\
            rsphere=(6378137.00,6356752.3142),\
            resolution='l', area_thresh=1000., projection='lcc', lat_1=22.5, lat_0=22.5, lon_0=114) #- shape文件,画出区域轮廓

    lons = [114.1267222, 114.111825, 114.04908059999998, 113.8175, 114.47, 114.1122222, 114.1658333, 114.0036111, 113.8936271, 113.8855675, 114.104705, 114.1508333, 114.5002778, 113.7672222, 114.1011111, 113.9536389, 113.8911111, 113.8979694, 114.5340278, 114.1436111, 114.2238889, 114.3366799, 114.3044444, 113.9308333, 114.3922222, 113.9147222, 113.8361111, 114.02916670000002, 114.2236111, 113.8686111, 114.1488889, 114.1230556, 114.1933333, 114.02916670000002, 113.9727778, 114.48444440000002, 114.2752778, 114.2422222, 114.01416670000002, 113.9288889, 114.5264328, 113.94485559999998, 114.19001670000002, 114.4861111, 114.1794444, 114.2430556, 114.1508333, 114.09555559999998, 114.2622222, 114.0163889, 114.3002778, 114.3552778, 113.8602778, 113.8797222, 114.2338889, 114.0708333, 114.43194440000002, 113.89305559999998]
    lats = [22.55097222, 22.55905833, 22.52501111, 22.67416667, 22.60055556, 22.60555556, 22.56472222, 22.54166667, 22.65377067, 22.47006253, 22.54966819, 22.55166667, 22.56944444, 22.72333333, 22.57194444, 22.76244444, 22.78166667, 22.70483, 22.59697222, 22.57166667, 22.555, 22.59546331, 22.7775, 22.48861111, 22.615, 22.5475, 22.77916667, 22.62305556, 22.64638889, 22.495, 22.61638889, 22.69611111, 22.64638889, 22.5725, 22.59638889, 22.53444444, 22.56666667, 22.72416667, 22.54888889, 22.67888889, 22.48137411, 22.50378611, 22.57101111, 22.48277778, 22.66222222, 22.58388889, 22.65611111, 22.5375, 22.76694444, 22.53027778, 22.67888889, 22.7125, 22.80166667, 22.55277778, 22.68527778, 22.56861111, 22.61888889, 22.58861111]
    values = [-0.03101638020010544, -0.059602408594572324, -0.08074725429957398, -0.052523178817571285, -0.06097954730989012, -0.048576189387818935, -0.05321303447484441, -0.08990485880945824, -0.07035292627778422, -0.08904485101486563, -0.050582862579880206, -0.08667040863306046, -0.2381958334486063, -0.09043589588854052, -0.015791558268944444, -0.04750735872842685, -0.0827816789190754, -0.0495746307369816, -0.09748174185420576, -0.05328468550193526, -0.0385492789056475, -0.12603457458801204, -0.03785426812465535, -0.10934222695289253, -0.06257603144203898, -0.05322345906174508, -0.0437720889282609, -0.029440526555296737, -0.0446847919726688, -0.05879880517527025, -0.042610207214769935, -0.07981280621664595, -0.056233334347744406, -0.07486982006522186, -0.064798640683293, -0.060273137801299975, -0.08829009917157292, -0.02696058143578384, -0.047529515842470234, -0.051839812353009496, -0.05970518244018841, -0.08892429975993077, -0.2594588992844997, -0.0853022809983619, -0.11143855759589913, -0.05064439000559071, -0.02366547879452241, -0.1743014882414493, -0.05539755391763087, -0.04722722346208863, -0.04903534243112728, -0.0613871242134162, -0.05259194456906426, -0.0933057542530412, -0.05063961430132472, -0.05351251987776765, -0.03849744311833736, -0.04819026109972248]

    sgt_scatter = m.scatter(lons, lats, s=60, c=values, marker="o", vmin=-0.15, vmax=-0.05, latlon=True, cmap=cmap)

    bounds = [ round(elem, 3) for elem in np.linspace(-0.15, -0.05, 5)] #
    m.colorbar(extend='both', ticks=bounds)

    m.drawmeridians(np.arange(10, 125, 0.5), labels=[1,0,0,1])
    m.drawparallels(np.arange(15, 30, 0.3),labels=[1,0,0,0])
    plt.show()

# by referring to ImportanceOfBeingErnest's answer, I changed my code as below, appreciation to ImportanceOfBeingErnest
def plot_scatter_new():
    fig = plt.figure(figsize=(6,4))

    # customized colormap
    colors = ['lightskyblue', 'deepskyblue', 'dodgerblue', 'royalblue', 'mediumblue', 'navy']
    cmap = mpl.colors.ListedColormap(colors[::-1]) # let deeper blues indicates smaller values

    # even bounds gives a contour-like effect
    bounds = [ round(elem, 3) for elem in np.linspace(-0.15, -0.05, 5)] #
    # get one more color than bounds from colormap
    colors = plt.get_cmap(cmap)(np.linspace(0,1,len(bounds)+1))
    # create colormap without the outmost colors
    cmap = mcolors.ListedColormap(colors[1:-1]) # 1:-1是从第二个到倒数第二个,左闭右开
    # set upper/lower color
    cmap.set_over(colors[-1])
    cmap.set_under(colors[0])

    m = Basemap(llcrnrlon=113.7, llcrnrlat=22.35, urcrnrlon=114.7, urcrnrlat=22.9,\
            rsphere=(6378137.00,6356752.3142),\
            resolution='l', area_thresh=1000., projection='lcc', lat_1=22.5, lat_0=22.5, lon_0=114) #- shape文件,画出区域轮廓

    lons = [114.1267222, 114.111825, 114.04908059999998, 113.8175, 114.47, 114.1122222, 114.1658333, 114.0036111, 113.8936271, 113.8855675, 114.104705, 114.1508333, 114.5002778, 113.7672222, 114.1011111, 113.9536389, 113.8911111, 113.8979694, 114.5340278, 114.1436111, 114.2238889, 114.3366799, 114.3044444, 113.9308333, 114.3922222, 113.9147222, 113.8361111, 114.02916670000002, 114.2236111, 113.8686111, 114.1488889, 114.1230556, 114.1933333, 114.02916670000002, 113.9727778, 114.48444440000002, 114.2752778, 114.2422222, 114.01416670000002, 113.9288889, 114.5264328, 113.94485559999998, 114.19001670000002, 114.4861111, 114.1794444, 114.2430556, 114.1508333, 114.09555559999998, 114.2622222, 114.0163889, 114.3002778, 114.3552778, 113.8602778, 113.8797222, 114.2338889, 114.0708333, 114.43194440000002, 113.89305559999998]
    lats = [22.55097222, 22.55905833, 22.52501111, 22.67416667, 22.60055556, 22.60555556, 22.56472222, 22.54166667, 22.65377067, 22.47006253, 22.54966819, 22.55166667, 22.56944444, 22.72333333, 22.57194444, 22.76244444, 22.78166667, 22.70483, 22.59697222, 22.57166667, 22.555, 22.59546331, 22.7775, 22.48861111, 22.615, 22.5475, 22.77916667, 22.62305556, 22.64638889, 22.495, 22.61638889, 22.69611111, 22.64638889, 22.5725, 22.59638889, 22.53444444, 22.56666667, 22.72416667, 22.54888889, 22.67888889, 22.48137411, 22.50378611, 22.57101111, 22.48277778, 22.66222222, 22.58388889, 22.65611111, 22.5375, 22.76694444, 22.53027778, 22.67888889, 22.7125, 22.80166667, 22.55277778, 22.68527778, 22.56861111, 22.61888889, 22.58861111]
    values = [-0.03101638020010544, -0.059602408594572324, -0.08074725429957398, -0.052523178817571285, -0.06097954730989012, -0.048576189387818935, -0.05321303447484441, -0.08990485880945824, -0.07035292627778422, -0.08904485101486563, -0.050582862579880206, -0.08667040863306046, -0.2381958334486063, -0.09043589588854052, -0.015791558268944444, -0.04750735872842685, -0.0827816789190754, -0.0495746307369816, -0.09748174185420576, -0.05328468550193526, -0.0385492789056475, -0.12603457458801204, -0.03785426812465535, -0.10934222695289253, -0.06257603144203898, -0.05322345906174508, -0.0437720889282609, -0.029440526555296737, -0.0446847919726688, -0.05879880517527025, -0.042610207214769935, -0.07981280621664595, -0.056233334347744406, -0.07486982006522186, -0.064798640683293, -0.060273137801299975, -0.08829009917157292, -0.02696058143578384, -0.047529515842470234, -0.051839812353009496, -0.05970518244018841, -0.08892429975993077, -0.2594588992844997, -0.0853022809983619, -0.11143855759589913, -0.05064439000559071, -0.02366547879452241, -0.1743014882414493, -0.05539755391763087, -0.04722722346208863, -0.04903534243112728, -0.0613871242134162, -0.05259194456906426, -0.0933057542530412, -0.05063961430132472, -0.05351251987776765, -0.03849744311833736, -0.04819026109972248]

    sgt_scatter = m.scatter(lons, lats, s=60, c=values, marker="o", vmin=-0.15, vmax=-0.05, latlon=True, cmap=cmap)

    m.colorbar(extend='both', ticks=bounds)

    m.drawmeridians(np.arange(10, 125, 0.5), labels=[1,0,0,1])
    m.drawparallels(np.arange(15, 30, 0.3),labels=[1,0,0,0])
    plt.show()

if __name__ == '__main__':
    plot_scatter()
    plot_scatter_new()

The result of the above codes would be like this:

But I want the 1st and last color display as the extend part of the colorbar.


text:
Q: How to assign key:value to dict iterating over dynamic nested dict How can I iterate over nested JSON data, extracting values, only when the key exists?
Using the Twitter API, if a tweet contains a hashtag, it's nested in tweet -> entities -> hashtags -> 0 (and this is the bit that changes) -> text.
If a tweet has more than 1 hashtag, the API creates a new key inside hastags going up from 0. So you can end up with tweet -> entities -> hashtags: {0: foo}, {1: bar}, {2: sup}, etc.
{
    "_id" : ObjectId("593adcb1b27be5eb5daa7e66"),
    "created_at" : "Fri Jun 09 14:54:55 +0000 2017",
    "id" : NumberLong(873191685915906049),
    "id_str" : "873191685915906049",
    "text" : "RT @NiamhMannion_: A beautiful day in Kinvara! Really impressed by the delicious produce @kinvaramarket #FoodieHeaven URL",
    "truncated" : false,
    "entities" : {
        "hashtags" : [
            {
                "text" : "FoodieHeaven",
                "indices" : [
                    104,
                    117
                ]
            }
        ],
        "symbols" : [],
        "user_mentions" : [
            {
                "screen_name" : "NiamhMannion_",
                "name" : "Niamh Mannion",
                "id" : NumberLong(2178812961),
                "id_str" : "2178812961",
                "indices" : [
                    3,
                    17
                ]
            },
            {
                "screen_name" : "kinvaramarket",
                "name" : "KinvaraFarmersMarket",
                "id" : NumberLong(3064922836),
                "id_str" : "3064922836",
                "indices" : [
                    89,
                    103
                ]
            }
        ],
        "urls" : []
    },
    "source" : "Twitter Web Client",
    "in_reply_to_status_id" : null,
    "in_reply_to_status_id_str" : null,
    "in_reply_to_user_id" : null,
    "in_reply_to_user_id_str" : null,
    "in_reply_to_screen_name" : null,
    "user" : {
        "id" : 37690003,
        "id_str" : "37690003",
        "name" : "Gabriela Guedez H",
        "screen_name" : "GabyGuedezH",
        "location" : "Ireland",
        "description" : "Award-wining food and drinks journalist at @TheTaste_ie Passionate about wines, whiskey, rum, spirits and craft beer. WSET Certified",
        "url" : "URL",
        "entities" : {
            "url" : {
                "urls" : [
                    {
                        "url" : "URL",
                        "expanded_url" : "URL",
                        "display_url" : "URL",
                        "indices" : [
                            0,
                            22
                        ]
                    }
                ]
            },
            "description" : {
                "urls" : []
            }
        },
        "protected" : false,
        "followers_count" : 7900,
        "friends_count" : 5047,
        "listed_count" : 159,
        "created_at" : "Mon May 04 16:02:34 +0000 2009",
        "favourites_count" : 8905,
        "utc_offset" : 3600,
        "time_zone" : "Dublin",
        "geo_enabled" : true,
        "verified" : false,
        "statuses_count" : 12727,
        "lang" : "en",
        "contributors_enabled" : false,
        "is_translator" : false,
        "is_translation_enabled" : false,
        "profile_sidebar_border_color" : "5ED4DC",
        "profile_sidebar_fill_color" : "95E8EC",
        "profile_text_color" : "3C3940",
        "profile_use_background_image" : true,
        "has_extended_profile" : false,
        "default_profile" : false,
        "default_profile_image" : false,
        "following" : true,
        "follow_request_sent" : false,
        "notifications" : false,
        "translator_type" : "none"
    },
    "geo" : null,
    "coordinates" : null,
    "place" : null,
    "contributors" : null,
    "is_quote_status" : false,
    "retweet_count" : 4,
    "favorite_count" : 14,
    "favorited" : true,
    "retweeted" : true,
    "possibly_sensitive" : false,
    "lang" : "en",
    "has_hashtags" : false,
    "is_retweet" : false
}
I want to take all existing hashtags, extract the text and store it in my new dictionary.
for tweet in tweets:
    thistweet = {
        'text': tweet.text,
        'created_at': str(tweet.created_at),
        'retweet_count': tweet.retweet_count,
        'favorite_count': tweet.favorite_count,
        'geo': tweet.geo,
        'coordinates': tweet.coordinates
    }
    for i in tweet[entities][hashtags][i]:
        thistweet = thistweet.update({'hashtag'[i]: tweet.entities.hashtags.i.text})

That bit of code doesn't work. I'm getting 'dict' object has no attribute 'hashtags'.
I'm not entirely sure how to start trying to fix this issue to be honest.

A: Try this,
for tweet in tweets:
    thistweet = {
        'text': tweet.text,
        'created_at': str(tweet.created_at),
        'retweet_count': tweet.retweet_count,
        'favorite_count': tweet.favorite_count,
        'geo': tweet.geo,
        'coordinates': tweet.coordinates,
        'hashtags':{}
    }
    for index, item in enumerate(tweet.entities.hashtags):
        try:
            thistweet = thistweet['hashtags'].update({item:tweet.entities.hashtags[index]['text']})
        except:
            pass


text:
Q: Consul not deregistering zombie services I am deploying a simple hello world nginx container with marathon, and everything seems to work well, except that I have 6 containers that will not deregister from consul. docker ps shows none of the containers are running.
I tried using the /v1/catalog/deregister endpoint to deregister the services, but they keep coming back. I then killed the registrator container, and tried deregistering again. They came back.
I am running registrator with
docker run -d --name agent-registrator -v /var/run/docker.sock:/tmp/docker.sock --net=host gliderlabs/registrator consul://127.0.0.1:8500 -deregister-on-success -cleanup

There is 1 consul agent running.
Restarting the machine (this is a single node installation on a local vm) does not make the services go away.
How do I make these containers go away?

A: Using the http api for removing services is another much nicer solution.  I just figured out how to manually remove services before I figured out how to use the https api.
To delete a service with the http api use the following command:

curl -v -X PUT http://<consul_ip_address>:8500/v1/agent/service/deregister/<ServiceID>

Note that your  is a combination of three things: the IP address of host machine the container is running on, the name of the container, and the inner port of the container (i.e. 80 for apache, 3000 for node js, 8000 for django, ect) all separated by colins :
Heres an example of what that would actually look like:

curl -v -X PUT http://1.2.3.4:8500/v1/agent/service/deregister/192.168.1.1:sharp_apple:80

If you want an easy way  to get the ServiceID then just curl the service that contains a zombie:

curl -s http://<consul_ip_address>:8500/v1/catalog/service/<your_services_name>

Heres a real example for a service called someapp that will return all the services under it:

curl -s http://1.2.3.4:8500/v1/catalog/service/someapp

A: Don't use catalog, instead of using agent, the reason is catalog is maintained by agents, it will be resync-back by agent even if you remove it from catalog, remove zombie services shell script:
leader="$(curl http://ONE-OF-YOUR-CLUSTER:8500/v1/status/leader | sed

's/:8300//' | sed 's/"//g')"
while :
do
serviceID="$(curl http://$leader:8500/v1/health/state/critical | ./jq '.[0].ServiceID' | sed 's/"//g')"
node="$(curl http://$leader:8500/v1/health/state/critical | ./jq '.[0].Node' | sed 's/"//g')"
echo "serviceID=$serviceID, node=$node"
size=${#serviceID}
echo "size=$size"
if [ $size -ge 7 ]; then
curl --request PUT http://$node:8500/v1/agent/service/deregister/$serviceID
else
break
fi
done
curl http://$leader:8500/v1/health/state/critical

json parser jq is used for field retrieving

A: Here is how you can absolutely delete all the zombie services: Go into your consul server, find the location of the json files containing the zombies and delete them.
For example I am running consul in a container:
docker run --restart=unless-stopped -d -h consul0 --name consul0 -v /mnt:/data \
    -p $(hostname -i):8300:8300 \
    -p $(hostname -i):8301:8301 \
    -p $(hostname -i):8301:8301/udp \
    -p $(hostname -i):8302:8302 \
    -p $(hostname -i):8302:8302/udp \
    -p $(hostname -i):8400:8400 \
    -p $(hostname -i):8500:8500 \
    -p $(ifconfig docker0 | awk '/\<inet\>/ { print $2}' | cut -d: -f2):53:53/udp \
    progrium/consul -server -advertise $(hostname -i) -bootstrap-expect 3

Notice the flag -v /mnt:/data this is where all the data consul is storing is located. For me it was located in /mnt. Under this directory you will find several other directories.
config raft  serf  services  tmp
Go into services and you will see the files that contain the json info of your services, find any ones that contains the info of zombies and delete them.  Then restart consul.  Then repeat for each server in your cluster that has zombies on it.

A: In a Consul Cluster the Agents are considered authoritative. If you use the the HTTP Api /v1/catalog/deregister endpoint to deregister services, it will keep coming back as long as other Agents have known about that service. It's the way that the Gossip protocol works.
If you want Services to go away immediately you need to deregister the host agent properly by issuing a consul leave before killing the service on the node.

A: This is one of the problems with Consul and registrator, if the service doesn't have a check associated with it, the service will stick around until it's de-registered and be "active". So it's good practice to have services register a health check as well. That way they will at least be critical if registrator messes up and forgets to de-register the service (which I see happens a lot).  Alex's answer, of erasing the files in consul's data/services directory (then consul reload) definitely works to erase the service, but registrator will re-add them, if the containers are still around and running.  Apparently the newer registrator versions are better at cleanup, but I've had mixed success.  Now I don't use registrator at all, since it doesn't add health checks.  I use nomad to run my containers (also from hashicorp) and it will create the service AND create the health check, and does a great job of cleaning up after itself.

A: Try to switch to v5
docker run -d --name agent-registrator -v /var/run/docker.sock:/tmp/docker.sock gliderlabs/registrator:v5 -internal consul://172.16.0.4:8500


text:
Q: Adodb.Connection not working in Excel VBA OS: windows 7 pro 64 bit I have an Excel file with VBA code, to import data from an Oracle database, which runs on Windows XP.
When I try on Windows 7 SP1 64 bit I get an error on the first line of below code.
Function getConnection2() As ADODB.Connection
  Dim cnn As New ADODB.Connection
  Dim strCnn As String

  strCnn = "Data Source=XXXXX;User ID=XXXXX;Password=XXXXXXX;"
  cnn.Provider = "OraOLEDB.Oracle"
  cnn.ConnectionString = strCnn

  cnn.Open
  Set getConnection2 = cnn
End Function

Error:  Compile Error: Automation Error
I searched MSDASQL for Windows 7 but was unable to find same on Microsoft website. They have it for Windows 2003
http://www.microsoft.com/en-in/download/details.aspx?id=20065
Do we have any solution for this feels like its unable to create object for ADODB.

A: Is it a complie error?
I think in windows 7, the library you used on XP 32bit is no longer there
VBA Editor Tools-->Reference--> Add Microsoft ActiveX Data Object X.Y Library


text:
Q: The remote server returned an error : 400 badrequest in WCF In our project, we are calling the .svc file directly from asp.net web page and I receive the error "The remoter server returned an error:(400) bad request.
Our project architecture is, we are using .svc file in our web application and the .cs file for the svc in writter in another class library project. From aspx, we are calling the WCF service directly without adding reference or anything. I cannot change the concept, because it is our standard. I'm able to add service reference and call those methods, but I wanted to call the method directly from .svc url.
I'm pissed off for 2 days and could not resolve the error. We are using HttpWebRequest to get the response from the service. Basically, the service will take Data Transfer Object(DTO) as input and returns the same(DTO) as output with only one value.
Check the following code:
HttpStatusCode statusCode = HttpHelper.PostXmlRequestValue(requestXMLInput,
      string.Format("http://{0}/{1}/MySample.svc/webhttp/MyMethodName",
      Request.ServerVariable["HTTP_HOST"], Request.ApplicationPath);

The same code works in one machine but not in the other. I have checked the configuration and everything is same, but still I receive the same error.
When I use the .svc url in my machine, it works, but gives a message "Method not allowed". When I checked the same url in the working machine, I got the same message.. I believe there is some simple thing I'm missing out. I couldn't find, as I'm new to WCF.

A: When using HttpWebRequest the "Method not allowed" error is for example that you are sending a Http GET, when the service expects a Http POST.
HttpWebRequest is a REST based configuration, this limits the complexity of the DTO's that you can send.


text:
Q: how can i find lcs length between two large strings I've written the following code in C# for obtaining the length of longest common subsequence of two texts given by use, but it doesn't work with large strings. Could you please help me. I'm really confused.
public Form1()
{
    InitializeComponent();
}

public int lcs(char[] s1, char[] s2, int s1size, int s2size)
{
    if (s1size == 0 || s2size == 0)
    {
        return 0;
    }
    else
    {
        if (s1[s1size - 1] == s2[s2size - 1])
        {
            return (lcs(s1, s2, s1size - 1, s2size - 1) + 1);
        }
        else
        {
            int x = lcs(s1, s2, s1size, s2size - 1);
            int y = lcs(s1, s2, s1size - 1, s2size);
            if (x > y)
            {
                return x;
            }
            else
                return y;
        }
    }
}

private void button1_Click(object sender, EventArgs e)
{
    string st1 = textBox2.Text.Trim(' ');
    string st2 = textBox3.Text.Trim(' ');

    char[] a = st1.ToCharArray();
    char[] b = st2.ToCharArray();

    int s1 = a.Length;
    int s2 = b.Length;

    textBox1.Text = lcs(a, b, s1, s2).ToString();
}

A: Here you are using the Recursion method. So it leads the program to occur performance problems as you mentioned.
Instead of recursion, use the dynamic programming approach.
Here is the C# Code.
public static void LCS(char[] str1, char[] str2)
    {
        int[,] l = new int[str1.Length, str2.Length];
        int lcs = -1;
        string substr = string.Empty;
        int end = -1;

        for (int i = 0; i < str1.Length; i++)
        {
            for (int j = 0; j < str2.Length; j++)
            {
                if (str1[i] == str2[j])
                {
                    if (i == 0 || j == 0)
                    {
                        l[i, j] = 1;
                    }
                    else
                        l[i, j] = l[i - 1, j - 1] + 1;
                    if (l[i, j] > lcs)
                    {
                        lcs = l[i, j];
                        end = i;
                    }

                }
                else
                    l[i, j] = 0;
            }
        }

        for (int i = end - lcs + 1; i <= end; i++)
        {
            substr += str1[i];
        }

        Console.WriteLine("Longest Common SubString Length = {0}, Longest Common Substring = {1}", lcs, substr);
    }

A: Here is a solution how to find the longest common substring in C#:
public static string GetLongestCommonSubstring(params string[] strings)
{
    var commonSubstrings = new HashSet<string>(strings[0].GetSubstrings());
    foreach (string str in strings.Skip(1))
    {
        commonSubstrings.IntersectWith(str.GetSubstrings());
        if (commonSubstrings.Count == 0)
            return string.Empty;
    }

    return commonSubstrings.OrderByDescending(s => s.Length).DefaultIfEmpty(string.Empty).First();
}

private static IEnumerable<string> GetSubstrings(this string str)
{
    for (int c = 0; c < str.Length - 1; c++)
    {
        for (int cc = 1; c + cc <= str.Length; cc++)
        {
            yield return str.Substring(c, cc);
        }
    }
}

I found it here: http://www.snippetsource.net/Snippet/75/longest-common-substring

A: Just for fun, here is one example using Queue<T>:
string LongestCommonSubstring(params string[] strings)
{
    return LongestCommonSubstring(strings[0], new Queue<string>(strings.Skip(1)));
}

string LongestCommonSubstring(string x, Queue<string> strings)
{
    if (!strings.TryDequeue(out var y))
    {
        return x;
    }

    var output = string.Empty;

    for (int i = 0; i < x.Length; i++)
    {
        for (int j = x.Length - i; j > -1; j--)
        {
            string common = x.Substring(i, j);
            if (y.IndexOf(common) > -1 && common.Length > output.Length) output = common;
        }
    }

    return LongestCommonSubstring(output, strings);
}

It's still using recursion though, but it's a nice example of Queue<T>.

A: I refactored the C++ code from Ashutosh Singh at https://iq.opengenus.org/longest-common-substring-using-rolling-hash/ to create a rolling hash approach in C# - this will find the substring in O(N * log(N)^2) time and O(N) space
using System;
using System.Collections.Generic;
public class RollingHash
{
    private class RollingHashPowers
    {
        // _mod = prime modulus of polynomial hashing
        // any prime number over a billion should suffice
        internal const int _mod = (int)1e9 + 123;
        // _hashBase = base (point of hashing)
        // this should be a prime number larger than the number of characters used
        // in my use case I am only interested in ASCII (256) characters
        // for strings in languages using non-latin characters, this should be much larger
        internal const long _hashBase = 257;
        // _pow1 = powers of base modulo mod
        internal readonly List<int> _pow1 = new List<int> { 1 };
        // _pow2 = powers of base modulo 2^64
        internal readonly List<long> _pow2 = new List<long> { 1L };

        internal void EnsureLength(int length)
        {
            if (_pow1.Capacity < length)
            {
                _pow1.Capacity = _pow2.Capacity = length;
            }
            for (int currentIndx = _pow1.Count - 1; currentIndx < length; ++currentIndx)
            {
                _pow1.Add((int)(_pow1[currentIndx] * _hashBase % _mod));
                _pow2.Add(_pow2[currentIndx] * _hashBase);
            }
        }
    }

    private class RollingHashedString
    {
        readonly RollingHashPowers _pows;
        readonly int[] _pref1; // Hash on prefix modulo mod
        readonly long[] _pref2; // Hash on prefix modulo 2^64

        // Constructor from string:
        internal RollingHashedString(RollingHashPowers pows, string s, bool caseInsensitive = false)
        {
            _pows = pows;
            _pref1 = new int[s.Length + 1];
            _pref2 = new long[s.Length + 1];

            const long capAVal = 'A';
            const long capZVal = 'Z';
            const long aADif = 'a' - 'A';

            unsafe
            {
                fixed (char* c = s)
                {
                    // Fill arrays with polynomial hashes on prefix
                    for (int i = 0; i < s.Length; ++i)
                    {
                        long v = c[i];
                        if (caseInsensitive && capAVal <= v && v <= capZVal)
                        {
                            v += aADif;
                        }
                        _pref1[i + 1] = (int)((_pref1[i] + v * _pows._pow1[i]) % RollingHashPowers._mod);
                        _pref2[i + 1] = _pref2[i] + v * _pows._pow2[i];
                    }
                }
            }
        }

        // Rollingnomial hash of subsequence [pos, pos+len)
        // If mxPow != 0, value automatically multiply on base in needed power.
        // Finally base ^ mxPow
        internal Tuple<int, long> Apply(int pos, int len, int mxPow = 0)
        {
            int hash1 = _pref1[pos + len] - _pref1[pos];
            long hash2 = _pref2[pos + len] - _pref2[pos];
            if (hash1 < 0)
            {
                hash1 += RollingHashPowers._mod;
            }
            if (mxPow != 0)
            {
                hash1 = (int)((long)hash1 * _pows._pow1[mxPow - (pos + len - 1)] % RollingHashPowers._mod);
                hash2 *= _pows._pow2[mxPow - (pos + len - 1)];
            }
            return Tuple.Create(hash1, hash2);
        }
    }

    private readonly RollingHashPowers _rhp;
    public RollingHash(int longestLength = 0)
    {
        _rhp = new RollingHashPowers();
        if (longestLength > 0)
        {
            _rhp.EnsureLength(longestLength);
        }
    }

    public string FindCommonSubstring(string a, string b, bool caseInsensitive = false)
    {
        // Calculate max neede power of base:
        int mxPow = Math.Max(a.Length, b.Length);
        _rhp.EnsureLength(mxPow);
        // Create hashing objects from strings:
        RollingHashedString hash_a = new RollingHashedString(_rhp, a, caseInsensitive);
        RollingHashedString hash_b = new RollingHashedString(_rhp, b, caseInsensitive);

        // Binary search by length of same subsequence:
        int pos = -1;
        int low = 0;
        int minLen = Math.Min(a.Length, b.Length);
        int high = minLen + 1;
        var tupleCompare = Comparer<Tuple<int, long>>.Default;
        while (high - low > 1)
        {
            int mid = (low + high) / 2;
            List<Tuple<int, long>> hashes = new List<Tuple<int, long>>(a.Length - mid + 1);
            for (int i = 0; i + mid <= a.Length; ++i)
            {
                hashes.Add(hash_a.Apply(i, mid, mxPow));
            }
            hashes.Sort(tupleCompare);
            int p = -1;
            for (int i = 0; i + mid <= b.Length; ++i)
            {
                if (hashes.BinarySearch(hash_b.Apply(i, mid, mxPow), tupleCompare) >= 0)
                {
                    p = i;
                    break;
                }
            }
            if (p >= 0)
            {
                low = mid;
                pos = p;
            }
            else
            {
                high = mid;
            }
        }
        // Output answer:
        return pos >= 0
            ? b.Substring(pos, low)
            : string.Empty;
    }
}


text:
Q: Undefined References to SDL_mixer functions from a static library (Code::Blocks) So, I've made a static library with references to SDL_mixer functions (and those work fine), but when I try to build the project that links to the library, Code::Blocks tells me that every function used (in the static library) is an undefined reference. I've searched and searched, but everyone else seems to always have a linker problem, so here is my order: -lSDL2,
-lSDL2_ttf,
-lSDL2_mixer,
-lGL,
-lGLEW, and then my library
Everything works fine, except for the one file that I try to use SDL_mixer functions. And by the way, everything worked before I converted to Code::Blocks. Any help is greatly appreciated :)

A: It was the order that I was linking the libraries. I changed the order so that my library was linked before the rest, and it worked perfectly
I guess I shouldn't be so confident with my own code so much :|


text:
Q: How to pass field values as arguement to a stored procedure I have a DB table in which one column have an array of values.
Lets assume
Student table
"Name" character(10),
"Subject_studying" text[],

I created a stored procedure as follows
CREATE OR REPLACE FUNCTION ArrayLike(vals text[], v text) RETURNS integer AS $$
DECLARE
  str text;
BEGIN
  v := replace(replace(v, '%', '.*'), '_', '.');
  FOREACH str IN ARRAY vals LOOP
    IF str ~* v THEN
      RETURN 1;
    END IF;
  END LOOP;
  RETURN 0;
END; $$
LANGUAGE PLPGSQL;

Which returns all the subjects that I'm looking for.
How do I pass the parameter of the subjects to the stored procedure.
My query looks like
SELECT Name FROM Student WHERE ArrayLike('Subject_studying', 'english') = 1

The query is giving me an error
 ERROR:  FOREACH expression must not be null
CONTEXT:  PL/pgSQL function Arraylike(text[],text) line 6 at FOREACH over array
********** Error **********

I guess the parameter 'Subject_studying' is not sent as a value but as a simple string. How do we pass the values in that field to the stored procedure?

A: The error is caused by passing the column name subject_studying as a string, as you already noted. Unquote it to make the error go away.
But you actually do not have to create your own function for this. You can use the built-in ANY operator:
SELECT Name FROM Student WHERE 'english' = ANY(subject_studying);


text:
Q: What is best algorithm for password encryption and decryption for android and web application in google app engine? We have developed an application using google app engine. We have an android and web application which communicates to same database. We have log in functionality.For which we need to encrypt and decrypt the password. We tried few earlier but it's not in sync.It means if we apply it both side then login fails at android side and vice versa.
Can you please suggest us which algorithm will be useful for both side so android and web both will work on same algorithm.
Thanks,
Prashant

A: I recommend either bcrypt or PBKDF2. Both are algorithms especially designed for hashing passwords.


text:
Q: Are HTML links that target a .php script basically forms? Normally an HTML link transfers you to another page, i.e., the browser loads in a different page. For example, an "asking help" link might be implemented with:
asking help »

But there are also links that target a php file, like
Edit

This seems to be an entirely different animal and looks effectively like a form, where post and action values are uploaded to a form handler at
http://example.com/wp-admin/post.php
Is that's what happening? Are you effectively implementing a form when the link target is a .php file?

A:
Are you effectively implementing a form when the link target is a .php file?

Not quite. You're requesting a resource from the webserver, and in the example you give (http://example.com/wp-admin/post.php), this "resource" is a php file. Many webservers will eliminate the file extension because it shouldn't matter to the end user how you've implemented your site, as long as they can access the page at http://example.com/wp-admin/post. For some more good information on URLs/URIs and file extensions check out this SO question: How come some site urls do not include a file extension?
Your second example (http://example.com/wp-admin/post.php?post=182&action=edit) is adding a slight wrinkle to this, a query string. The query string is "the part of a URL containing data that does not fit conveniently into a hierarchical path structure" (Wikipedia). In this case, the query string is passing two paramteters to the post.php page. The first parameter is named post and its value appears to be the ID of the post that you would like to view. The second parameter is action and the value is the action that you would like to perform on the given post, view, edit and delete are three likely possible values for this parameter. Once the server processes this request, it returns a page that allows you to edit the post with an ID of 182 or perhaps a page telling you that you don't have permissions to edit this post.

A: Both of these cause HTTP Get Requests. One has variables and one does not.
asking help »

Edit

Both could be created as a form with method="GET". The difference is that one has hardcoded parameters like action="edit" and title="Edit this Item". If you did this as a form you could allow the user to change the parameters such as title. Most sites of any substantial information you would want to complete as a Form and use the method="POST" attribute so that the information is a little more secure. Using HTTP Get for form posts allows for URL injection.
http://example.com/wp-admin/post.php?post=183&action="Approved";title="This Item approved"


text:
Q: Definable types over stably embedded sets Let $T$ be a complete $\mathcal{L}$-theory and $\mathfrak{U}$ a monster model, with $\theta(v)$ an $\mathcal{L}$-formula and $M\preccurlyeq \mathfrak{U}$ a (not necessarily small) model. We say that $\theta(M)$ is stably embedded in $M$ if, for every $\mathcal{L}_M$-formula $\varphi(v_1,\dots,v_n,\overline{m})$, the formula $\varphi(v_1,\dots,v_n,\overline{m})\wedge\bigwedge_{i=1}^n\theta(v_i)$ is equivalent to some $\mathcal{L}_{\theta(M)}$ formula. The following exercise is from Tent and Ziegler:

Exercise 8.3.4: Show that $\theta(M)$ is stably embedded in $M$ if and only if, for all $n$, every $p\in S_n(\theta(M))$ which contains $\bigwedge_{i=1}^n\theta(v_i)$ has a unique extension $\overline{p}\in S_n(M)$. If $\theta$ is absolutely stably embedded and $p$ is definable, show that $\overline{p}$ is definable over $\theta(M)$.

I've done the first part of the problem, for which one direction is clear; indeed, if $p_1,p_2\in S_n(M)$ are distinct extensions of $p$, let $\varphi(\overline{v},\overline{m})$ be a separating formula, with $\varphi\in p_1$ and $\neg\varphi\in p_2$. Since $\bigwedge_{i=1}^n\theta(v_i)\in p_1,p_2$, letting $\varphi'=\varphi(\overline{v},\overline{m})\wedge\bigwedge_{i=1}^n\theta(v_i)$ still gives $\varphi'\in p_1$ and $\neg\varphi'\in p_2$. If $\theta(M)$ were stably embedded, then $\varphi'$ would be equivalent to an $\mathcal{L}_{\theta(M)}$-formula, and then either that formula or its negation would lie in $p$, which would make one of $p_1$ or $p_2$ inconsistent.
The other direction seems to require a bit more work; suppose any type in $S_n(\theta(M))$ containing $\bigwedge_{i=1}^n\theta(v_i)$ has a unique extension to $S_n(M)$, and let $\varphi(v_1,\dots,v_n,\overline{m})$ be any $\mathcal{L}_M$-formula such that $\varphi\to\bigwedge_{i=1}^n\theta(v_i)$. We wish to show that $\varphi$ is equivalent to some $\mathcal{L}_{\theta(M)}$ formula. To see this, enumerate the stone space $S_n(\theta(M))$ as $(p_\alpha)_{\alpha\in\lambda}$ for some cardinal $\lambda$, and define
\begin{align}
A&=\{\alpha\in\lambda:p_\alpha\cup\{\varphi(\overline{v},\overline{m})\}\text{ is consistent}\} \\
B&=\{\beta\in\lambda:p_\beta\cup\{\neg\varphi(\overline{v},\overline{m})\}\text{ is consistent}\}.
\end{align}
We claim $S_n(\theta(M))=A\sqcup B$. That $S_n(\theta(M))=A\cup B$ is clear, and disjointness follows from the hypothesis on types. Indeed, if $p_\alpha$ is consistent with $\varphi(\overline{v},\overline{m})$, then it must contain $\bigwedge_{i=1}^n\theta(v_i)$, and so by the hypothesis has a unique extension to $S_n(M)$. This extension must contain $\varphi(\overline{v},\overline{m})$, and so $p_\alpha$ is inconsistent with $\neg\varphi(\overline{v},\overline{m})$, whence $\alpha\notin B$, as desired. Thus, for any $\alpha\in A$ and $\beta\in B$, we can choose $\psi_{\alpha\beta}$ with $\psi_{\alpha\beta}\in p_\alpha$ and $\neg\psi_{\alpha\beta}\in p_\beta$; note in particular that $\psi_{\alpha\beta}$ is an $\mathcal{L}_{\theta(M)}$-formula.
Now, fix $\alpha\in A$. Since any type over $M$ containing $\neg\varphi$ must contain $p_\beta$ for some $\beta\in B$, we have $\{\psi_{\alpha\beta}\}_{\beta\in B}\models \varphi$, and thus there are $\beta_1,\dots,\beta_k$ such that $\{\psi_{\alpha\beta_i}\}_{i=1}^k\models\varphi$. Let $\eta_\alpha=\bigwedge_{i=1}^k\psi_{\alpha\beta_i}$, so that $\eta_\alpha\to\varphi$ and $\eta_\alpha\in p_\alpha$. Since every type over $M$ containing $\varphi$ must be $p_\alpha$ for some $\alpha\in A$, this latter condition means $\{\neg\eta_\alpha\}_{\alpha\in A}\models \neg\varphi$, and thus there are $\alpha_1,\dots,\alpha_k$ with $\{\neg\eta_{\alpha_i}\}_{i=1}^k\models\neg\varphi$. Then, letting $\eta=\bigvee_{i=1}^k\eta_{\alpha_i}$, we have $\varphi\leftrightarrow\eta$, and by construction $\eta$ is an $\mathcal{L}_{\theta(M)}$-formula, as desired.
So this wraps up the first part. Unfortunately, I'm struggling a bit with the second part. For one thing, I'm not actually sure what T&Z mean by "absolutely" stably embedded; this isn't a term they've defined. I assume this result doesn't hold in the general case, or else they wouldn't add that qualifier, but for now I've only been trying to approach it in general. Perhaps it will be clearer once I know the right hypotheses?
Anyway, let $\varphi(\overline{v},\overline{w})$ be an $\mathcal{L}$-formula; we may assume $\varphi(\overline{v},\overline{w})\to\bigwedge_{i=1}^n\theta(v_i)$. For any $\overline{m}\in M$, we then know that $\varphi(\overline{v},\overline{m})$ is equivalent to some $\theta(M)$-formula $\psi_\overline{m}(\overline{v},\overline{a}_\overline{m})$, and so $\varphi(\overline{v},\overline{m})\in\overline{p}$ if and only if $\psi_\overline{m}(\overline{v},\overline{a}_\overline{m})\in p$. Thus, if there were some way to choose all the $\psi_\overline{m}(\overline{v},\overline{u})$ to be equal, we would be done, since we would have $$\varphi(\overline{v},\overline{m})\in \overline{p}\iff\mathfrak{U}\models\exists \overline{u}\left[\bigwedge_{i=1}^k \theta(u_i)\wedge\left[\forall\overline{v}\varphi(\overline{v},\overline{m})\leftrightarrow\psi(\overline{v},\overline{u})\right]\wedge d_p\overline{v}\psi(\overline{v},\overline{u})\right],$$ where $\psi=\psi_\overline{m}$ for all $\overline{m}$ and $d_p\overline{v}$ denotes the definition of $p$ over $\theta(M)$. However, I'm not so sure how we might go about removing the dependence on $\overline{m}$, and presumably we can't in general; does the "absolute" hypothesis somehow make this possible? Is this even a good approach, or does it not work?

A: You've correctly identified the sticking point in your suggested proof: Every formula $\varphi(v,m)$ with $m\in M$ is equivalent to some formula $\psi_m(v,n)$ with $n\in \theta(M)$, but which formula $\psi_m$ works apparently depends on $\varphi$ and $m$, and we would like it to depend just on $\varphi$.
One of the most important tricks in the model theory toolbox is using the compactness theorem to get "uniformity for free". We often know something of the form "In every model $M$, for every definable set $X$, there exists a definable set $Y$ such that..." Then we can use the compactness theorem to show that when we restrict to those $X$ which are defined by instances of a formula $\varphi$, there must be finitely many formulas $\psi_1,\dots,\psi_k$ such that the witnessing $Y$ is defined by an instance of one of the $\psi_i$. And finally, we can code the finitely many $\psi_i$ into a single formula and conclude "For every formula $\varphi$ there is a formula $\psi$ such that for every instance $X$ of $\varphi$ there is an instance $Y$ of $\psi$ such that..."
At this point, you might like to use the above as a hint and try to solve the exercise yourself. But if you get stuck, here are the details.
Suppose $\theta(M)$ is stably embedded in $M$ for every $M\models T$. To simplify notation, I'll write all tuples of variables as if they were singletons. Fix a formula $\varphi(v,w)$ which implies $\theta(v)$. Consider the following partial type in the variables $w$: $$T\cup \{\lnot \exists z\,(\theta(z)\land \forall v\, (\varphi(v,w)\leftrightarrow \psi(v,z)))\mid \psi(v,z)\in \mathcal{L}\}.$$
This partial type is inconsistent (this is where we need to use stable embeddedness in every small model, or equivalently in the monster model). So by compactness there are finitely many formulas $\psi_1(v,z_1),\dots,\psi_k(v,z_k)\in \mathcal{L}$ such that $$T\models \forall w\, \bigvee_{i=1}^k \exists z_i\,(\theta(z_i)\land \forall v\, (\varphi(v,w)\leftrightarrow \psi_i(v,z_i))).$$
Now by the standard trick of coding finitely many formulas by a single formula (which I described, for example, here), we may assume there is a single formula $\psi(v,z)$ such that for every model $M$ and every instance of $\varphi(v,w)$ with parameters from $M$, there is an equivalent instance of $\psi(v,z)$ with parameters from $\theta(M)$.
[Technical note: To do this coding, we need to assume that $\theta(M)$ has as least two elements. But if $\theta(M)$ has at most one element, then any complete type which implies $\theta(v)$ is realized in $M$, and hence definable.]
Finally, we can conclude as you did, writing down an explicit definition over $\theta(M)$ for any type containing $\theta(v)$ which is definable over $M$.


text:
Q: Units of Klein-Gordon equation I'm looking at the units of the Klein-Gordon equation
$$u_{tt} - c^2\Delta u = -\frac{m^2c^2}{\hbar^2}u.
$$
Disregarding the units of $u$, which are the same everywhere and so cancel, I get $seconds^{-2}$ for both terms on the LHS, but $meters^{-2}$ on the RHS. What am I doing wrong?

A: You are missing a $c^2$ on the RHS, equation should be
$$
\color{red}{\frac{1}{c^2}}u_{tt} - \Delta u = -\frac{m^2 c^2}{\hbar^2}u
$$
Or equivalently
$$
u_{tt} - c^2\Delta u = -\frac{m^2 \color{red}{c^4}}{\hbar^2}u
$$


text:
Q: How to calculate Hazard Ratio from Kaplan Meier curve Is it possible to calculate the Hazard Ratio, Log[HR], and SE for overall survival (OS) using data from a manuscript that presents Kaplan Meier curve for OS? Usually these manuscripts present the survival of the patients in raw numbers but do not provide HR. How can I calculate it? Is there a formula or a computed system I could use? I would appreciate a detail response as I do not have great knowledge into that field.
Thank you.

A: When considering the hazard ratio, it is best to obtain this by fitting a Cox proportional hazards model.  If you do not adjust for outcome heterogeneity caused by any other variables than the grouping variable, your regression model would contain one binary predictor.  The output will be a log hazard ratio and its standard error.  You anti-log the regression coefficient to get the point estimate of the hazard ratio.
The Cox model in this situation is essentially two Kaplan-Meier estimates that borrow information from each other by assuming a common shape of the survival curves (curves are parallel on the log-log survival scale).
There is a Mantel-Haenszel-type hazard ratio estimator but I prefer the Cox model.
You need the raw data in either case.  You can approximate the statistics by using a digitization program to retrieve the points on the published curves, and re-plotting on the log-log scale and taking an average distance between them.  This estimates the Cox regression coefficient.  How to weight the distances for optimum estimation is difficult.  An approximate standard error comes from the approximate variance estimate of $\frac{4}{e}$ where $e$ is the total number of events in both groups combined.

A: Besides the already provided answer regarding methods for extracting the information from Kaplan-Meier plots, it is also possible estimate the hazard ratio and standard error/confidence interval using the number of patients with an event in combination with the total time (e.g. years) of follow-up to first event or censoring, if the hazard for an event is approximately constant in all treatment groups. This is because these numbers together constitute the sufficient statistics for an exponential time to event model. This can be fitted in just about any Poisson regression software with the number of patients with an event as the number of events and the logarithm of the follow-up as the offset.

A: If your question is still topical, I found this paper, which may help you:
Tierney, Jayne F et al. "Practical Methods for Incorporating Summary Time-to-Event Data into Meta-Analysis." Trials 8 (2007): 16. PMC. Web. 6 Oct. 2015.
http://www.ncbi.nlm.nih.gov/pmc/articles/PMC1920534/


text:
Q: Strange classification in R and Error in eval(predvars, data, env) : object [...] not found error (no typo!) I am very new to R and have spent hours trying to solve the following problems (which I sense may be interrelated). I have read other answers mainly suggesting that there may be a typo in the DRB1 column. This is definitely now the case here and I am wondering if the error is earlier on since the confusion matrix shows that everything is classified as "-" while about 20% of factors in "Response" are "+":
Call:
 randomForest(formula = Response ~ ., data = training, ntree = 21, importance = TRUE)
               Type of random forest: classification
                     Number of trees: 21
No. of variables tried at each split: 1

OOB estimate of  error rate: 20.24%
Confusion matrix:

   -     +   class.error
 - 17504 0           0
 +  4443 0           1

I am trying to use the random forest fn to predict the response variable "Response" by column DRB1:
library(randomForest)
#library(xlsx)
library(xlsx)

# load data
path <- "C:/Users/[...].xlsx" #I have only removed the path for privacy reasons
data <- read.xlsx(path, sheetIndex = 2)

# show data [FINE]
head(data)

# make some data categorical
data$DRB1=as.factor(data$DRB1)
data$Response=as.factor(data$Response)

# to check data structure [FINE]
str(data)

# define 20% testing, 80% training data set etc.
data_set_size=floor(nrow(data)*0.80)
index <- sample(1:nrow(data), size = data_set_size)

# training set up to first set of index
training <- data[index,]

# testing set up to first set of index
testing <- data[-index,]

head(testing,100)  #FINE!

# now apply random forest
rf <- randomForest(Response ~ ., data = training, ntree=21, importance=TRUE)
rf
plot(rf)

# testing$DRB1 [FINE]
str(testing)

# predict runs random forest
result <- data.frame(testing$Response, predict(rf, testing[,2], type = "response"))
result
plot(result)

Here is a scaled-down version of the information I get when running the code:
> library(randomForest)
> #library(xlsx)
> library(xlsx)
>
> # load data
> path <- "C:/Users/[...].xlsx"
> data <- read.xlsx(path, sheetIndex = 2)
>
> # show data
> head(data)
  Response  DRB1
1        - 08_01
2        - 11_01
3        - 07_01
4        - 11_01
5        - 04_04
6        - 07_01
>
> # make some data categorical
>
> data$DRB1=as.factor(data$DRB1)
> data$Response=as.factor(data$Response)
>
> # to check data structure
> str(data)
'data.frame':   27438 obs. of  2 variables:
 $ Response: Factor w/ 2 levels "-","+": 1 1 1 1 1 1 1 1 1 1 ...
 $ DRB1    : Factor w/ 47 levels "0","01_01","01_02",..: 19 26 18 26 10 18 18 19 31 18 ...
>
> # define 20% testing, 80% training data set etc.
> data_set_size=floor(nrow(data)*0.80)
> index <- sample(1:nrow(data), size = data_set_size)
>
> # training set up to first set of index
> training <- data[index,]
>
> # testing set up to first set of index
> testing <- data[-index,]
>
> head(testing,20)
    Response  DRB1
2          - 11_01
6          - 07_01
9          - 12_01
13         - 03_01
14         - 12_01
27         - 08_01
28         + 04_02
31         - 04_04
33         - 03_01
39         - 14_54
54         - 01_01
55         - 03_01
60         - 04_02
69         - 03_02
81         - 08_01
83         - 11_01
88         - 04_04
90         - 04_07
104        - 15_03
115        - 11_01
>
> # now apply random forest
> rf <- randomForest(Response ~ ., data = training, ntree=21, importance=TRUE)
> rf

Call:
 randomForest(formula = Response ~ ., data = training, ntree = 21,      importance = TRUE)
               Type of random forest: classification
                     Number of trees: 21
No. of variables tried at each split: 1

        OOB estimate of  error rate: 20.24%
Confusion matrix:
      - + class.error
- 17504 0           0
+  4443 0           1

Question 1: Why are there no + predictions?
> plot(rf)
>
> # testing$DRB1
>
> str(testing)
'data.frame':   5488 obs. of  2 variables:
 $ Response: Factor w/ 2 levels "-","+": 1 1 1 1 1 1 2 1 1 1 ...
 $ DRB1    : Factor w/ 47 levels "0","01_01","01_02",..: 26 18 31 5 31 19 8 10 5 40 ...

Question2: If DRB1 has some NA data, is this counted as a category like any other and does the randomForest take it into account as a category or ignore it?
> # predict runs random forest
> result <- data.frame(testing$Response, predict(rf, testing[,2], type = "response"))
Error in eval(predvars, data, env) : object 'DRB1' not found

Question 3: I have been trying so hard to understand this error message but cannot. Can you help me?
> result
     testing.Response predict.rf..testing...2.3...type....response..
7                   -                                              -
11                  -                                              -
13                  -                                              -
16                  -                                              -
24                  -                                              -
36                  -                                              -
56                  -                                              -
58                  -                                              -
59                  -                                              -
65                  -                                              -
72                  -                                              -
73                  -                                              -
75                  -                                              -
77                  -                                              -
87                  -                                              -
89                  -                                              -
95                  -                                              -
101                 -                                              -
108                 -                                              -
111                 +                                              -
118                 -                                              -
123                 -                                              -
124                 -                                              -
126                 -                                              -
127                 -                                              -
130                 -                                              -
143                 -                                              -
149                 -                                              -
154                 -                                              -
155                 -                                              -
167                 -                                              -
169                 -                                              -
174                 -                                              -
175                 -                                              -
177                 -                                              -
199                 -                                              -
201                 -                                              -
202                 -                                              -
213                 -                                              -
220                 -                                              -
229                 -                                              -
231                 +                                              -
256                 -                                              -
259                 -                                              -
268                 -                                              -
278                 -                                              -
281                 -                                              -
291                 -                                              -
296                 +                                              -
297                 +                                              -
298                 -                                              -
301                 +                                              -
302                 -                                              -
303                 +                                              -
[...]
 [ reached 'max' / getOption("max.print") -- omitted 2244 rows ]
> plot(result)

The result plot stays the same as from a previous simulation...
I am SUPER grateful for any help/answers to even just 1 of the 3 questions.
Thanks a lot!

A: You have only one variable DRB1 for making the prediction, so most likely random forest is an overkill.
I would check by simple plots whether there is any association between categories of DRB1 and your response, for example doing:
library(ggplot2)
library(dplyr)
data %>% group_by(DRB1) %>%
count(Response) %>%
mutate(prop=n/sum(n)) %>%
ggplot(aes(x=DRB1,y=prop,fill=Response)) + geom_col()

As for NAs.. it is no used in the model, but I don't know how applicable is this given that your data doesn't really need a ML model


text:
Q: Taming the x-axis labels of a multi-level pandas dataframe maptlotlib .plot() call I have pandas dataframe with multi-level row index composed of two datetime values.
I plot various slices of the dataframe. (they're slices of the inner level).
My problem is that the x-axis labels have too much detail. The label includes both levels of the index, and uses a format string that includes 00:00:00 time.    I only need to use the outer level (index[0].values) and I don't care about the time fragment.  I highlighted in red the parts I don't want.

What's the most-efficient way I could give a different index (that looks like what I want) to the .plot()?  Can I do it without messing with the dataframe itself?
#create the main dataframe
dt = pd.DatetimeIndex(start='2010-1-1', end = '2010-12-31', freq='m')
dt2 = pd.DatetimeIndex(start='2011-1-1', end = '2011-1-10', freq='d')
mi = pd.MultiIndex.from_product([dt,dt2], names=['assessment_date', 'contract_date'])

df = pd.DataFrame(index=mi)
df['foo']=7

df.plot(rot=50)

A: Since the ticklabels for a multiindex dataframe are anyways fixed, you may just loop over them and truncate their text to whatever you want.
trunc = lambda x: x.strip("()").split(" ")[0]
tl = [ trunc(t.get_text()) for t in ax.get_xticklabels()]
ax.set_xticklabels(tl)

Complete example:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

#create the main dataframe
dt = pd.DatetimeIndex(start='2010-1-1', end = '2010-12-31', freq='m')
dt2 = pd.DatetimeIndex(start='2011-1-1', end = '2011-1-10', freq='d')
mi = pd.MultiIndex.from_product([dt,dt2], names=['assessment_date', 'contract_date'])

df = pd.DataFrame(index=mi)
df['foo']=np.random.rand(len(df))

ax = df.plot(rot=50)

trunc = lambda x: x.strip("()").split(" ")[0]
tl = [ trunc(t.get_text()) for t in ax.get_xticklabels()]
ax.set_xticklabels(tl)

plt.show()