text:
Q: How can I return JSON data from MVC? I am currently returning JSON data like this:
return new JsonResult {
Data = from service in _serviceTable.GetAll(
 u => u.PartitionKey == "1Z0-851" &
 u.RowKey.CompareTo(lowerBound) >= 0 &
 u.RowKey.CompareTo(upperBound) < 0)
       select new {
 service.PartitionKey,
 service.RowKey,
 service.TopicDescription,
 service.SubTopicDescription,
 service.Weight,
 service.Format,
 service.Style,
 service.ShortTitle }
};

This works good but now I would like to return some data to indicate status. I tried adding this as , status in this way:
 ShortTitle },
 Status = "abc"
    };

but I get a syntax error message saying "does not contain a definition for status
Can someone hopefully explain how I could add status and send it back to my web page. Note that there are many rows from the serviceTable but just one status to send back.

A: You could do that and clean things up a bit by using a couple intermediate variables (var handily handles anonymous types):
var service = from service in _serviceTable.GetAll(
                u => u.PartitionKey == "1Z0-851" &
                u.RowKey.CompareTo(lowerBound) >= 0 &
                u.RowKey.CompareTo(upperBound) < 0)
              select new {
                service.PartitionKey,
                service.RowKey,
                service.TopicDescription,
                service.SubTopicDescription,
                service.Weight,
                service.Format,
                service.Style,
                service.ShortTitle });

var status = "abc";

var result = new {
  Service = service,
  Status = status
};

return Json(result);

A: return new JsonResult {
Data = new {Result=(from service in _serviceTable.GetAll(
 u => u.PartitionKey == "1Z0-851" &
 u.RowKey.CompareTo(lowerBound) >= 0 &
 u.RowKey.CompareTo(upperBound) < 0)
       select new {
 service.PartitionKey,
 service.RowKey,
 service.TopicDescription,
 service.SubTopicDescription,
 service.Weight,
 service.Format,
 service.Style,
 service.ShortTitle}), Status="abc"}

};

Please check the syntax, but you get the idea.
To access the data you'll have to use something like data.Result and data.Status for the status.


text:
Q: My script isn't running even if 2 colors are the exact same So basically I have a script that says if the color of a square in this array is not the same as the color on the screen (a gameObject in my game) the square should disappear. But instead all of the squares disappear even if the color is the exact same as the screen! Can some one help me with this? Thank you! This is the code that's supposed to do this:
foreach(SpriteRenderer square in squares)
        {
            if(square.color != colorScreen.GetComponent<SpriteRenderer>().color)
            {
                square.gameObject.SetActive(false);
            }
        }

A: Ok so I figured it out. For some reason when I copied all of the colors at the same time they came out tinted, making them slightly off from the colors I needed to compare them to. So I just copied and pasted the colors one by one and that seemed to work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I click OK with Apple Script? I'm trying to select OK with the popup for scaling the screen with Apple script.
Does anyone know what I can add to this script to allow me to click OK?
Apple Script:
tell application "System Preferences"
    reveal anchor "displaysDisplayTab" of pane "com.apple.preference.displays"
end tell
tell application "System Events" to tell process "System Preferences" to tell window "Built-in Retina Display"
    click radio button "Scaled" of radio group 1 of tab group 1
    click radio button 1 of radio group 1 of group 1 of tab group 1

    (* Trying to click the ok button here *)
    delay 1
    click ((pop up buttons of sheet 1 of window 1) whose description is "OK")

end tell

quit application "System Preferences"

Or also rather does anyone know a trusted application that can graphically print out the labels of the UI when I visit them on my screen so I will know what to use when I say: "tell UIName"?
Thanks.

A: Solution 1: Press Return
Since you're using System Events anyway, and the button in question is selected by default (indicated by being highlighted in blue), just make sure that the preference pane is in focus and use System Events to hit the return key:
    tell application "System Events" to keystroke return

It's quick, simple, and saves the hassle of identifying UI elements within the hierarchy.  The drawback is that the preference pane has tone in focus, and if it loses focus before it receives the keystroke, the rest of the script will fail.
Solution 2: The One You Asked For
Regarding identification of UI elements within the GUI objects hierarchy, you got the class of the button in question wrong as well as its description.
The "OK" button is referenced like so:
    tell application "System Events" to tell process "System Preferences" ¬
        to get button "OK" of sheet 1 of window "Built-in Retina Display"

(window 1 is also fine).  You can use the whose filter to target it instead, which would be done like this (via System Events and the System Preferences process):
    get buttons of sheet 1 of window 1 whose name is "OK"

but all this does is ask AppleScript to search for a button whose name we know, then annoyingly give the result back to us as a list (the list structure can be flattened by requesting the first button of sheet 1...).
However, we do know its name and that there's only one of it, so we can reference it by name directly.
As a side-bar, if you quickly run this command:
    get the properties of button "OK" of sheet 1 of window "Built-in Retina Display"

you'll be able to see that its description is merely "button", which isn't what you had hoped.  Now run this command:
    get the actions of button "OK" of sheet 1 of window "Built-in Retina Display"

which reveals it has one action available, AXPress (this is equivalent to a mouse click).
Therefore, finally, the way to click the button in a more satisfactory way than hitting the return key looks like this:
    tell application "System Events" to tell process "System Preferences" ¬
        to tell button "OK" of sheet 1 of window "Built-in Retina Display" ¬
            to perform action "AXPress"

For exploring the GUI objects on the screen, I occasionally use the Accessibility Inspector that comes with Apple's XCode.  It's vaguely useful, although inconveniently annoying with some of the discrepancies between the names by which it references objects and the names by which AppleScript does (they're also really subtle discrepancies, but enough to stop your script from working and send you into a frenzy for weeks).
So, actually, I just explore it programmatically myself in Script Editor.
What I did to solve your issue was to bring up the pane and the dialog box in question, then systematically tell the System Preferences process to get UI elements; then get buttons of UI elements; then get buttons of UI elements of UI elements, and stop when I saw a pair of buttons returned called "OK" and "Cancel".  It can be pain-staking, but it'll get you the correct reference.
There are other ways too, but I would be moving beyond the scope of this question.


text:
Q: Kotlin: iterate through array in reversed order Is there a convenient way in Kotlin to iterate through an array, let's say IntArray, in reversed order with these 2 conditions:

*

*do not create an additional reversed copy of the array.

*I need a handle to an element like in Java's enhanced for.

The best I could get is adding an extension function, but this needs to be done for each type of array if I need it not only for IntArrays:
fun IntArray.forEachReversed(action: (Int) -> Unit): Unit {
    for (i in indices.reversed()) action(this[i])
}

Is there a better way in Kotlin class library?

A:
this needs to be done for each type of array if I need it not only for IntArrays:

I think this is unavoidable because of the way the JVM works. There are separate classes to represent each primitive type on the JVM. However, there are only 8 of them, so it shouldn't be too bad ;-)
For Collections, there is the asReversed() function, but it's not available for arrays:

val original = mutableListOf('a', 'b', 'c', 'd', 'e')
val originalReadOnly = original as List<Char>
    val reversed = originalReadOnly.asReversed()

println(original) // [a, b, c, d, e]
println(reversed) // [e, d, c, b, a]

// changing the original list affects its reversed view
original.add('f')
println(original) // [a, b, c, d, e, f]
println(reversed) // [f, e, d, c, b, a]

A: To answer you question, you solution looks fine but if your are targeting primitive IntArray, LongArray, FloatArray etc you cannot come with a generic solution, as this classes are independent and only thing common is Iterator, but you cannot traverse the iterator in reverse order without making a copy(ListIterator supports reverse iteration though), but the closest you can get is to use Array<T> instead specific Array like below
 fun <T> Array<T>.forEachReversed(action: (T) -> Unit){
    for(i in indices.reversed()){  action(this[i]) }
 }

 val intArray = Array(2){ 0 }
 val longArray = Array<Long>(2){ 0 }
 intArray.forEachReversed { }
 longArray.forEachReversed {  }

A: As pointed out by @ajan.kali if you need primitive arrays there is not much you can do. I suppose you have to deal with arrays but, if this is not the case, you should prefer other data structures (more info here)
Returning to your question, if your are fine using generic arrays you could probably declare your iterator to iterate in reverse order:
class ReverseIterator<T>(val it: Iterable<T>) : Iterator<T> {
   private var index = it.count() - 1
   override fun hasNext() = index >= 0
   override fun next(): T = try { it.elementAt(index--) } catch (e:
   IndexOutOfBoundsException) { index -= 1; throw
     NoSuchElementException(e.message) }
}

then your extension function will become:
fun <T> Iterable<T>.forEachReversed(action: (T) -> Unit) {
   for(elem in ReverseIterator(this)) {
      action(elem)
   }
}

and then given an array you can invoke it this way:
intArrayOf(1, 2, 3).asIterable().forEachReversed {
  println(it)
}

Not particularly happy with this, but with arrays there is not much you can do other to try avoiding them.


text:
Q: Poles of abelian differentials Let $X$ be a smooth projective curve of genus $g$ over an algebraically closed field $k$. As a corollary of the Riemann-Roch theorem we know that for every abelian differential $\omega$ on $X$ we have
$$ \deg(\omega) = 2g - 2. $$
Now assume that $g\geq 2$, then $\deg(\omega)\geq 0$.  Does this imply that an arbitrary differential has no poles on the whole $X$?
I guess no: a priori this just means that the number of zeros (with multiplicity) is greater than the number of poles. But anyway, is it always possible to find a function $f\in k(X)$ such that the form $f \omega$ has no poles?
Any idea or clarification is welcome!

A: Yes, you can always find such a rational function $f\in k(X)$. Here is why:
Since the cotangent bundle $\Omega_X$ satisfies $\operatorname {dim} H^0(X,\Omega_X)=g\geq 2$, there certainly exists a   regular differential form $ \eta\neq 0\in H^0(X,\Omega_X)$.
As is the case for all line bundles, the quotient $\frac \eta\omega$ of two rational sections (with $ \omega\neq0$) of $\Omega_X$ is a rational function $f\in k(X)$ and we have found our desired functoion $f$ with $\eta=f\omega \in H^0(X,\Omega_X)$, a differential form with no poles.
Notice that the result is true  also for $g=1$ but  of course false for $g=0$.
[As to your first question, you can of course force any differential form to acquire a pole at any designated point  by multiplying it by a rational function having a sufficiently bad pole at that point]

A: Since $g=p_g=\dim_k \Gamma(X,\omega_X)\geq 2$, we may fix any nonzero regular abelian differential $\omega_0$. Therefore, any rational abelian differential $\omega$ is a rational section of the invertible sheaf $\omega_X$, hence $\omega$ can be represented as $\omega=f\omega_0$ for some $f\in k(X)$, so $\omega/f$ has no poles.
However, $div(\omega)=div(f)+div(\omega_0)$ is not necessarily effective (e.g. $f$ may have poles outside the zeroes of $\omega_0$), so $\omega=f\omega_0$ is not regular in general.


text:
Q: Setting Linux UID on NFS volume from EMC NX4 I have an EMC NX4 from which there are several CIFS shares with corresponding NFS mount points. The CIFS user ids seem fine but when viewed from Linux they are all 327xx numbers and can't be set from the file system. (IE CHOWN doesn't work - permission denied).
On our other (older) EMC devices we used an MMC app to set the Linux UID for each user. I don't seem to have such an app on the 'Applications and Tools' CD for this new device. Is there some other method for setting these? Did I setup the system incorrectly?

A: It sounds like the usermapper service on the datamover is not enabled or not running.   If you have powerlink access you can review this document:
PowerLink UserMapper Guide
The MMC Snap in is on the Applications CD, if you can't find it you can always download it from PowerLink also, but you'll need to open a support session via Chat to get the link.  It's not "publicly available" for some reason...


text:
Q: How to write mysql query to get JSON output? I am exporting a part of MySQL Database as JSON Format.
I want to do this from mysql-cli without using any web interfaces like phpmyadmin or softwares like mysqlworkbench.
I am aware that I can do so by using php json_encode() function after a mysql query.
But are there any methods that can be used, so that I can write a mysql query to get the dump as JSON.
I used php to do this.
json_encode($result);

A: From mysql version 5.7.8 you can use JSON_ARRAY, JSON_OBJECT to converting query output as json. Here is many more in mysql official documentation: https://dev.mysql.com/doc/refman/8.0/en/json-creation-functions.html


text:
Q: numpy calling sse2 via ctypes In brief, I am trying to call into a shared library from python, more specifically, from numpy. The shared library is implemented in C using sse2 instructions. Enabling optimisation, i.e. building the library with -O2 or –O1, I am facing strange segfaults when calling into the shared library via ctypes. Disabling optimisation (-O0), everything works out as expected, as is the case when linking the library to a c-program directly (optimised or not). Attached you find a snipped which exhibits the delineated behaviour on my system. With optimisation enabled, gdb reports a segfault in __builtin_ia32_loadupd (__P) at emmintrin.h:113. The value of __P is reported as optimised out.
test.c:
#include <emmintrin.h>
#include <complex.h>
void test(const int m, const double* x, double complex* y) {

    int i;
    __m128d _f, _x, _b;
    double complex f __attribute__( (aligned(16)) );
    double complex b __attribute__( (aligned(16)) );
    __m128d* _p;

    b = 1;
    _b = _mm_loadu_pd( (double *) &b );

    _p = (__m128d*) y;

    for(i=0; i<m; ++i) {
        f = cexp(-I*x[i]);
        _f = _mm_loadu_pd( (double *) &f );
        _x = _mm_loadu_pd( (double *) &x[i] );
        _f = _mm_shuffle_pd(_f, _f, 1);
        *_p = _mm_add_pd(*_p, _f);
        *_p = _mm_add_pd(*_p, _x);
        *_p = _mm_mul_pd(*_p,_b);
        _p++;
    }
    return;
}

Compiler flags:
gcc -o libtest.so -shared -std=c99 -msse2 -fPIC -O2 -g -lm test.c
test.py:
import numpy as np
import os

def zerovec_aligned(nr, dtype=np.float64, boundary=16):
    '''Create an aligned array of zeros.
    '''
    size = nr * np.dtype(dtype).itemsize
    tmp = np.zeros(size + boundary, dtype=np.uint8)
    address = tmp.__array_interface__['data'][0]
    offset = boundary - address % boundary
    return tmp[offset:offset + size].view(dtype=dtype)

lib = np.ctypeslib.load_library('libtest', '.' )
lib.test.restype = None
lib.test.argtypes = [np.ctypeslib.ctypes.c_int,
                     np.ctypeslib.ndpointer(np.float64, flags=('C', 'A') ),
                     np.ctypeslib.ndpointer(np.complex128, flags=('C', 'A', 'W') )]

n = 13
y = zerovec_aligned(n, dtype=np.complex128)
x = np.ones(n, dtype=np.float64)
# x = zerovec_aligned(n, dtype=np.float64)
# x[:] = 1.

lib.test(n,x,y)

Calling test from C works as expected:
call_from_c.c:
#include <stdio.h>
#include <complex.h>
#include <stdlib.h>
#include <emmintrin.h>

void test(const int m, const double* x, double complex* y);

int main() {

    int i;
    const int n = 11;
    double complex *y = (double complex*) _mm_malloc(n*sizeof(double complex), 16);
    double *x = (double *) malloc(n*sizeof(double));
    for(i=0; i<n; ++i) {
        x[i] = 1;
        y[i] = 0;
    }

    test(n, x, y);
    for(i=0; i<n; ++i)
            printf("[%f %f]\n", creal(y[i]), cimag(y[i]));

    return 1;

}

Compile and call:
gcc -std=c99 -otestc -msse2 -L. -ltest call_from_c.c
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:.
./testc
... works.
My system:

*

*Ubuntu Linux i686  2.6.31-22-generic

*Compiler: gcc (Ubuntu 4.4.1-4ubuntu9)

*Python: Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GCC 4.4.1]

*Numpy: 1.4.0

I have taken provisions (cf. python code) that y is aligned and the alignment of x should not matter (I think; explicitly aligning x does not solve the problem though).
Note also that i use _mm_loadu_pd instead of _mm_load_pd when loading b and f. For the C-only version _mm_load_pd works (as expected). However, when calling the function via ctypes using
_mm_load_pd always segfaults (independent of optimisation).
I have tried several days to sort out this issue without success ... and I am on the verge beating my monitor to death. Any input welcome.
Daniel

A: I just got bitten by this trying to call some SSE-code from python, the problem seems to be that GCC wants to assume that the stack is aligned on 16-byte boundaries (the largest native type on the architecture, i.e. the SSE-types), and calculates all offset with that assumption. When that assumption is false, the SSE-instructions will trap.
The answer seems to be to compile with gcc -mstackrealign which changes the function prologues to always align the stack to 16 bytes.

A: Try building your extension using numpy build system to discount potential cflags/ldflags differences:
http://projects.scipy.org/numpy/wiki/NumpySconsExtExamples

A: Have you try upgrading to Numpy 1.5.0b2.  Just run the following (but be careful it might break other things (you will have to recompile all pyrex):
sudo easy_install -U numpy

I was having similar problems with ctypes when I was trying to use H5PY (I had to recompile the .deb to get with the latest version of numpy) and also there was major issues with weave that the latest upgrade fixed.


text:
Q: Numerical result out of range I have a program that creates semaphore. But when i try to use SETALL, i get the error in errno as

Numerical result out of range

if((temp_semid = semget(IPC_PRIVATE, 250, 0666 | IPC_CREAT)) != -1)
{
  semun arg;
  ushort array[100];
  memset(array,0, 100);
  arg.array = array;
  if(semctl(temp_semid, 0, SETALL, arg) == -1){
   std::cout << " failed to setall semaphore" << std::endl;
   std::cout << strerror(errno) << std::endl;
    break;
  }
}

What is wrong?

A: This worked.
if((temp_semid = semget(IPC_PRIVATE, 250, 0666 | IPC_CREAT)) != -1)
{
  semun arg;
  ushort array[100] = { 0 };
  arg.array = array;
  if(semctl(temp_semid, 0, SETALL, arg) == -1){
   std::cout << " failed to setall semaphore" << std::endl;
   std::cout << strerror(errno) << std::endl;
    break;
  }
}

i was using memset in the wrong way. thanks to hmjd for pointing that out.


text:
Q: ImageNet classification challenge: Achieving top-5 error of 0.99472 on test set using VGG11 I recently took an imagenet pre-trained VGG11 network and made predictions on the imagenet test dataset. Upon submitting this file to the evaluation server, I received an email with following text:
Error: 0.99607 (top-5)  0.99898 (top-1)
Per-class error (classes 1-1000):
1 1
1 1
1 1
...

Does this mean that my top-5 accuracy is 1-0.99607=0.393%? If so then the score is too low.
Could you please point out where I could be going wrong? Here is the code for reference.
P.S.: I have checked that the images are loaded and predicted upon in alphabetical order.
vgg11 = models.vgg11(pretrained=True)
vgg11.to(torch.device("cuda"))
vgg11.eval()
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                 std=[0.229, 0.224, 0.225])

test_loader = torch.utils.data.DataLoader(datasets.ImageFolder("test_dataset",
                                                               transforms.Compose([
                                                                   transforms.Resize(256),
                                                                   transforms.CenterCrop(224),
                                                                   transforms.ToTensor(),
                                                                   normalize
                                                                   ])),
                                          batch_size=32, shuffle=False)
fp = open("predictions.txt", "w")
for a, b in tqdm(test_loader):
    preds = vgg11(a.cuda())
    _, preds = torch.topk(preds, k=5, dim=1)
    preds = preds.cpu().detach().numpy()
    for i in range(len(preds)):
        fp.write(" ".join(str(j) for j in preds[i])+"\n")
fp.close()

A: Based on your code, I believe the error is right because of the lack of normalization. I don't have the environment to test on the ImageNet test set, so I made a small example with 4 random cat images from the internet. (Link: image1, image2, image3, image4).
The code test as below:
import torch
from torchvision import models
import numpy as np
import cv2
import os

with torch.no_grad():
    vgg11 = models.vgg11(pretrained=True)
    vgg11.eval()

    mean=torch.tensor([0.485, 0.456, 0.406])
    std=torch.tensor([0.229, 0.224, 0.225])

    def read_image(image_path, size=224):
        image = cv2.imread(image_path)
        image = cv2.resize(image, (size,size))
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB).astype(np.float32)
        image = torch.tensor(image).permute(2,0,1).unsqueeze(0) / 255.
        image = (image - mean[None, :, None, None])/std[None, :, None, None]
        return image

    from_path = './../test_image/'
    cat_name = ['cat1','cat2','cat3','cat4']

    images = torch.empty(0, 3, 224, 224)

    for name in cat_name:
        image_path = os.path.join(from_path, f'{name}.png')
        image = read_image(image_path)
        images = torch.cat((images, image), 0)

    preds = vgg11(images.float()).detach().cpu().numpy()
    result = np.argmax(preds, axis=1)
    print(result)

Without normalization, the result is ['Egyptian cat', 'sock', 'Komodo dragon', 'doormat'] ([285, 806, 48, 539]).
With normalization, the result is ['tabby cat', 'tabby cat', 'leopard', 'Egyptian cat'] ([281 281 288 285]).


text:
Q: FluentBit: add dynamic es index I have a working fluent-bit:1.7
I need OUTPUT to Elasticsearch and create a dynamic index based on the k8s label = name.
I want the following convention for the index:
infra-${app_name}-yyyy.mm.dd
Example: infra-mongodb-2021.01.01, infra-postgresql-2021.01.01, infra-kafka-2021.01.01 etc...
This is my FILTER and OUTPUT config:
[FILTER]
    Name             kubernetes
    Match            kube.*
    Merge_Log        Off
    Keep_Log         Off

[OUTPUT]
    Name  es
    Match kube.*
    Host ${ES_HOST}
    Logstash_Format On
    Logstash_Prefix_Key kubernetes['labels']['name']

But it generates the following index: mongodb-2021.01.01
It's almost done, I just need to always add the infra- prefix.
Just to be clear, I need something like:
    Logstash_Prefix_Key infra-${kubernetes['labels']['name']}

A: I did this using Lua plugin to create a field in the record with the name  of the index then using this field as Logstash_Prefix_Key
Lua script (based on https://github.com/fluent/fluent-bit/blob/master/scripts/append_tag.lua):
function append_es_index(tag, timestamp, record)
    new_record = record

    if (record["cluster_name"] ~= nil) then
        es_index = record["cluster_name"]
    else
        es_index = "k8s"
    end

    if (record["kubernetes"] ~= nil) then
        kube = record["kubernetes"]
        if (kube["namespace_name"] ~= nil and string.len(kube["namespace_name"]) > 0) then
            es_index = es_index .. "." .. kube["namespace_name"]
        end

        if (kube["labels"] ~= nil) then
            labels = kube["labels"]

            if (labels["app"] ~= nil and string.len(labels["app"]) > 0) then
                es_index = es_index .. "." .. labels["app"]
            elseif (labels["k8s-app"] ~= nil and string.len(labels["k8s-app"]) > 0) then
                es_index = es_index .. "." .. labels["k8s-app"]
            elseif (labels["name"] ~= nil and string.len(labels["name"]) > 0) then
                es_index = es_index .. "." .. labels["name"]
            end
        end
    end

    new_record["es_index"] =  es_index

    return 1, timestamp, new_record
end

Fluentbit filters config:
[FILTER]
    Name                kubernetes
    ...
[FILTER]
    Name record_modifier
    Match *
    Record cluster_name my-test-cluster
[FILTER]
    Name    lua
    Match   *
    script  /fluent-bit/scripts/append_es_index.lua
    call    append_es_index

A: Another way to achieve similar result is to create a label or an annotation for your Pods
for example
[OUTPUT]
  Name                es
  Logstash_Prefix_Key kubernetes['labels']['log-key']
...

deployment yml based on docs
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
        log-key: infra-nginx # log-key label will be used in Logstash_Prefix_Key
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80

this way you will be able to combine multiple "dynamic" data for example also the namespace


text:
Q: Electric field due to a uniformly charged plane I have a plane that aligned on the $x$-$y$ plane extending from $x=-a$ to $x=+a$ and $y=-b$ to $y=+b$
and I want to find the electric field intensity at a point h along the $z$-axis.
$\sigma \equiv $ area charge density
The final answer is :
$$\vec E= \frac{\sigma}{\pi \epsilon_o} \tan^{-1}({\frac{ab}{\sqrt{a^2+b^2+h^2}}}) \hat i_z$$
but using gauss law we get a constant electric field $\vec E = \sigma/\pi \epsilon_0$
Where is the deviation here?

A: This is not an infinite plane.  Gauss' law still applies but is not useful in this case.  You cannot assume that the field is uniform. You have to integrate all the contributions from each area element. It is essential to understand the conditions for which a formula is valid.  The simple result you showed is valid for infinite plane which you don't have here.


text:
Q: intento Crear un código para determinar la frecuencia de un elemento específico
tengo una lista y necesito utilizar el input del usuario para sacarlo de la lista y imprimirlo solo. mas las veces que aparece. ejemplo (onions: 4)

def user_item(self):
    item = input('Item: ')
    file = open('InputFile.txt', 'r')
    d = dict()
    for line in file:
        line = line.strip()
        line = line.lower()
        words = line.split(" ")
        for word in words:
            if word in d:
                d[word] = d[word] + 1
            else:
                d[word] = 1
    for key in list(d.keys()):
        print(key, ":", d[key])

A: Por suerte Python tiene métodos que te facilitan ese trabajo. Solo tienes que leer el archivo de texto y convertir su contenido en una Lista y con el método count() puedes contar las veces que aparece un elemento especificado dentro de una Lista. Podrías hacer algo como esto:
item = input('Item: ').lower()
file = open('InputFile.txt', 'r')
lines = file.read().lower().splitlines()
file.close()

print(item, ":", lines.count(item))

la línea 3 hace tres cosas:

*

*read() Lee el contenido del archivo y devuelve un string.

*lower() Convierte el string en minúscula en caso que haya alguna
mayúscula.

*splitlines() divide el string en los saltos de línea y devuelve una
lista.


text:
Q: Which is efficient either before_filter or an if check using params[:action]? Which is more efficient, Case I or II?
Case I:
before_filter :validator, only: :test1
before_filter :parser, only: :test2

def test1
  <some code>
end

def test2
  <some code>
end

private

  def validator
    <condition1>
  end

  def parser
    <condition2>
  end

Case II:
before_filter :validator

def test1
  <some code>
end

def test2
  <some code>
end

private

  def validator
    if params[:action] == 'test1'
      <condition1>
    end

    if params[:action] == 'test2'
      <condition2>
    end
  end

A: Case 1 is more efficient, but not because it runs more quickly. You can benchmark them to be sure, but they almost certainly have very similar resource requirements.
The reason #1 is more efficient is because it reduces developer strain. For example, it more obviously expresses your intent. It can grow more organically, and it is much easier to write tests for. The complexity added by case 2 will negatively impact the project by making testing and long-term maintenance more difficult.


text:
Q: displaying a texarea value into another textarea value I've two input fields, both type textareas.
<input id="display" type="text" disabled="disabled" style="border: none; background: none" />
<input id="name" type="text" />

And I'm using jQuery to display the value of #name into #display. The textarea #display is used only for displaying. (It can be changed to any other suitable HTML element)
I use the jQuery code to do that:
$('#name').keyup( function() {
    $('#display').val($('#name').val());
});

The problem is, as I type, I want the value inside #display to wrap within its width. When I type long strings in #name, the string wraps and falls down as the next line but in #display it doesn't do so.
Again, when I type return, I want the same format to be followed up in the #display text field.
Can anyone tell me how do I do that??

A: You'd need a <textarea>, not an input box if you want multiline text editing:
<textarea id="display" disabled="disabled" style="border: none; background: none; resize: none;"></textarea>
<textarea id="name" style="resize: none;"></textarea>

So to make the two look identical, your code should work:
$('#name').keyup(function() {
  $('#display').val($('#name').val());
});

I added resize: none; because it prevents the textareas from resizing via the little handle on the bottom-right-hand-corner (Webkit only).

A: You could set a white-space property to #display and make it a div instead of an input
http://www.quirksmode.org/css/whitespace.html
#display {
    white-space:pre;
    white-space:pre-wrap;
    white-space:pre-line;
}

Any one of these values may be appropriate for you, see the link for reference and browser support.
I'm assuming you don't need to post the value of #display, so no need for a form element.


text:
Q: BotFramework , Not Receiving Response To First Message I'm using Microsoft BotFramework and have created one simple Bot.
Flow is something like,
User Says Hi -> Bot responds with Greeting what user can ask
User Asks relevant Question -> Bot Responds with Answer and Possible Next Question and then Again flow continues with User Asking Question
on Local Emulator everything works fine. However when I use published API App it doesn't show response to Users "Hi" , if user asks any other relevant question everything works fine.
Also on bot page it does not show any errors also so it is not error.
I also added try catch block and sent error as message that also did not show any message , again pointing towards no error.
i tried debug with ngrok and there also it complets whole block without going into catch or any unexpected path.
So I'm lost with where it can go wrong!!!
Any pointers will be useful.
Thanks,
Dilkush

A: Are you running the bot in Azure? If so, make sure you have "AlwaysOn" enabled; otherwise the web app will be unloaded if it's idle for a period of time. Check this for a similar problem.

Always On. By default, web apps are unloaded if they are idle for some period of time. This lets the system conserve resources. In Basic or Standard mode, you can enable Always On to keep the app loaded all the time. If your app runs continuous web jobs, you should enable Always On, or the web jobs may not run reliably.

You can read more about the web sites configuration here.


text:
Q: Flutter - How to remove the ability to click on a step title? Specifically the ripple effect even when stepTapped is undefined I noticed that the steps can be clicked on to navigate back. But is there a way to disable this? In the image below clicking on the name triggers a material button click.
child: Stepper(
              type: StepperType.vertical,
              physics: const ScrollPhysics(),
              currentStep: _currentStep,
              onStepTapped: null,
              controlsBuilder: ((context, details) {
                return Row(
                  children: [
                    ElevatedButton(
                      onPressed: (() => continued()),
                      child: const BrandText(
                        text: 'Continue',
                      ),
                    ),
                    if (_currentStep != 0)
                      TextButton(
                        onPressed: (() => cancel()),
                        child: const BrandText(
                          text: 'Back',
                        ),
                      ),
                  ],
                );
              }),
              steps: [
                Step(
                  title: const BrandText(text: 'Name'),
                  content: Column(
                    children: <Widget>[
                      BrandTextInput(
                          controller: _groupNameController,
                          hintText: 'Name',
                          iconName: Icons.label)
                    ],
                  ),
                  isActive: _currentStep >= 0,
                  state: _currentStep >= 0
                      ? StepState.complete
                      : StepState.disabled,
                ),

A: Make onStepTapped blank
onStepTapped: (step){},

title click effect Disabled
You need to edit the stepper.dart file.
Widget _buildVertical() {
    return ListView(
      shrinkWrap: true,
      physics: widget.physics,
      children: <Widget>[
        for (int i = 0; i < widget.steps.length; i += 1)
          Column(
            key: _keys[i],
            children: <Widget>[
              // InkWell(
              //   onTap: widget.steps[i].state != StepState.disabled ? () {
              //     // In the vertical case we need to scroll to the newly tapped
              //     // step.
              //     Scrollable.ensureVisible(
              //       _keys[i].currentContext!,
              //       curve: Curves.fastOutSlowIn,
              //       duration: kThemeAnimationDuration,
              //     );
              //
              //     widget.onStepTapped?.call(i);
              //   } : null,
              //   canRequestFocus: widget.steps[i].state != StepState.disabled,
              //   child: _buildVerticalHeader(i),
              // ),
              Container(
                child: _buildVerticalHeader(i),
              ),
              _buildVerticalBody(i),
            ],
          ),
      ],
    );
  }


text:
Q: Replace specific string using sed I have a code.txt file that contains morse code for example

.- .-.

I have a function called decode inside a bash file called morse as this:
decode (){
   sed -i 's/ \.-/A/g' $1
   sed -i 's/ \.-./R/g' $1
   cat $1
}

When I type in terminal $bash morse decode code.txt
I receive:

AA.

The output I want is :

AR

How can it see separate that the string .- is A and the .-. is R?

A: If your intention is to encode and decode Morse messages with any tool then something like this will do :
#!/usr/local/bin/python3
import re

alphabet = { 'A':'.-', 'B':'-...', 'C':'-.-.', 'D':'-..', 'E':'.', 'F':'..-.', 'G':'--.', 'H':'....', 'I':'..', 'J':'.---', 'K':'-.-', 'L':'.-..', 'M':'--', 'N':'-.', 'O':'---', 'P':'.--.', 'Q':'--.-', 'R':'.-.', 'S':'...', 'T':'-', 'U':'..-', 'V':'...-', 'W':'.--', 'X':'-..-', 'Y':'-.--', 'Z':'--..', '1':'.----', '2':'..---', '3':'...--', '4':'....-', '5':'.....', '6':'-....', '7':'--...', '8':'---..', '9':'----.', '0':'-----', ', ':'--..--', '.':'.-.-.-', '?':'..--..', '/':'-..-.', '-':'-....-', '(':'-.--.', ')':'-.--.-',' ':'  '}

def encode(message):
    return "".join([ ( alphabet[letter.upper()] + ' ' ) if letter != ' ' else '  ' for letter in message])

def decode(message):
    return "".join([ list(alphabet.keys())[list(alphabet.values()).index(item if item != '|' else '  ')] for item in re.sub(r' {2,}', ' | ',message).split(' ')])

print(encode('THIS IS FINE'))
print(decode('- .... .. ...   .. ...   ..-. .. -. .'))

Hope it helps too.

A: Wow interesting idea! Based on @MatiasBarrios alphabet i made this.
#!/bin/bash

string=$1

declare -A morse=(
    [A]='.-'    [B]='-...'  [C]='-.-.'  [D]='-..'   [E]='.'
    [F]='..-.'  [G]='--.'   [H]='....'  [I]='..'    [J]='.---'
    [K]='-.-'   [L]='.-..'  [M]='--'    [N]='-.'    [O]='---'
    [P]='.--.'  [Q]='--.-'  [R]='.-.'   [S]='...'   [T]='-'
    [U]='..-'   [V]='...-'  [W]='.--'   [X]='-..-'  [Y]='-.--'
    [Z]='--..'

    [1]='.----'  [2]='..---'  [3]='...--'  [4]='....-'  [5]='.....'
    [6]='-....'  [7]='--...'  [8]='---..'  [9]='----.'  [0]='-----'
    [(]='-.--.'  [)]='-.--.-' [/]='-..-.'  [-]='-....-' [+]='.-.-.'
    [.]='.-.-.-' [,]='--..--' [?]='..--..' [!]='-.-.--' [ ]='  '
)

morse () {
    while [[ "$string" ]]; do
        symbol="${string::1}"
        printf -- "${morse["${symbol^}"]} "
        string="${string:1}"
    done
}

demorse () {
    declare -A demorse
    for item in "${!morse[@]}"; { demorse["${morse["$item"]}"]="$item"; }
    while [[ $@ ]]; do
        printf -- "${demorse["$1"],}"
        shift
    done
}

case $string in
    demorse) shift; demorse "$@";;
    *      )          morse     ;;
esac

Usage
$ ./morse 'hello world!'
.... . .-.. .-.. ---    .-- --- .-. .-.. -.. -.-.--

Demorse also worsk but, spaces have to be printed like this '  '
$ ./morse demorse .... . .-.. .-.. --- '  ' .-- --- .-. .-.. -.. -.-.--
hello world!

A: You need to run s/ \.-\./R/g replacement first. Note the second . must be escaped to only match a dot.
Hence, use
sed 's/ \.-\./R/g;s/ \.-/A/g' file

See the online demo
Or, another way:
sed -e 's/ \.-\./R/g' -e 's/ \.-/A/g' file

Replace the file with "$1" in your code.
UPDATE
Here is the translation of encoding / decoding Python function posted by Matias below:
#!/bin/bash

### Encoding:

declare -A MORSE=( [A]='.-' [B]='-...' [C]='-.-.' [D]='-..' [E]='.' [F]='..-.' [G]='--.' [H]='....' [I]='..' [J]='.---' [K]='-.-' [L]='.-..' [M]='--' [N]='-.' [O]='---' [P]='.--.' [Q]='--.-' [R]='.-.' [S]='...' [T]='-' [U]='..-' [V]='...-' [W]='.--' [X]='-..-' [Y]='-.--' [Z]='--..' [1]='.----' [2]='..---' [3]='...--' [4]='....-' [5]='.....' [6]='-....' [7]='--...' [8]='---..' [9]='----.' [0]='-----' [',']='--..--' ['.']='.-.-.-' [';']='-.-.-.' [':']='---...' ['?']='..--..' ['!']='-.-.--' ['/']='-..-.' ['-']='-....-' ['+']='.-.-.' ['(']='-.--.' [')']='-.--.-' ['_']='..--.-' ['"']='.-..-.' ["'"]='.----.' ['$']='...-..-' ['@']='.--.-.' ['&']='.-...' ['  ']=' '  )

function encode {
  res=''
  s="$1"
  for (( i=0; i<${#s}; i++ )); do
    letter="${s:$i:1}"
    if [[ "$letter" == ' ' ]]; then
      res="${res}  "
    else
      res="${res}${MORSE[${letter^^}]} ";
    fi
  done
  printf "%s" "$res"
}

echo "$(encode "THIS IS FINE")"

### Now, decoding

declare -A MORSEDEC=( ['-.--.-']=')' ['..--..']='?' ['--..--']=', ' ['-....-']='-' ['.-.-.-']='.' ['...--']='3' ['-.--.']='(' ['---..']='8' ['-..-.']='/' ['....-']='4' ['-....']='6' ['----.']='9' ['.----']='1' ['..---']='2' ['.....']='5' ['--...']='7' ['-----']='0' ['-...']='B' ['-..-']='X' ['-.-.']='C' ['--..']='Z' ['--.-']='Q' ['.-..']='L' ['-.--']='Y' ['..-.']='F' ['.--.']='P' ['.---']='J' ['...-']='V' ['....']='H' ['-..']='D' ['---']='O' ['..-']='U' ['...']='S' ['.--']='W' ['-.-']='K' ['.-.']='R' ['--.']='G' ['-.']='N' ['..']='I' ['--']='M' ['.-']='A' ['  ']=' ' ['.']='E' ['-']='T' )

function decode {
  res=''
  tmp="$(sed 's/ \{2,\}/ | /g' <<< "$1")";
  for word in $tmp; do
    if [[ "$word" == '|' ]]; then
      res="${res}${MORSEDEC['  ']}";
    else
      res="${res}${MORSEDEC[$word]}";
    fi
  done
  printf "%s" "$res"
}
echo "$(decode "- .... .. ...   .. ...   ..-. .. -. .")"

See Bash demo online.

A: The easy answer in RE engines that support look-ahead and look-behind would be to treat the spaces as look-ahead and look-behind triggers, but sed does not support this.
Another option that avoids needing to order the letters is to inject extra symbols to help you mark each letter. Say we inject = round each space, then we can replace delimited sequences in any order, and finally get rid of the delimiters:
echo  .- .-.|sed -e 's/^\(.*\)$/=\1=/;s/ /= =/g' -e 's/=\.-\.=/=R=/g;s/=\.-=/=A=/g' -e 's/= =//g;s/^=//;s/=$//'

If you have rules that need to preserve multiple spaces, then that can be accommodated.


text:
Q: Логическая задача на python с применением if,else,while right_ans = "Куплю."
wrong_ans1 = "Не хочу!"
a1 = "Все так говорят!"
wrong_ans2 = "Зачем?"
a2 = "Все хотят знать!"
a3 = "Хороший ответ!"
congrat = "Ура! С полезной покупкой!"
s = input("Купишь мне слона?")
if s == right_ans:
    print(congrat)
else:
    if s == wrong_ans1:
        print(a1)
    else:

Дальше тупняк,я не понимаю почему не работает код после условного оператора else.
Помогите пожалуйста решить!

A: guess = ''

while guess != 'Куплю':
    #Python будет входить в блок инструкции while до тех пор, пока пользователь не ответит "Куплю".
    guess = input('Купишь мне слона? ')

    if guess == 'Куплю':
        print('Ура! С полезной покупкой!')
    elif guess == 'Не хочу!':
        print('Все так говорят!\n')
    elif guess == 'Зачем?':
        print('Все хотят знать!\n')
    else:
        print('Хороший ответ.\n')

Вывод:
Купишь мне слона? Нет.
Хороший ответ.
Купишь мне слона? Не хочу!
Все так говорят!
Купишь мне слона? Зачем?
Все хотят знать!
Купишь мне слона? Куплю
Ура! С полезной покупкой!

A: Вот так:
right_ans = "Куплю."
wrong_ans1 = "Не хочу!"
wrong_ans2 = "Зачем?"

a1 = "Все так говорят!"
a2 = "Все хотят знать!"
a3 = "Хороший ответ!"

congrat = "Ура! С полезной покупкой!"

s = input("Купишь мне слона?")
while s!=right_ans:
    if s==wrong_ans1: print(a1)
    elif s==wrong_ans2: print(a2)
    else: print(a3)
    s = input("Купишь мне слона?")
print(congrat)


text:
Q: How to use "regular expression" in Google Analytics as "contains"? I want to set a goal in Google Analytics which "triggers" when someone visits a page that contains this part of the url, it's in the middle of url structure:
&naytasivu=3&tapaus=verkkokauppatilaus&tapaus2=tilausok&saitti=ahtihuvila&vaihe=4&tnro=
How do I use regular expression?

A: In this particular case you can use the whole string &naytasivu=3&tapaus=verkkokauppatilaus&tapaus2=tilausok&saitti=ahtihuvila&vaihe=4&tnro= as a regular expression since it doesn't contain any of the special characters from the GA regexp implementation.
In general, the easiest way to test your regular expressions is simply to open up the page report (Behaviour -> Site Content -> All Pages), paste your regex there, see which pages come up, and tweak your regex until you obtain the desired result.
To validate your goal setup your can click the "verify your goal" link inside your goal config and see if the reported conversion rate makes sense (bear in mind that the data can lag up to 48 hours behind, although in practice it's usually ~24 hours).
What usually causes problems in GA with regex is the ? in URLs which you must escape as \? (once again your example doesn't have it so you're fine), and again please refer to the list of special characters to know what to escape


text:
Q: point of inflection for discontinuous function I have a doubt on graph of $f(x) = \frac{x-5}{x+6}$.
Is there a point of inflection on $x=-6$?
The graph changes it nature from concave up to concave down but $f''(x)$ is not equal to zero anywhere.

A: There won't be any point of inflection as at x = -6 the function is undefined.


text:
Q: Menu creation and the ANR crash with LibGDX Some users on my app are experiencing ANR crashes at start up as UI thread-max-pause time is manufacture set it's crucial to avoid UI thread blocking events.
My problem is this and I'm not sure how to fix it:
OpenGL requires that you need to load textures on the UI thread.
Now I'm loading textures using a async class at the start and loading them in, this works fine my problem is my UI engine creates all the screens at the start and an entire map of the world with each country (takes 1.7ish seconds on Nexus 5, a lot longer on slower devices).
The following requires OpenGL context:
sprite = SpriteLoader.getInstance().getSprite(textureName);
//and in getSprite
return new Sprite(this.assetManagerInternal.get(textureName, Texture.class));

So I have to create all my menus using the UI thread
Gdx.app.postRunnable(new Runnable()

As each screen:
PopupManager.getInstance().createPopupViews();
//Somehow tell Android/Application were still alive.
TraitController.getInstance().createTraitViews();

Problem is this blocks the UI thread and sometimes (but not always on the same device) causes an ANR crash.
I can't think of any ideas to get around this. I've tried running it in another thread then posting each sprite to the UI thread but this causes lots of issues with thread synchronisation.
The ideal solution which I can't find would be to notify the Android process that my application is still running after each screen, does this exist?


text:
Q: Access Code of another virtual directory Suppose I have two virtual directories under one application and I want to access functions and methods of another virtual directory in one directory. Is this possible and if yes then How ?

A: using web-service or Http handler or WCF.
What do you mean by virtual directory.
Does it mean a hosted application.
If yes then above is the solution.
Otherwise If you know the physical path of the application
You can also use reflection to execute the method inside any dll


text:
Q: Ruby Rubocop. MutableConstant - not detecting freeze I wrote a lib/animal.rb with several lists of params, and I want to reference that list in my controller and add it my params list. I did this because I use this list in several locations and didn't want to litter my code with a bunch of references to the library.
Controller
ANIMAL_TYPE_INPUT_PARAMS = *Animals::ANIMAL_TYPE_PARAMS.freeze

....

def familar_params
  params.permit(ANIMAL_TYPE_INPUT_PARAMS, OTHER_PARAM_LIST....)
end

Lib/animal.rb
module Animal

  # param lists
  ANIMAL_TYPE_PARAMS = [
    :animal_has_fur, :animal_id, :animal_weight
  ].freeze
end

Functionally it works just fine, but I am seeing a weird rubocop error. I would prefer to not disable MutableConstant for this section (disabling rubocop is usually a band aid that you pay for at some point).
Rubocop error
app/controllers/api/v1/example_controller.rb:55:24: C: Freeze mutable objects assigned to constants.
  ANIMAL_TYPE_INPUT_PARAMS = *Animals::ANIMAL_TYPE_PARAMS.freeze
                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

I looked into this question: Ruby rubocop: how to freeze an array constant generated with splat But mine are already arrays, so I feel like it doesn't apply to me / shouldn't have to call to_a.

A: As @drenmi suggested, it was an older version of rubocop giving me this error. Once I upgraded to 0.46.0 the error was no longer.


text:
Q: Plug-in display 3d-objects from VRML or X3D I'm not sure that such plug-ins exist.. But my program displays the data that are easily convertible to VRML or X3D file, so it would be very convenient if I could display rendered by these files figures directly in the window of the program. Anyone can suggest any plugin for Java or any solution to automate this?

A: If your program generates or reads 3D mesh data (triangles) and is able to create a String object containing a well defined X3D document representing these 3D objects then the Java 3D(TM) API and the XModelImporter API might provide a solution for you.
XModelImporter provides Java 3D importers for "Extensible 3D (X3D)" files. In this case the 'com.interactivemesh.j3d.interchange.ext3d.XModelReader' seems to be the appropriate importer, alternatively 'com.interactivemesh.j3d.interchange.ext3d.XModelLoader'.
The XModelReader imports X3D files by accepting different sources like 'java.io.File' and 'java.net.URL' for external data, but also 'java.io.Reader' which should be applicable for internal stored data, too.
Following not tested scenario might work:

*

*write the X3D document into a StringBuilder object

*create the corresponding String object (StringBuilder.toString)

*create a java.io.StringReader instance with this X3D string

*create a XModelReader instance and import the X3D data by calling XModelReader.read(java.io.Reader reader)

*calling XModelReader.getImport() returns an array of 'javax.media.j3d.Node' which can be rendered with Java 3D

Java 3D https://java3d.java.net/binary-builds.html
XModelReader http://www.java.net/node/706300
I'm not aware of any "currently supported" ready to go VRML or X3D players for Swing or JavaFX. Instead of converting meshes to and back from VRML or X3D you might consider choosing one of the 3D APIs for the Java platform and convert your data directly into the related format.
August

A: Xj3D is maybe the simplest solution. See http://www.xj3d.org/tutorials/xj3d_application.html or, better, http://www.xj3d.org/tutorials/general_sai.html.
At the firs sight Xj3D appears rather difficult to use, but it is not. If you need more help I could send you a little NetBeans project. Ask for more help on this forum and I will try to help you.

A: A revised and maintained version of the Xj3D library can be found at:

*

*NPS branch of Xj3D
https://savage.nps.edu/Savage/developers.html#Xj3D


text:
Q: How to add php values to a function in a wordpress dashboard widget? I am working on a plugin for wordpress - and I am pretty new at this - but I am trying to make dashboard widgets that display feeds from different sources (CNN, The Onion, MOZ, etc.) I have the plugin set up with a custom options pages I got from https://jeremyhixon.com/tool/wordpress-option-page-generator/ and everything seems to work right. My question is - how do I take the values from the options page and add them to my widget code. Here are the specific options:
Feed Label
Feed URL
Number of Articles
    /*
 * Retrieve this value with:
 * $dashboard_feeds_options = get_option( 'dashboard_feeds_option_name' ); // Array of All Options
 * $feed_label_0 = $dashboard_feeds_options['feed_label_0']; // Feed Label
 * $feed_url_1 = $dashboard_feeds_options['feed_url_1']; // Feed URL
 * $number_of_articles_2 = $dashboard_feeds_options['number_of_articles_2']; // Number of Articles
 */

Here is an example of my widget code with The Onion as a feed source
/** START The Onion Dashboard */

add_action( 'wp_dashboard_setup', 'onion_dashboard_add_widgets' );
function onion_dashboard_add_widgets() {
    wp_add_dashboard_widget( 'dw_dashboard_widget_onion', __( 'The Onion', 'dw' ), 'dw_dashboard_widget_onion_handler' );
}

function dw_dashboard_widget_onion_handler() {
    $feeds = array(
        array(
            'url'          => 'https://www.theonion.com/rss',
            'items'        =>15,
            'show_summary' => 1,
            'show_author'  => 0,
            'show_date'    => 1,

        ),

    );

    ob_start(); // start output buffering
    wp_dashboard_primary_output( 'dw_dashboard_widget_onion', $feeds );
    $buffer = ob_get_clean(); // get the buffer without printing the content

    // add the target attribute to the a-tag:
    $result = str_replace("<a class='rsswidget'",
                          "<a class='rsswidget' target='_blank'", $buffer);
    echo $result;
};

/** END The Onion Dashboard */

To sum it up - how do I take the values entered in the options page into this code to make it easy for someone to add multiple dashboard widgets to their site? As always - thank you in advance for helping me figure this out!

A: I would useget_option, you can find more on it here: https://developer.wordpress.org/reference/functions/get_option/.  The basic idea would be something like this:
// from your plugin

$example_option_value = get_option('example_option_key');

// do something with $example_option_value


text:
Q: What does using right/left/up/down key and option/command key together mean? Using right/left/up/down keys with Fn key can do the same as page down / page up / home / end on a PC.
Some mentioned about using right/left/up/down keys with either option or command key in http://www.apple.com/shop/question/answers/mac/how-can-i-make-the-home-and-end-keys-on-the-apple-extended-keyboard-work-as-line-commands-rather-than-page-commands/Q7HY7K2UFDTUK7J7C .
What do they mean under OS X?
Thanks.

A: ⌘+← or → jumps to the left/right end of the current line
⌘+↑ or ↓ jumps to the top/bottom of the current page
⌥+← or → jumps to the left/right adjacent word
⌥+↑ or ↓ jumps to the start/end of the paragraph
(all terms are respective)


text:
Q: WCF NetTcpBinding security I have a WCF service which uses NetTcpBinding with message security and username authentication. Before that I was using WsHttpBinding but I switched to NetTcp because I could use callbacks.
My service config looks like this:
<service behaviorConfiguration="WcfServiceLibrary1.ServiceBehavior" name="WcfServiceLibrary1.Service">

    <endpoint
            address="net.tcp://localhost:9000/Design_Time_Addresses/WcfServiceLibrary1/Service/"
            binding="netTcpBinding"
            bindingConfiguration="NetTCPbinding"
            contract="WcfServiceLibrary1.IService"
            name="NetTCPBinding">
    </endpoint>
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:8732/Design_Time_Addresses/WcfServiceLibrary1/Service/" />
      </baseAddresses>
    </host>
  </service>
</services>
<bindings>
  <netTcpBinding>
    <binding name="NetTCPbinding">
      <security mode="Message">
        <message clientCredentialType="UserName"/>
      </security>
    </binding>
  </netTcpBinding>
</bindings>
<behaviors>
  <serviceBehaviors>
    <behavior name="WcfServiceLibrary1.ServiceBehavior">
      <serviceCredentials>
        <serviceCertificate findValue="ServerCert"
                            storeLocation="CurrentUser"
                            storeName="TrustedPeople"
                            x509FindType="FindBySubjectName" />
        <userNameAuthentication
          userNamePasswordValidationMode="MembershipProvider"
          membershipProviderName="CustomMembershipProvider" />
      </serviceCredentials>
      <!-- To avoid disclosing metadata information,
      set the value below to false and remove the metadata endpoint above before deployment -->
      <serviceMetadata httpGetEnabled="True" />
      <!-- To receive exception details in faults for debugging purposes,
      set the value below to true.  Set to false before deployment
      to avoid disclosing exception information -->
      <serviceDebug includeExceptionDetailInFaults="true" />
      <serviceAuthorization principalPermissionMode="UseAspNetRoles" roleProviderName="MyRoleProvider" />
      <!-- Logs when an authentication failure -->
      <serviceSecurityAudit auditLogLocation="Application"
                            suppressAuditFailure="true"
                            serviceAuthorizationAuditLevel="Failure"
                            messageAuthenticationAuditLevel="SuccessOrFailure" />
    </behavior>
  </serviceBehaviors>
</behaviors>

I assume the service credentials -in this case the certificate- are used so that the service can sign all the data that it sends to the client, so the client can know that it is communicating with the correct service.
The client config is the following:
<behaviors>
  <endpointBehaviors>
    <behavior name="messageSecurityBehavior">
      <clientCredentials>
        <clientCertificate storeLocation="CurrentUser"
                           storeName="TrustedPeople"
                           x509FindType="FindBySubjectName"
                           findValue="ClientCert" />
        <serviceCertificate>
          <authentication certificateValidationMode="None" />
        </serviceCertificate>
      </clientCredentials>
    </behavior>
  </endpointBehaviors>
</behaviors>
<bindings>
  <netTcpBinding>
    <binding name="NetTCPBinding" closeTimeout="00:01:00" openTimeout="00:01:00"
                receiveTimeout="00:10:00" sendTimeout="00:01:00" transactionFlow="false"
                transferMode="Buffered" transactionProtocol="OleTransactions"
                hostNameComparisonMode="StrongWildcard" listenBacklog="10"
                maxBufferPoolSize="524288" maxBufferSize="65536" maxConnections="10"
                maxReceivedMessageSize="65536">
      <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
          maxBytesPerRead="4096" maxNameTableCharCount="16384" />
      <reliableSession ordered="true" inactivityTimeout="00:10:00"
          enabled="false" />
      <security mode="Message">
        <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
        <message clientCredentialType="UserName" />
      </security>
    </binding>
  </netTcpBinding>

</bindings>
<client>
  <endpoint address="net.tcp://localhost:9000/Design_Time_Addresses/WcfServiceLibrary1/Service/"
            binding="netTcpBinding" bindingConfiguration="NetTCPBinding"
            contract="IService" name="NetTCPBinding" behaviorConfiguration="messageSecurityBehavior">
    <identity>
      <certificate encodedValue="AwAAAAEAAAAUAAAAQerRMlEg2a66HMxD/8El6LutassgAAAAAQAAAOwBAAAwggHoMIIBVaADAgECAhAzOWVhNWUzM2Y5MzUwNzFhMAkGBSsOAwIdBQAwIjELMAkGA1UEBhMCVVMxEzARBgNVBAMTClNlcnZlckNlcnQwHhcNMTIwMTE3MTk1NDQ2WhcNMjUwOTI1MTk1NDQ2WjAiMQswCQYDVQQGEwJVUzETMBEGA1UEAxMKU2VydmVyQ2VydDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAs6SaYi3pDDIOuXeCe7HgOOTvOpwajKdxM8MzZpkK3l+DqkriMQUx9DT5I9WZvNK5FMuorLueG5adWkTgWpvttC7Sp8CJ//A+PbPewiAU4L3Txln6dX3jHZFd99LY/58/2AzY8ln2NykQFzz1DdmVeyShG9ktVsX82Ogz60lzpeUCAwEAAaMnMCUwEwYDVR0lBAwwCgYIKwYBBQUHAwEwDgYDVR0PBAcDBQD6AAAAMAkGBSsOAwIdBQADgYEAMGQ7fIW34CYjybCc0gWOLaxeRFiNHmX/dgxqPIWGgg3uc0avz1GHJ3uMHcPAZBKcw9QpbccALpqZxZzkDBxufWjRni+8XCzeAKUqaB7XaJTYYUYBbz7/2+EuaAw7/vF4JTtZGWhPkHZZcX5+Oyo2ktK0z24MfXP2Ggy+IsQJ2JM=" />
    </identity>
  </endpoint>
</client>

All of this works fine. I've read that the service certificate is used to encrypt the client credentials and the messages. Then why do we need the algorithm specified in AlgorithmSuite? What does it encrypt?
I need to understand this well so I can explain it in my thesis.

A: The certificate leads to the key that's used for encryption of the message (I'm not sure if it's directly used as a key itself, or used to negotiate a key). The AlgorithmSuite determines the algorithm, which will use that key to encrypt the message.

Why do you need to specify an algorithm?
Because you need to tell WCF how it should encrypt your message. The used algorithm is also identified in the SOAP message, because the receiving party has to know what algorithm to use to decrypt the message. Note that if you don't set an algorithm explicitly, it will still have a value, default Basic256 for NetTcp (source).
If you enable message tracing, you'd see something along these lines in the SOAP body for the appropriate (encrypted) action for your service operation:
<e:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc" />

If you would change the AlgorithmSuite to Basic128 the above would show aes128-cbc in the latter bit of the Algorithm attribute.
In the message trace, right before the action corresponding to your service operation, there will be several actions in the http://schemas.xmlsoap.org/ws/2005/02/trust/... range to negotiate all the security options. On the Message Security in WCF MSDN page you can see that WCF uses the WS-Security specification. For more information on this spec you could go to this page where I found the WS-Security 2004 spec (pdf). This may be also be useful if you need official references for your thesis.
What does it encrypt?
The algorithm encrypts both the credentials and the message (using the key that was obtained with help from the certificate), just like you already stated :-). You can see this if you enable message tracing: both the credentials and the message body will be encrypted with the selected algorithm.

Disclaimer: I'm still somewhere in the slope of the WCF learning curve, so if your thesis grade depends on this you'd better double check my claims :D


text:
Q: find specific vocab and extract row of csv and transform in new csv file I have 30,000 rows list of csv files and I want to search through these rows and columns after finding specific words write that row in new csv files.
for example:
job ,position , email , adress

joe  ,validi ,  ceo  ,  joevalidi@yahoo.com

I want to know who are ceo then extract it and save it in different csvfiles.

A: say this is your input file test.txt located at /Users/redwing/temp/
/Users/cat/meow/meoew
/Users/cat/meow/meoew2
/Users/dog/bow/wow

then this script would output a file containing only the lines that contain cat.
in_fname = '/Users/redwing/temp/test.txt'
out_fname = '/Users/redwing/temp/test_output.txt'

f_out = open(out_fname, 'w+')
f_in = open(in_fname, 'r')
for content in f_in:
    if 'cat' in content:
        f_out.write(content)
f_in.close()
f_out.close()

nice thing about this solution is that all of the file is never read into memory, so it does not matter if you filter 3000 or 30 million rows.
PS. Submitted my response before your edit. Obviously you need just to replace cat with a ceo )

A: You can try this: use re module
import re

pattern = re.compile(r'ceo')
ceo_list = []

with open('managers.csv', 'r') as f:  ## where managers.csv is the file you shared above
    for i in f:
        if pattern.search(i):
            ceo_list.append(i.split(',')[0].strip())

Now, you have all ceo's stored in the list ceo_list. Just write it into a separate file:
with open('ceo.csv', 'w') as f:
    for item in ceo_list:
        f.write("%s\n" % item)

Let me know if this helps.


text:
Q: Копирование файлов на множество серверов Сейчас у меня 20 серверов + 1 главный. С главного я с помощью scp скидываю файлы на все другие.
Как автоматизировать процесс, чтобы один файл можно было залить на свой список серверов?

Сейчас я делаю так:
$ scp package.rpm user@server2:/tmp/

и так с 20 серверами.

A: с ключами
я бы рекомендовал воспользоваться возможностью авторизации по ключу.

*

*сгенерируйте себе пару публичный/секретный ключ:
$ ssh-keygen

на все вопросы можно ответить «утвердительно» (нажать enter).
если ключ уже существует — ничего страшного не произойдёт, программа сообщит об этом и предложит перезаписать файлы (от чего можно отказаться, нажав n и enter).

*скопируйте публичную часть ключа на все нужные серверы:
$ ssh-copy-id user@host

*установите программу parallel-scp (в debian-основных дистрибутивах она обычно входит в состав пакета pssh и переименована из оригинального имени pscp для избежания конфликта имён с программой из пакета putty-tools, имеющей совсем иную функциональность).

*копируйте файл:
$ parallel-scp -H user1@host1 -H user2@host2 /локальный/файл /путь/на/удалённой/машине
[1] 18:40:23 [SUCCESS] user2@host2
[2] 18:40:24 [SUCCESS] user1@host1

/путь/на/удалённой/машине должен быть абсолютным, а путь к локальному файлу — не обязательно (может быть относительным).
опций -H user@host может быть произвольное (разумное) количество.
более того — имеет смысл вместо них указывать опцию -h /путь/к/списку, где /путь/к/списку — файл, содержащий строки формата [user@]host[:port] (в некоторых реализациях — host[:port] [user], уточните в справке к вашей версии: man parallel-scp).
если нет возможности установить упомянутую программу, воспользуйтесь советом из ответа @sercxjo.
без ключей
если по какой-то причине вы не можете/хотите пользоваться доступом по ключу, то, чтобы не вводить пароль на запрос программы ssh/scp, можете воспользоваться, например, программой sshpass (обычно — из одноимённого пакета):
$ sshpass -p 'пароль' scp параметры-программы-scp
$ sshpass -p 'пароль' ssh параметры-программы-ssh

модифицировать соответствующим образом скрипт, предложенный @sercxjo, я думаю, труда не составит.

полезная информация: Одновременное управление несколькими серверами

A: Настройте ssh-авторизацию по ключу.
Пример скрипта для параллельной закачки, если user и пути закачки на всех серверах одинаковые ($1 - первый аргумент при запуске скрипта):
#!/bin/bash
serverlist=server1 server2 server3
for server in $serverlist ; do
    scp "$1" user@$server:/tmp/ &
done
wait

A: Вот, смотрю, пока конкретной помощи нет, набросал что-то (вроде работающее) на коленке:
#!/bin/bash

echo Test scp-expect
User=avp
PASS=XXXXXX
RDIR=/tmp
FILE=$1
if [ "X$FILE" == "X" ]; then
    echo usage: ./tscp FILE
    exit 1
fi

echo Go...

#rm ~/.ssh/known_hosts  вместо этого -o 'UserKnownHostsFile /dev/null' в вызове scp

for HOST in nas
do
    expect -c "
spawn scp -o UserKnownHostsFile\\ /dev/null $FILE $User@$HOST:$RDIR
expect \".*no)? \"
send \"yes\r\"
expect \".*assword:\"
send \"$PASS\r\"
expect eof
"
done

В данном случае один файл пересылается на один хост (с именем nas) в оглавление /tmp.
Обратите внимание, для упрощения скрипта expect я делаю недоступной всю локальную информацию ssh о хостах (по умолчанию она находится в ~/.ssh/known_hosts), поскольку при запуске неизвестно, на данный хост уже заходили ssh/scp или еще нет (и тогда scp требует ввода "yes").
Ну, думаю, как тут работает expect в принципе ясно, а шелловскую обвязку (что, откуда, куда, где брать пароль и т.п.) Вы сами под свою задачу напишите.

A: Всяк сверчок хвалит свой шесток. Я буду хвалить Ansible. Он использует обычное SSH-соединение с теми же настройками, которые используются при обычном ssh hostname
Предположим, что вы уже настроили доступ по SSH-ключам.
Перечисляем хосты в файле hosts (имя произвольное). Можно и параметром задавать, но предполагаю, что список хостов у вас более-менее постоянный.
host1.dc1
host2.dc1
# все номера с 1 по 10
host[1:10].dc2

В любом месте запускаем команду.
ansible all -i path/to/hosts -m copy -a 'src=path/to/example.txt dest=/tmp/example.txt'

И всё, файлы копируются, а вы получаете отчёт по каждому хосту:
example.host | SUCCESS => {
    "changed": true,
    "checksum": "c3499c2729730a7f807efb8676a92dcb6f8a3f8f",
    "dest": "/tmp/example.txt",
    "gid": 1002,
    "group": "root",
    "md5sum": "1a79a4d60de6718e8e5b326e338ae533",
    "mode": "0664",
    "owner": "root",
    "size": 7,
    "src": "/home/username/.ansible/tmp/ansible-tmp-1467312219.54-140783443033936/source",
    "state": "file",
    "uid": 1002
}

Дополнительные параметры здесь: http://docs.ansible.com/ansible/copy_module.html
Если не настроили SSH-ключи, то к строке запуска добавим:
-u <имя-пользователя> --ask-pass

Тогда соединение будет устанавливаться по указанному имени пользователя, пароль будет запрошен в командной строке.

A: Вопрос синхронизации между хостами не решается в одну строчку. Опишу общие принцыпы, так как конкретная настройка будет обширна в описании.
Было несколько путей, которые я испробовал на хостах (3.000+): писать скрипты в ручную, создовать демонов синхронизации, использовать готовые решения.
Для отпраки использовал протоколы ssh, http[s] и torrent, последий позволяет создать свою отказоустойчивую сеть передачии контента.
От простого к запутанному
У вас локальная сеть, без каких либо ограничений. Хосты и сервер на Linux. Можно поднять веб сервер.  с lsftp для раздачи файлов. Связка pxe+apache+lsftp отлично отрабатывает свою задачу уже два года. Цеклично запустить. на каждом
~$ wget file_server:/file

в этом варианте вообще не нужны ключи для хостов и пароли для ftp, достаточно иметь удаленный доступ к кажому. Парадигма pull
У вас разрозненные хосты, доступ к которым идет через общую сеть (intrnet, WAN, MAN или VPN).  В наличие ssh сервер-клиент на каждом из хостов и основном сервере. В этом варианте выгодней по скорости использовать rsync и expect если нет RSA ключей то на сервере пишем небольшой скрипт на expect
#!/usr/bin/env bash

hosts="$1"
send_file="$2"

for host in "$hosts"; do
    expect -c "
         spawn rsync -az --append \"$send_file\" \"$host\"
         expect \".assword.+\"
         send \"my_password\r\"
    " &
done

с ключамии в одну строчку
~# while read -r host; do rsync -az --append /path/to/file "$host" & done < hosts

Интересный момент - это отсылать каждую "раздачу" в фоновый процесс &.
Вы хотите синхронизировать тысячи и болелее хостов или узлов кластера. Тут уже скриптами не справишся из готовых и бесплатных решений можно отметить:

*

*Ansible - модули copy и synchronize. ssh протокол

*Lsyncd (Live Syncing Daemon) синхронизирует локальные директории с удаленными хостами. Обертка rsync демонизированная на Lua

*Resilio решение для распределенной доставки файлов.

*glusterfs расспределеная файловая система

*libtorrent открытая библиотека на c++  смотрите приложения использующие ее в качестве базовой, на оффициальном сайте.


text:
Q: Which USB distributions may fit as notebook/development/demonstration platforms? I want to build a (very) nomad work platform and I don't want it to be on the cloud but on a USB drive. (I know I will have to create backups and/or disk images to make it USB disk failure proof.)
I am very fond of Dokuwiki on a stick as a portable notebook: it's a Dokuwiki install with a micro-Apache server, and it lets me have my research notes and papers and work on it everywere.
But I would also like to work on my LaTeX papers, on my IPython notebooks, and why not embed my IPython notebooks in my dokuwiki pages. I would then have (nearly) everything I need to work properly and make demos anywhere without bothering with configurations. And even make several USB images for several contexts.
I am then looking for a lightweight live distribution where I can easily install this environment. I know Debian more than other distributions but I'm ready to try any good alternative.

A: I've been using Puppy Linux for this. (Precise Puppy)
It is very USB stick friendly:

*

*It loads your save file to RAM on boot.

*It saves your data at an interval (I set it to 30 minutes) and on shutdown to your USB stick.

*Additions are partially done via layered file systems.

This reduces the writes to your USB stick, so that it lasts longer.


text:
Q: Why does $\frac{\sum X_i^2}{n} \rightarrow \sigma^2+\mu^2$? I cannot find a reference to the proof of this, but I found
$$\frac{\sum X_i^2}{n} \rightarrow \sigma^2+\mu^2$$
From: https://math.stackexchange.com/a/1416911/248602
So why does it converge to that?

A: I presume you're already happy to accept that -- in the limit as $n\to\infty$ -- $\bar{Y} \to E(Y)$ (as long as $E(Y)$ is finite.
Now let $Y_i=X_i^2$. Then clearly also (in the limit) $\overline{X^2}\to E(X^2)$ (again, as long as the expectation of $Y$ is finite).
But $\text{Var}(X) = E(X^2) - E(X)^2$ so $E(X^2) =  \sigma_X^2 + \mu_X^2$.
Hence by the strong law of large numbers, $\lim_{n\to\infty}
\overline{X^2}\to \sigma_X^2 + \mu_X^2$.


text:
Q: NetBeans - "no Axis2 url specified" when I click on test operation in browser I'm writing a simple web service using Axis2 and NetBeans 8.0, my (very simple) code looks like this:

and my configuration of Axis2 in Tools panel (I'm using oracle weblogic 10.3.6) is this:

but when I click on "test operation in browser" I have this error:

even if it seems to be ok. What I'm doing wrong?


text:
Q: Why Do I See No Output With Git Log But I Do See This With Git Diff? Team,
I type: git log branchA..branchB -- /dir1/dir2
When typing this "git log" command nothing is output. However, when I type this "git diff" command many files are output.
git diff branchA..branchB -- /dir1/dir2
Does anyone know why there is this extreme difference? I have read the documentation but this does not give me an obvious answer unfortunately and i have to venture onto the open seas of the Internet.
Seems like if there is output with the "git diff" command then this means files were changed between the branches (branchA and branchB). If there are changes between these branches as evidenced by the "git diff" command then there should be something, anything, in the "git log" command.
Why does the "git log" command not return anything but the "git diff" command does return a lot of output on file and code changes?

A: TL;DR
First, check whether there are any commits in the branchA..branchB range, using git rev-list for instance (add --count if you don't want to see the raw hash IDs).  Then, if there are commits, consider adding --full-history and maybe -m to your git log command.
Long
There is a lot to unpack here.  (There might be a lot less if you pointed to a specific repository and two specific branch names within that one specific repository.)
First, git log and git diff are pretty different beasts.  But it is worth noting that git log can run git diff, more or less; git diff cannot run git log.  Nonetheless, git diff can do things git log can't do.  Second, the two-dot notation has multiple different meanings.  What it means to git log is very different from what it means to git diff.  In one sense, it doesn't mean anything at all to git diff as you can always replace:
git diff X..Y

with:
git diff X Y

That is, the two dots here merely serve to separate X from Y, which you could also do just by giving them as separate arguments.  That's not true for git log, though.  That makes git diff quite a bit simpler, so let's start with the git diff.
Diffing two commits
You have run (in effect anyway):
git diff branchA branchB -- /file1/file2

This form of git diff, given two commit-specifiers and a path,1 has the effect of checking out each of the two specific commits and comparing them.  Without the path limiter, you'd get complete instructions on what set of operations would change the first commit into the second one: add files A and B, delete files C and D, modify files E through H, etc.  Using the path specifier /file1/file22 eliminates from the output any instructions that affect files whose name does not start with (or equal) this string.  (The leading slash here is just relative to the top level of your repository.)

1Some Git commands take pathspec arguments.  The git log and git diff commands do not.  If you don't use complicated stuff, there's nothing to worry about here.  If you start using :/: or :(glob) and other tricky pathspec options, just note that they're not available here.
2Note that your OS probably demands that file1/file2 name either a file named file2 within a directory / folder file1, or a directory / folder named file2 within one named file1.  To Git, these are just strings—there's no "folder-ness" involved.  Still, it's probably better to say /dir1/dir2 here.

Using git log
There is a lot to know about git log; let's start with the two-dot notation.  In this case your two items are branchA and branchB.  Git will—at least with git log, and also with many other commands but not git diff—first treat this as selecting all commits reachable from the tip of branchB, minus any and all commits reachable from the tip of branchA.  This uses the phrase reachable from, which deserves an entire web tutorial: Think Like (a) Git.  (Go read it!)
As knittl notes in a comment, this list can be empty, even if the two names designate different commits.  In this case, git log will print nothing, as we'll see.  To find the list of hash IDs—without seeing anything else—use git rev-list:
git rev-list branchA..branchB

The rev-list command is a major Git work-horse that a lot of Git's commands use, either by running it, or by having it built in to themselves.  For instance, all of cherry-pick, revert, rebase, log, shortlog, and push use git rev-list internally.  A git fetch also uses it, but runs the rev-list command on the other Git, rather than on yours.
In any case, git log now has, in effect, a list of commits to walk.  It's not at all obvious how many commits are in this list.  If the list had just one commit in it, your git log and git diff would do the same thing—produce the same output—so we may safely assume that the list has either no commits in it, or at least two commits in it.  If it's empty, but the commits are different, your output is already explained.
If not, things get more complicated, but it's likely that the list of commits has at least one merge commit in it.  If we assume that it does have at least one merge in it, that also gets us an explanation.  What Git will now do is walk the list of commits, in some order—and if you hadn't added -- /file1/file2 it would now do something simple to explain:

*

*Find a commit that is to be walked (internally, these actually come off a priority queue, as part of this build-a-list-and-simultaneously-walk-it).

*

*Find its parent.  If this commit is a merge, find all parents.  This is really part of the rev-list action: git log and git rev-list are built from a single source and share most of their code, and rev-list and log both walk the commit graph using this shared walking-code.

*Print the log message from the commit, plus any leading stuff like the commit hash, based on the --pretty format chosen.

*If the commit is not a merge, run git diff between the (single) parent and the commit itself, and show that output too.  If the commit is a merge, show nothing.

*Put the parent(s) on the queue of commits to walk, and go back to the top.

So you'd see a git diff for every non-merge commit in the list that git log / git rev-list find by enumerating "commits reachable from branchB minus commits reachable from branchA".
Now, you would think that adding -- /file1/file2 would affect each of these diffs so that you see only those changed files ... and that's true.  But it does more that that: it turns on History Simplification.
With History Simplification turned on, git log (and git rev-list) deliberately cut off parts of the reachability graph.  In particular, at any merge, Git goes through an elaborate computation of what the documentation calls TREESAME.  This computation amounts to stripping each commit down to just those files within the list of files and/or directories you specified on the command line, and comparing the contents of each such file.
When one "leg" of a merge is TREESAME on all files, after this stripping of other files, and the other isn't TREESAME, Git discards the not-TREESAME leg, including all the commits that are reachable through that leg of the merge.  If the merge is an octopus merge, and at least one parent has the TREESAME-after-stripping property, Git picks one at more or less random and follows that one, discarding all the other legs.  (If all legs are different, Git follows all legs.)
Then, since the merge commit is a merge commit, git log, by default, prints nothing.  Even if git log weren't skipping diff-listings for this,3 it has probably just picked some TREESAME parent, so that the diff listing would be empty anyway.  That's what TREESAME implies: after stripping away all the files you didn't select, the remaining ones were the same from the merge commit to its chosen parent.
Having chosen the TREESAME parent, Git continues down this track.  If branchA identifies some commit that's in the discarded leg, you can—I think—now see why the output from this git log might be empty: there may well be no changes to the selected files in any commits from here on back to wherever branchA rejoins with commits reachable from the tip of branchB.
If it is in fact History Simplification that has discarded the interesting commits, adding --full-history to your git log command will show you the commits you wanted to see.  Of course, it's possible that any changes you were looking for were introduced by an "evil merge", so you might also need the -m option, which forces git log to show a full diff between a merge commit and each of its parents.

3You can tell git log to print diff listings at merges, using either -c, --cc, or -m, each of which has a different effect.


text:
Q: Bacula Backups Failing with Duplicate Primary Key Error All of my Bacula backups started failing over the weekend with the following MySQL error:

Fatal error: sql_create.c:XXX Fill File table Query failed: INSERT
  INTO File (FileIndex, JobId, PathId, FilenameId, LStat, MD5)SELECT
  batch.FileIndex, batch.JobId, Path.PathId,
  Filename.FilenameId,batch.LStat, batch.MD5 FROM batch JOIN Path ON
  (batch.Path = Path.Path) JOIN Filename ON (batch.Name =
  Filename.Name): ERR=Duplicate entry '375086058' for key 'PRIMARY'

It was fairly sudden: it seems to have happened between 3.05am and 3.11am this morning with no other hints as to what happen.
A quick look at the database agrees that 375086058 is the highest numbered FileId field (which is the Primary Index for the File Table), but I don't know what to do to fix it without corrupting my Bacula database.
Any ideas?

A: I looked at the status of the table and verified that the Fileid field was an autoincrement and that it was stuck at 375086058, which is the number that it now says is duplicate. I got this info with the following two commands:
mysql> describe File;
mysql> show table status where name='File';

To resolve this problem, I updated the auto_increment to the *next( number:
mysql> ALTER TABLE File AUTO_INCREMENT=375086059;

This took about 10 minutes due to the size of the table. It seems to have fixed the problem.


text:
Q: Multiple replace characters in array I have:
$content = file_get_contents('data.html');
preg_match_all('/<span class="ng-binding">.*?<\/span>/is', $content, $matches);
print_r(array_values(array_unique($matches[0])));

Array
(
    [0] => 3 January 2018 - Month - Month of Circumstances
    [1] => 2 February 2018 - Month - A New Advancement
    [2] => 1 March 2018 - Month - The Threat
    [3] => 31 April 2018 - Month - Month of Prediction
    [4] => 30 May 2018 - Month - Seven Days
)

How can I remove and replace characters so the end array would be something like...
Content.2017.S01E01.Month.of.Circumstances.HOTSTAR.mp4
Content.2017.S01E01.A.New.Advancement.HOTSTAR.mp4
Content.2017.S01E01.The.Threat.HOTSTAR.mp4
Content.2017.S01E01.Month.of.Prediction.HOTSTAR.mp4
Content.2017.S01E01.Seven.Days.HOTSTAR.mp4

A: You could either do 2 preg_replace calls or use preg_replace_callback and preg_replace. A regex such as .*-\s*(.*) will give everything until the last - then \s* will allow any additional whitespace characters. Then you have the part you care about in the first capture group. With that capture group you then can replace all non alphanumerical characters.
$array = array('3 January 2018 - Month - Month of Circumstances',
                '2 February 2018 - Month - A New Advancement',
                '1 March 2018 - Month - The Threat',
                '31 April 2018 - Month - Month of Prediction',
                '30 May 2018 - Month - Seven Days');
foreach($array as $item) {
    echo preg_replace_callback('/.*-\s*(.*)/', function($match){
        return 'Content.2017.S01E01.' . preg_replace('/\W+/', '.', $match[1]) . '.HOTSTAR.mp4';
    }, $item) . PHP_EOL;
}

Note \w includes underscores so if that is a special character you also want replaced use a character class including the underscore in place of the \W. This should do it [\W_] (with the quantifier).

A: You can just use preg_replace with array values for pattern and replacement. Patterns are replaced in the order of the elements in the array. So the first replace in this code replaces spaces with a . and the second replace adds the leading and trailing text to the extracted name.
$array = array('3 January 2018 - Month - Month of Circumstances',
                '2 February 2018 - Month - A New Advancement',
                '1 March 2018 - Month - The Threat',
                '31 April 2018 - Month - Month of Prediction',
                '30 May 2018 - Month - Seven Days');
$new_array = array();
foreach ($array as $line) {
    $new_array[] = preg_replace(array('/\s+/', '/^.*?-([\w.]+)$/'),
                                array('.', 'Content.2017.S01E01$1.HOTSTAR.mp4'),
                                $line);
}
print_r($new_array);

Output:
Array
(
    [0] => Content.2017.S01E01.Month.of.Circumstances.HOTSTAR.mp4
    [1] => Content.2017.S01E01.A.New.Advancement.HOTSTAR.mp4
    [2] => Content.2017.S01E01.The.Threat.HOTSTAR.mp4
    [3] => Content.2017.S01E01.Month.of.Prediction.HOTSTAR.mp4
    [4] => Content.2017.S01E01.Seven.Days.HOTSTAR.mp4
)


text:
Q: Bootstarp 5 - Fullscreen modal relative to parent BootStrap 5
I'm using this layout:

          ...

The main is the main content area ( scrollable ).
I'm trying to use a full-screen modal inside main, but instead of it being relative to the viewport it should be relative to it's immediate parent (i.e main).
.modal uses position:fixed which won't let this happen. So I did this:

       ...

But to no avail. It made it look messy. Is there a cleaner way to achieve what I'm trying to achieve.

A: I don't really think the following code will be cleaner than your solution but just in case here it is.
The idea it to create a stacking context, this way Position: fixed will not be relative to the viewport. A few properties create a stacking context (transform, … and probably some more).
In other words transform: translateX(0) on your div.main element will make your div.modal behave like it has a position: absolute.
EDIT: For more information about properties creating stacking context : Which CSS properties create a stacking context?


text:
Q: running a python script on cloud shell and saving ouput into cloud sql I want to run a python script which takes input around 350 images and the output which is generated has more than 700 million rows so it takes a lot of time to process. That's why i wanted to run the script on google cloud shell and save the output in the form of cloud sql database. I want to know how i can modify and run the script on shell so that it takes input from bucket and save the output into database. Any help is appreciated
import cv2
import numpy as np
import sqlite3
from skimage import data
from skimage import filters
from skimage import exposure
from skimage.color import rgb2gray
import matplotlib.pyplot as plt
import glob
import csv

ksize=31
filters1=[]
def build_filters():
    for theta in np.arange(0, (np.pi* 0.75), np.pi/4):
        for lamda in np.arange(0, np.pi, np.pi/8):
            kernel= cv2.getGaborKernel((ksize, ksize), 0.8, theta, lamda, 0.8, 0, cv2.CV_32F )
            kernel= kernel / (1.5* kernel.sum())
            filters1.append(kernel)
    return filters1

def process_img(img, filters):

    accum=np.zeros_like(img)
    for kernel in filters1:
        filtered= cv2.filter2D(img, cv2.CV_8UC3, kernel)
        np.maximum(accum, filtered, accum)
    return accum

filters1=build_filters()

conn = sqlite3.connect('train.db')
c = conn.cursor()

def create_table():
     c.execute("CREATE TABLE IF NOT EXISTS features(intensity REAL,red REAL,green REAL,blue REAL,yellow REAL,Orientation REAL,foreground REAL)")
create_table()

def dynamic_data_entry(I,R,G,B,Y,O,fore):
    intensity       = float(I)
    red             = float(R)
    green           = float(G)
    blue            = float(B)
    yellow          = float(Y)
    Orientation     = float(O)
    foreground      = int(fore)

    c.execute("INSERT INTO features (intensity,red,green,blue,yellow,Orientation,foreground) VALUES(?, ?, ?, ?, ?, ?, ?)",
                                (intensity,red,green,blue,yellow,Orientation,foreground))

    conn.commit()

for file in  glob.glob('c:/Users/shafee/Downloads/image dataset/1080p/*.jpg'):
           img = cv2.imread(file)
           img = cv2.resize(img,(192,108))
           r=img[:,:,2]
           g=img[:,:,1]
           b=img[:,:,0]
           img1=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
           val=filters.threshold_otsu(img1)
           foreground=img1<val

           R=r- (g + b)/2
           I=(r + g + b)/3
           G= g - ( r + b)/2
           B= b - (r + g)/2
           Y =(r + g)/2 -abs(r - g)/2 - b
           O= process_img(img1, filters1)
           I1=I.reshape(-1,1); I1 = np.divide(I1,255)
           R1=R.reshape(-1,1); R1 = np.divide(R1,255)
           G1=G.reshape(-1,1); G1 = np.divide(G1,255)
           B1=B.reshape(-1,1); B1 = np.divide(B1,255)
           Y1=Y.reshape(-1,1); Y1 = np.divide(Y1,255)
           O1=O.reshape(-1,1); O1 = np.divide(O1,255)
           fore1=foreground.reshape(-1,1)

           for i in range(20736):
               dynamic_data_entry(I1[i], R1[i], G1[i], B1[i], Y1[i], O1[i], int(fore1[i]==True))

    c.close
    conn.close()

A: First, you will need to use Cloud Storage Client Library for Python. To read from an existing bucket, you'll need to set up authentication and then you can use the client library. Example code is provided in the link above.
The second step is Connecting to Cloud SQL from external application (like your script) to write data to your database. The code samples are also provided here.


text:
Q: Reading excel file in python with pandas and multiple indices I am a python newbie so please excuse this basic question.
My .xlsx File looks like this
Unnamend:1    A     Unnamend:2    B
2015-01-01    10    2015-01-01    10
2015-01-02    20    2015-01-01    20
2015-01-03    30    NaT           NaN

When I read it in Python using pandas.read_excel(...) pandas automatically uses the first column as the time index.
Is there a one-liner that tells pandas to notice, that every second column is a time index belonging to the time series right next to it?
The desired output would look like this:
date          A     B
2015-01-01    10    10
2015-01-02    20    20
2015-01-03    30    NaN

A: In order to parse chunks of adjacent columns and align on their respective datetime indexes, you can do the following:
Starting with df:
Int64Index: 3 entries, 0 to 2
Data columns (total 4 columns):
Unnamed: 0    3 non-null datetime64[ns]
A             3 non-null int64
Unnamed: 1    2 non-null datetime64[ns]
B             2 non-null float64
dtypes: datetime64[ns](2), float64(1), int64(1)

You could iterate over chunks of 2 columns and merge on index like so:
def chunks(l, n):
    """ Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i + n]

merged = df.loc[:, list(df)[:2]].set_index(list(df)[0])
for cols in chunks(list(df)[2:], 2):
    merged = merged.merge(df.loc[:, cols].set_index(cols[0]).dropna(), left_index=True, right_index=True, how='outer')

to get:
             A   B
2015-01-01  10  10
2015-01-01  10  20
2015-01-02  20 NaN
2015-01-03  30 NaN

pd.concat unfortunately doesn't work as it can't handle duplicate index entries, otherwise one could use a list comprehension:
pd.concat([df.loc[:, cols].set_index(cols[0]) for cols in chunks(list(df), 2)], axis=1)

A: I use xlrd for import the data, after i use pandas to display
import xlrd
import pandas as pd
workbook = xlrd.open_workbook(xls_name)
workbook = xlrd.open_workbook(xls_name, encoding_override="cp1252")
worksheet = workbook.sheet_by_index(0)
first_row = [] # The row where we stock the name of the column
for col in range(worksheet.ncols):
    first_row.append( worksheet.cell_value(0,col) )
data =[]
for row in range(10, worksheet.nrows):
    elm = {}
    for col in range(worksheet.ncols):
          elm[first_row[col]]=worksheet.cell_value(row,col)
    data.append(elm)

first_column=second_column=third_column=[]
for elm in data :
    first_column.append(elm(first_row[0]))
    second_column.append(elm(first_row[1]))
    third_column.append(elm(first_row[2]))

dict1={}
dict1[first_row[0]]=first_column
dict1[first_row[1]]=second_column
dict1[first_row[2]]=third_column
res=pd.DataFrame(dict1, columns=['column1', 'column2', 'column3'])
print res


text:
Q: MongoDB - How to access nested array and object then $sum I have a document with an array that contains a list of objects, and each object has an array. I need to get the total points per team that are stored in the inner array (points).
It should return an output of:

*

*8 total points for Team  1

*10 total points for Team 2

*12 total points for Team 3

This is the document.
[{
  "_id": {
    "$oid": "0123456789"
  },
  "teams": [
    {
      "team": "Team 1",
      "captain": "Ryan",
      "points": [2, 2, 2, 2]
    },
    {
      "team": "Team 2",
      "captain": "Josh",
      "points": [2, 2, 3, 3]
    },
    {
      "team": "Team 3",
      "captain": "Amiel",
      "points": [3, 3, 3, 3]
    }]
}]

I have something along this line but it is incorrect.
db.users.aggregate([
  {
    $match: {
      _id: "0123456789"
    }
  },
  {
    $project: {
      _id: 1,
      points: {
        $sum: "$teams.points"
      }
    }
  }
])

A: Assume that you are trying to add a new field: totalPoints to each document in the teams array.

*

*$set - Set teams array field.
1.1. $map - Iterate each element in the teams array and return a new array.
1.1.1. $mergeObjects - Merge current iterated document in the teams array with the result of 1.1.1.1.
1.1.1.1. A document with totalPoints field with the value of the total sum of points array.
db.user.aggregate([
  {
    $match: {
      _id: "0123456789"
    }
  },
  {
    $project: {
      _id: 1,
      teams: {
        $map: {
          input: "$teams",
          in: {
            $mergeObjects: [
              "$$this",
              {
                totalPoints: {
                  $sum: "$$this.points"
                }
              }
            ]
          }
        }
      }
    }
  }
])

Demo @ Mongo Playground


text:
Q: Logs not forwarded (but fluentd container running) I have a fluentd container that after a week of working regularly, it stops forwarding logs to elasticsearch.
If a 'docker logs' that container it shows me all logs, but after a certain date/time these are not forwarded.
Fluentd config is this:
</source>
 @type      forward
 @label     @mainstream
 bind       0.0.0.0
 port       24224
</source>

<label @mainstream>
 <match **>
   @type copy    <store>
     @type               elasticsearch
     host                elasticsearch
     port                9200
     logstash_format     true
     logstash_prefix     fluentd
     logstash_dateformat %Y%m%d
     include_tag_key     true
     type_name           access_log
     tag_key             @log_name
     <buffer>
       flush_mode        interval
       flush_interval    1s
     </buffer>
   </store>  </match>
</label>

Do you have any suggestions to find the root of this problem?
Thank you in advance.


text:
Q: Error Can not convert char** to const char** I have following code:-
static char* ListOfStr[] = { "str1", "str2", "str3" };
void Foo(const char** listOfStr)
{
// do something
}

When I call Foo like;
Foo(ListOfStr);

I get Error Can not convert char** to const char** (C2664 - vc++)
I know how to solve the problem using casting or other way around like defining const array at first place.
But isn't it safe to use char** as const char** than why it gives error ?
I supposed there should be auto convertion like std::string to const std::string when passing to function. Only the reverse of this cont char** to char** must give the Error without cast.

A: The issue is covered in the C++ FAQ, thanks to Steve Summit: https://isocpp.org/wiki/faq/const-correctness#constptrptr-conversion
I have looked at it for 10 minutes and still don't fully understand it, but the problem is apparently that you could create non-const aliases and thus modify  an originally const object if this were allowed.


text:
Q: Js Regex exact pattern I want to write function which exactly tell me that expression suit to regular expression.
eg.
<script>
var pattern = /[0-9]{2}/

alert(pattern.test("1236"));

</script>

This expression is true, but I want false because I want only two numbers
eg.
alert(pattern.test("25"));

Only this should be true.
How can I change my code?

A: Use:
var pattern = /^[0-9]{2}$/

It says now:
Two digits from start "^" to the end "$"


text:
Q: Ordinal inequality - simple question We are given 2 ordinals: $\alpha$ and $\beta$ where $\beta$ does not have a maximal number (So it's transfinite, right?)
We are asked to find $\alpha,\beta$ such that:
$\alpha+\beta > \beta+\alpha$
My problem is, that I don't think such a solution exists when alpha is a finite ordinal (lets say that $\beta=\omega$). if it is, then $\alpha+\beta = \{0,1,2,...,\alpha-1,0^*,1^*,2^*,...\} = \omega$
and $\beta+\alpha = \{0,1,2,...,0^*,1^*,2^*,...(\alpha-1)^*\} > \omega$
So I think $\alpha$ also has to be a transfinite ordinals. But I can't for the life of me think of such an ordinal that this will be true.

A: HINT: Think of a case where $\beta+\alpha=\alpha$. For example when $\alpha$ is much bigger than $\beta$.
(Also, ordinal is without a maximum if and only if it is not a successor ordinal, which means either zero or a limit ordinal - which has to be infinite.)


text:
Q: htaccess redirection not working on parameters We're looking to migrate our site from a really bad hosted ecommerce platform to WordPress.
1/2 of our URL redirects are solid as a rock in htaccess using typical 301 redirects. The current ecommerce site has some strange url parameters:
http://thisisthedomain.com/Item_Details?m8:item=1

This is essentially the same thing for about 300+ URLs, with only the numerical after the item= changing.
We've tried the following separately:
redirect 301 /Item_Details?m8:item=0110 http://finaldomain.com/
redirect 301 /Item_Details%3Fm8%3Aitem%3D0110 http://finaldomain.com/
RewriteRule /Item_Details?m8:item=0110 http://finaldomain.com/ [R=301,L]
RewriteRule ^Item_Details%3Fm8%3Aitem%3D0110$ http://finaldomain.com/ [R=301,L]

None of them work. Any help would be great.

A: You can't match against the query string in the pattern of a RewriteRule or in a Redirect/RedirectMatch. You need to use a RewriteCond and the %{QUERY_STRING} variable:
RewriteCond %{QUERY_STRING} ^m8:item=
RewriteRule ^Item_Details$ http://finaldomain.com/ [L,R=301]