text:
Q: matplotlib: removing patches from plot I am using matplotlib to interactively plot some patches and points.
I receive the data from a separate process via a queue and send them to my plot-process. That part of the code works fine and points are shown on the graph and continuously updated in the plot as expected.
Upon request from the user I would like to remove all the old patches in the plot and replace with new ones.
I thought it would be enough to perform:
# remove the old patch
patch.remove()
# I also tried ax.cla() without any success
# create a new patch
monitor_box = path.Path([(305, 500), (11, -213), (300, -220), (500, 1734)])
patch = patches.PathPatch(monitor_box, facecolor='black', lw=1)
# add the patch to the axis
ax.add_patch(patch)

and then during the next iteration, the plot should be updated with new patch:
canvas.draw()

but when I use the above code, the patch still remains in the window and nothing changes. (I am still getting the points in the plot so that is at-least still being continuously updated)
Below I have provided a minimal working example of the issue. When you run the code, you can see that different points get plotted but the patches are never removed.
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
import multiprocessing
from Tkinter import *
import matplotlib.path as path
import matplotlib.patches as patches
import sys, thread, time

from random import randint

#Create a window
window=Tk()

sendProximityInfo = True
latest_published_msg = ""

def erasePatchesAndCreateNew_A():
    print "erasePatchesAndCreateNew_A"
    global line, ax, canvas
    global monitor_box
    global patch
    patch.remove()
    ax.cla()
    monitor_box = path.Path([(35, 1677), (11, -213), (652, -220), (500, 1734)])
    patch = patches.PathPatch(monitor_box, facecolor='black', lw=1)

    ax.add_patch(patch)

def erasePatchesAndCreateNew_B():
    print "erasePatchesAndCreateNew_B"
    global line, ax, canvas
    global monitor_box
    global patch
    patch.remove()
    ax.cla()
    monitor_box = path.Path([(35, 500), (11, -213), (300, -220), (500, 1734)])
    patch = patches.PathPatch(monitor_box, facecolor='red', lw=1)

    ax.add_patch(patch)

monitor_box = path.Path([(35, 1677), (111, -213), (62, -220), (800, 1734)])
fig = matplotlib.figure.Figure()
ax  = fig.add_subplot(1,1,1)
ax.set_xlim(-1500,2000)
ax.set_ylim(-1500,2000)
patch = patches.PathPatch(monitor_box, facecolor='black', lw=1)
ax.add_patch(patch)

def main():
    erasePatchesAndCreateNew_B()

    #Create a queue to share data between process
    q = multiprocessing.Queue()
    #Create and start the simulation process
    simulate = multiprocessing.Process(None, simulation,args=(q,))
    simulate.start()
    #Create the base plot
    plot()
    #Call a function to update the plot when there is new data
    updateplot(q)

    window.mainloop()
    print 'Done'
    simulate.join() # wait for the other process to finish as well

def plot():    #Function to create the base plot, make sure to make global the lines, axes, canvas and any part that you would want to update later
    global line, ax, canvas
    global monitor_box
    global patch

    fig = matplotlib.figure.Figure()
    ax  = fig.add_subplot(1,1,1)
    ax.set_xlim(-1500,2000)
    ax.set_ylim(-1500,2000)

    patch = patches.PathPatch(monitor_box, facecolor='black', lw=1)
    ax.add_patch(patch)

    ax.invert_yaxis()
    canvas = FigureCanvasTkAgg(fig, master=window)
    canvas.show()
    canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
    canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)
    line, = ax.plot([], [], 'ro')

def updateplot(q):
    try:       #Try to check if there is data in the queue
        result = q.get_nowait()

        if result != 'Q':
            x, y = result
            line.set_data(x, y)
            ax.draw_artist(line)
            canvas.draw()
            window.after(1,updateplot,q)
        else:
            print 'done'
    except:
        window.after(1,updateplot,q)

def simulation(q):
    try:
        while True:
            for i in range(10):
                q.put( (randint(0,1500), randint(0,1500)) )
                time.sleep(1)
            erasePatchesAndCreateNew_A()
            time.sleep(1)
            for i in range(10):
                q.put( (randint(0,1500), randint(0,1500)) )
                time.sleep(1)
            erasePatchesAndCreateNew_B()
            time.sleep(1)
    except KeyboardInterrupt:
        print "received KeyboardInterrupt"
    finally:
        print "simulation ended"
        sys.exit()

if __name__ == '__main__':
    main()

Below is a screenshot from the program, the red dot moves around in the graph but the patch (black shape) never changes.

A: I managed to solve this issue, or to be exact I figured out a around for this issue. I am adding it below and maybe it will help someone else in the future.
I am basically using the queue to communicate when the graph should be updated in the main thread.
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
import multiprocessing
from Tkinter import *
import matplotlib.path as path
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import sys, thread, time

from random import randint

#Create a window
window=Tk()

sendProximityInfo = True
latest_published_msg = ""

monitor_box = path.Path([(1000, -1000), (111, -213), (62, -220), (800, 1734)])
fig = matplotlib.figure.Figure()
ax  = fig.add_subplot(1,1,1)
ax.set_xlim(-1500,2000)
ax.set_ylim(-1500,2000)
patch = patches.PathPatch(monitor_box, facecolor='black', lw=1)
ax.add_patch(patch)

def main():
    #Create a queue to share data between process
    q = multiprocessing.Queue()
    #Create and start the simulation process
    simulate = multiprocessing.Process(target=simulation,args=(q,))
    simulate.start()
    #Create the base plot
    plot()
    #Call a function to update the plot when there is new data
    updateplot(q)

    window.mainloop()
    print 'Done'
    simulate.join() # wait for the other process to finish as well

def plot():    #Function to create the base plot, make sure to make global the lines, axes, canvas and any part that you would want to update later
    global line, ax, canvas, fig, monitor_box, patch
    patch.remove()
    monitor_box = path.Path([(500, -500), (111, -213), (62, -220), (800, 1734)])
    patch = patches.PathPatch(monitor_box, facecolor='pink', lw=1)
    ax.add_patch(patch)

    canvas = FigureCanvasTkAgg(fig, master=window)
    canvas.show()
    canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
    canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)
    line, = ax.plot([], [], 'ro')

def erasePatchesAndCreateNew_A():
    print "erasePatchesAndCreateNew_A"
    global ax, monitor_box, patch
    patch.remove()
    monitor_box = path.Path([(35, 1677), (11, -213), (652, -220), (500, 1734)])
    patch = patches.PathPatch(monitor_box, facecolor='red', lw=1)
    ax.add_patch(patch)

def erasePatchesAndCreateNew_B():
    print "erasePatchesAndCreateNew_B"
    global ax, monitor_box, patch
    patch.remove()
    monitor_box = path.Path([(-2000, 2000), (11, -213), (300, -220), (500, 1734)])
    patch = patches.PathPatch(monitor_box, facecolor='blue', lw=1)
    ax.add_patch(patch)

def updateplot(q):
    try:       #Try to check if there is data in the queue
        result = q.get_nowait()

        if result != 'A' and result != 'B':
            x, y = result
            line.set_data(x, y)
            ax.draw_artist(line)
            canvas.draw()
            window.after(10,updateplot,q)
        elif result == 'A':
            erasePatchesAndCreateNew_A()
            canvas.draw()
            window.after(10,updateplot,q)
        elif result == 'B':
            erasePatchesAndCreateNew_B()
            canvas.draw()
            window.after(10,updateplot,q)
    except:
        window.after(10,updateplot,q)

def simulation(q):
    try:
        while True:
            for i in range(5):
                q.put( (randint(0,1500), randint(0,1500)) )
                time.sleep(0.5)
            #erasePatchesAndCreateNew_A()
            q.put('A')
            time.sleep(1)
            for i in range(5):
                q.put( (randint(0,1500), randint(0,1500)) )
                time.sleep(0.5)
            #erasePatchesAndCreateNew_B()
            q.put('B')
            time.sleep(1)
    except KeyboardInterrupt:
        print "received KeyboardInterrupt"
    finally:
        print "simulation ended"
        sys.exit()

if __name__ == '__main__':
    main()

A: I attempted to understand your problem to see if I could resolve it. I managed to replace the patch plots in a LIVE matplotlib chat upon user request. My working code is shown below.
While digesting your problem, I thought the multiprocessing section was a bit of a distraction to the main problem, i.e. unable to refresh the "matplotlib patches.Path" plot that is embedded in a tkinter window. As such, I adopted the LIVE matplotlib Chart solution by Sentdex (referenced in my script), which is quite similar to your code, as a basis to study your main problem. I think his approach to generating live plot is straight forward to understand.
So in my code, while the tkinter window is up, live data is being stream into the tkinter window LIVE chart, it reads the coordinates of the "matplotlib patches.Path" plot straight off the the file "patchesCoor.txt" and updates the LIVE chart with it. You have to create "patchesCoor.txt" at your end in the same folder as the script and it should contain a single row of entry comprising of 8 numbers separated by white space. Every time you amend the coordinate in that file and save it, the changes will appear in the LIVE Chart in the tkinter window. My solution excludes multiprocessing, although that can be implemented as the next phase of this script.
The section responsible for updating the plots in the LIVE chart is found in "def animate(i)." See my comments there.
Hope you find this solution useful, although it came a few hour after your posted answer.  :)
#!/usr/bin/python3.5
# -*- coding: utf-8 -*-
"""
1. Script for creating LIVE matplotlib figure inside a tkinter window via
   tkinter backend TkAgg (see Reference 1). I replaced the Pack system with a
   Grid system for the Tk objects (see Reference 2), created the scripts to input
   the live data and added your random coordinate generator.

2. It requires 1 input file:
   patchesCoor.txt - 4 x,y coordinate points for the patches.PathPatch plot
                     space seperated type.

References:
1. https://www.youtube.com/watch?v=Zw6M-BnAPP0
2. http://stackoverflow.com/questions/12913854/displaying-matplotlib-navigation-toolbar-in-tkinter-via-grid

Author: Sun Bear
Created on: 17 Jan 2017
"""

import matplotlib
matplotlib.use('TkAgg') # Backend of matplotlib
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import matplotlib.patches as patches
import matplotlib.path as path
import matplotlib.animation as animation
from matplotlib import style
style.use('ggplot')

try:
    # for Python2
    import Tkinter as tk   ## notice capitalized T in Tkinter
    import ttk
except ImportError:
    # for Python3
    import tkinter as tk
    import tkinter.ttk as ttk

import random

class App(ttk.Frame):
    ''' Create tkinter window frame with base matplotlib figure, subplot and
        toolbar. '''

    def __init__(self, parent, *args, **kwargs):

        # Customise ttk styles
        s=ttk.Style()
        s.configure(".", font=('URW Gothic L', '11', 'bold'), foreground='#3D3C3A',
                    cap=tk.ROUND, join=tk.ROUND)
        s.configure('App.TFrame', background='pink')

        # Initialise App Frame
        ttk.Frame.__init__(self, parent, style='App.TFrame', borderwidth=20,
                           relief=tk.FLAT)
        self.grid(row=0, column=0, sticky='nsew')

        # Create tk Canvas
        canvas = FigureCanvasTkAgg(f, self)
        canvas.show()
        canvas.get_tk_widget().grid(row=0, column=0, sticky='nsew')

        # Create matplotlib navigation toolbar in a grid frame
        toolbar_frame = ttk.Frame(self, style='App.TFrame', borderwidth=2,
                           relief=tk.RAISED)
        toolbar_frame.grid(row=1, column=0, sticky='nsew')
        toolbar = NavigationToolbar2TkAgg(canvas, toolbar_frame)

        root.rowconfigure(0, weight=1)
        root.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)
        self.columnconfigure(0, weight=1)

def animate(i):
    '''Provide matplotlib figure with latest plots coordinates and refresh
       matplotlib figure.'''

    # 1. Obtain x, y coordinates for Live data plot
    xList, yList = simulate()

    # 2. Obtain x, y coordinates for patches.PathPatch plot
    patchesData = open('patchesCoor.txt', 'r').read()
    print('patchesData = {}'.format(patchesData))
    patchesList = patchesData.split()
    print('patchesList = {}'.format(patchesList))
    if len(patchesList) > 1:
        x1,y1,x2,y2,x3,y3,x4,y4 = tuple(int(x) for x in patchesList)
    print('patchesCoor = {0} {1} {2} {3} {4} {5} {6} {7}'.
          format(x1,y1,x2,y2,x3,y3,x4,y4))
    monitor_box = path.Path([(x1, y1), (x2, y2), (x3, y3), (x4, y4)])
    patch = patches.PathPatch(monitor_box, facecolor='blue', lw=1)

    # 3. Clear LIVE Chart and update it with latest plot data
    ax.clear()
    ax.plot(xList, yList)   # For random x, y data plot
    ax.add_patch(patch)     # For patches.PathPatch plot
    ax.set_xlim(-1500,2000) #   Need the following 2 lines to ensure
    ax.set_ylim(-1500,2000) #   the Live Chart axis is updated at every read

def simulate():
    ''' Generate random x, y coordinate for Live data'''
    xList = []
    yList = []
    for i in range(100):
        x, y = random.randint(0,1500), random.randint(0,1500)
        xList.append(int(x))
        yList.append(int(y))
    return xList, yList

def matplotlib_base_figure():
    ''' Create matplotlib base figure '''
    f = Figure(figsize=(5,5), dpi=100)
    ax = f.add_subplot(111) # One chart created
    ax.plot([1,2,3,4,5,6,7,8], [5,6,1,8,6,10,2,7])
    monitor_box = path.Path([(35, 1677), (111, -213), (62, -220), (800, 1734)])
    patch = patches.PathPatch(monitor_box, facecolor='black', lw=1)
    ax.add_patch(patch)
    ax.set_xlim(-1500,2000)
    ax.set_ylim(-1500,2000)
    return f, ax

if __name__ == '__main__':

    # 1. Create matplotlib base figure and subplot
    f, ax = matplotlib_base_figure()

    # 2. Create tkinter GUI with matplotlib base figure, subplot & toolbar.
    root = tk.Tk()
    app = App(root)

    # 3. Make matplotlib figure LIVE via animation
    ani = animation.FuncAnimation(f, animate, interval=1000)
    # 'interval' control the update rate of the LIVE Chart.

    # 4. Activate GUI continually via an infinite loop.
    app.mainloop()

Original:  Updated:


text:
Q: Cómo hacer un for genérico que haga push con solamente 3 objetos en un nuevo array? Necesitaría hacer un for genérico, que pushee 3 objetos por cada array. La información lo traigo via API. Esto lo necesito porque estoy usando un carousel y solo quiero mostrar 3 cards por slide.
Adjunto código actual que estoy usando, pero el problema es que en caso de tener 9 objetos en mi API, me faltaría agregar otro push and NewData y creo que esa no sería la mejor idea. Espero que me hayan entendido, un saludo
useEffect(() => {
    getNews()
      .then(function (response) {
        const total = response.data.news.length;
        const groups = total / 3;
        const newData = [];
        newData.push(response.data.news.slice(0, 3));
        newData.push(response.data.news.slice(3));
        setData(newData);
        console.log(newData);
      })
      .catch(function (error) {
        setError(error);
      })
      .finally(function (response) {
        setIsLoading(false);
      });
  }, []);

A: En lugar de usar .slice(), te recomiendo splice(), dentro de un ciclo que se ejecute mientras haya elementos en el arreglo original:
getNews()
    .then(function (response) {
        const newData = [];
        while(response.data.news.length > 0) {
            // Elimina hasta 3 elementos del arreglo original
            // Y los agrega en newData
            newData.push(response.data.news.splice(0, 3));
        }
        setData(newData);
        console.log(newData);
    })
    .catch(function (error) {
        setError(error);
    })
    .finally(function (response) {
        setIsLoading(false);
    });

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pattern Matching - String Search I am trying to work out a formula to match a following pattern:
input string example:
'444'/'443'/'434'/'433'/'344'/'334'/'333'
if any of the patterns above exist in a particular input string I want to match it as the same pattern.
also is it possible to do a variable substitution using regex? meaning check for the 3 chars of the string by using each character as a variable and just doing an increment/decrement for each character? so that you dont have to specify the particular number ranges (hardcoding the pattern string ) for different patterns?
Is there any good library one can use for this?? I was working with Pattern class in java.
If you have any link which would be helpful please pass it through :)
Thank you.

A: Let's first consider this pattern: [34]{3}
The […] is a character class, it matches exactly one of the characters in the set. The {n} is an exact finite repetition.
So, [34]{3} informally means "exactly 3 of either '3' or '4'". Thus, it matches "333", "334", "343", "344", "433", "434", "443", "444", and nothing else.
As a string literal, the pattern is "[34]{3}". If you don't want to hardcode this pattern, then just generate similar-looking strings that follows this template "[…]{n}". Just put the characters that you want to match in the …, and substitute n with the number you want.
Here's an example:
  String alpha = "aeiou";
  int n = 5;

  String pattern = String.format("[%s]{%s}", alpha, n);

  System.out.println(pattern);
  // [aeiou]{5}

We've now seen that the pattern is not hardcoded, but rather programmatically generated depending on the values of the variables alpha and n. The pattern [aeiou]{5} will 5 consecutive lowercase vowels, e.g. "ooiae", "ioauu", "eeeee", etc.
It's again not clear if you just want to match these kinds of strings, or if they have to appear like '…'/'…'/'…'/'…'/'…'. If the latter is desired, then simply compose the pattern as desired, using repetition and grouping as necessary. You can also just programmatically copy and paste the pattern 5 times if that's simpler. Here's an example:
  String p5 = String.format("'%s'/'%<s'/'%<s'/'%<s'/'%<s'", pattern);

  System.out.println(p5);
  // '[aeiou]{5}'/'[aeiou]{5}'/'[aeiou]{5}'/'[aeiou]{5}'/'[aeiou]{5}'

This will now match strings like "'aeooi'/'eeiuu'/'uaooo'/'eeeia'/'eieio'".
Caveat
Do be careful about what goes in alpha. Specifically, -, [. ], &&, ^, etc, are special metacharacters in Java character class definition. If you restrict alpha to contain only digits/letters, then you will probably not run into any problems, but e.g. [^a] does NOT mean "either '^' or 'a'". It in fact means "anything but 'a'. See java.util.regex.Pattern for exact character class syntax.

A: You can use the regex:
('\\d{3}'/){6}'\\d{3}'

A: Pattern.Compile takes a String as its parameter. Though that's probably most often supplied in the form of a string literal, if you have variable upper and lower bounds for your pattern, you can use something like StringBuilder to build your string, then pass that result to Pattern.Compile.


text:
Q: IA32 Assembly cmp on strings I'm having some trouble reverse engineering some IA32 assembly code. Namely, these lines:
   0x08049d6d <+206>:   mov    -0xc(%ebp),%edx
   0x08049d70 <+209>:   mov    -0x14(%ebp),%eax
   0x08049d73 <+212>:   mov    %edx,%ecx
   0x08049d75 <+214>:   sub    %eax,%ecx
   0x08049d77 <+216>:   mov    %ecx,%eax
   0x08049d79 <+218>:   cmp    $0x5,%eax
   0x08049d7c <+221>:   je     0x8049d83 <level_6+228>

Here, the $edx register is holding a string and the $eax register is holding the same string, only with the character at index 0 removed.
The confusion arises from the sub instruction at step 214. It seems, no matter what the two characters are at the start of the strings, it comes out to 1. Is it comparing the lengths of the strings?
Additionally what does calling cmp on two strings compare?
Many thanks!
EDIT:
Earlier, two strings are being cmp'd:
0x08049d68 <+201>: cmp -0xc(%ebp),%eax
0x08049d6b <+204>: jb 0x8049cfa <level_6+91>

A: It feels like we've been here before.
Registers can't "hold strings", unless they're very short ones. What you're got there are addresses of strings, or pointers to (the first characters of) strings. If %edx holds a pointer to the string, and %eax holds "the same string, only with the character at index 0 removed", then %eax almost certainly points to the second character of the string.
That being the case, if you subtract one from the other, of course you're always going to get 1, because the second character of the string is always one byte further along than the first character. It doesn't matter what the characters are, because you're comparing addresses.
The cmp instruction is clearly not comparing two strings - it's comparing the literal number 5 with the contents of %eax, which at that point will be your 1, the difference between the two pointers. So the cmp instruction compares 5 with 1, and if they're equal - which they're obviously not, in this case - jmps to 0x8049d83.
That being said, I suspect you have this back to front. If %edx points to the start of the string, and %eax points to the second character, then the sub instruction should be giving you -1, not 1. %edx and %eax are probably the other way round. This routine seems to be designed to jmp to 0x8049d83 when %edx points to the sixth character of the string that %eax points to.


text:
Q: Multiple definition of a function in C/C++ code This is a question on C/C++ function definitions. The code discussed is the static library libRmath that provides the definitions in the Rmath.h header file in R.
The documentation provided for the library states that it is optional for the user to provide the function definition for the function double unif_rand(void).
So my question is if such a function definition is optional, wouldn't there be a problem of multiple function definitions which is not allowed in C/C++?
Edit:
It might be tempting to speculate on how things works without looking at the source code, but that is not what I want. I am interested to know how it really works, so you would probably need to read the source code and documentations to answer this question.

A: When you application is linked, unresolved symbols will be resolved using the libraries you provide. If you don't define a function, it will be an unresolved symbol during linking, therefore, the linked will try to resolve that symbol using librmath, in this case. If one or more symbols can't be resolved, you'll get a linker error.
However, if you do define the function in your code, it will be already defined during linking, so there will be no need to resolve it using symbols from external libraries.
What you can't do is to define the same symbol more than once in your application.
Edit: Since there is a lot of debate in another answer, i've made a practical example. I've created a shared object(similar to a DLL in windows), which defines and exports a function foo:
//lib.h
extern "C" {
    void foo();
    void bar();
};

//lib.cpp
#include <iostream>
#include "lib.h"

void foo() {
    std::cout << "From lib\n";
}

void bar() {
    std::cout << "Bar, calling foo\n";
    foo();
}

In order to test this shared object, i've created an application which is linked with it:
//test.cpp
#include <iostream>
#include "lib.h"

void foo() {
    std::cout << "From app\n";
}

int main() {
    bar();
}

I've compiled both, the shared object and the application:
g++ lib.cpp -o libtest.so -Wall -fPIC -shared -Wl,--export-dynamic -Wl,-soname,libtest.so -Wl,-z,defs
g++ test.cpp -o test -L. -ltest

And when i execute test, setting the library path to ".", so my shared object can be loaded, i get this output:
matias@master:/tmp$ LD_LIBRARY_PATH="." ./test
Bar, calling foo
From app

As you can see, the foo function defined in the application(not the shared object) is called. You can basically do this for every exported symbol in a shared object.
EDIT2: i've added another exported function in lib.h. The application now calls this function, which ends up calling foo. The result is the same, as expected.
EDIT3: Ok, let's go deeper. This is the dump from function bar:
Dump of assembler code for function bar@plt:
   0x0804855c <+0>: jmp    DWORD PTR ds:0x804a004
   0x08048562 <+6>: push   0x8
   0x08048567 <+11>:    jmp    0x804853c

If we go to address 0x804a004:
Dump of assembler code for function _GLOBAL_OFFSET_TABLE_:
   0x08049ff4 <+0>: or     BYTE PTR [edi+0x804],bl
   0x08049ffa <+6>: add    BYTE PTR [eax],al
   0x08049ffc <+8>: add    BYTE PTR [eax],al
   0x08049ffe <+10>:    add    BYTE PTR [eax],al
   .....

As you can see, it's jumping to the Global Offset Table. You can read about the GOT here and here. Dynamic symbols(which are resolved at runtime) are stored in this table. Whenever you call a symbol that should be resolved at runtime, you actually jump to this table, and then jump to the address that is stored in the this table's corresponding entry. Since the application defines foo, the GOT contains the address of the definition from test.cpp, not the one in our shared object.
EDIT4: Okay, last edit. Quoting from the documentation:

You will need to supply the uniform random number generator
 double unif_rand(void)

or use the one supplied (and with a dynamic library or DLL you will
  have to use the one supplied(...)

The documentation clearly says that you cannot provide you own implementation of unif_rand if you're using the dynamic library. Therefore, i believe that what i pointed out, actually answers your question.

A: Linking a static library is slightly different from linking all the objects inside the static library.
Definitions in the static library are pulled in only if needed, so they can't cause multiple definition errors.
This has some side effects, for example the well-known problem of global initializers inside a static library not running when nothing in the main program references that object.


text:
Q: Give filter_var() filter by passing a variable PHP (filter_var() expects parameter 2 to be long, string given) Right now i'm trying to validate some postdata with filter_var(). I want to get the filter related to each input from my database. So if the input should be filtered by EMAIL, the variable would contain FILTER_VALIDATE_EMAIL. This would then be passed like so:
        foreach($this->postdata as $key => $input){
        if(!((empty($requirements[$key][1])) || $requirements == 'allowed')){
            if(filter_var($input, $requirements[$key][1]) === false){
                $errors = true;
            }
        }
    }

The $postdata looks like this:
    array (size=4)
  'personer_navn' =>
    array (size=1)
      0 => int 0
  'personer_alder' =>
    array (size=1)
      0 => int 1
  'personer_kon' =>
    array (size=2)
      0 => int 2
      1 => int 3
  'personer_by' =>
    array (size=1)
      0 => int 4

And the $requirements looks like this:
    array (size=4)
  'personer_navn' =>
    array (size=4)
      0 => string 'string' (length=6)
      1 => string 'FILTER_VALIDATE_EMAIL' (length=21)
      2 => string '' (length=0)
      3 => string '' (length=0)
  'personer_alder' =>
    array (size=4)
      0 => string 'int' (length=3)
      1 => string 'FILTER_VALIDATE_EMAIL' (length=21)
      2 => string '' (length=0)
      3 => string '' (length=0)
  'personer_kon' =>
    array (size=4)
      0 => string 'allowed' (length=7)
      1 => string 'allowed' (length=7)
      2 => string 'allowed' (length=7)
      3 => string 'allowed' (length=7)
  'personer_by' =>
    array (size=4)
      0 => string 'string' (length=6)
      1 => string 'FILTER_VALIDATE_EMAIL' (length=21)
      2 => string '' (length=0)
      3 => string '' (length=0)

Again the problem seems to ba passing $requirements[$key][1] to the filter_var() function.
Any help is appreciated.

A: FILTER_VALIDATE_EMAIL is not to be used as a string. Try using it without the quotes. Examples can be found in the documentation

A: A simple change that will fix the bug
foreach($this->postdata as $key => $input){
        if(!((empty($requirements[$key][1])) || $requirements == 'allowed')){
            if(filter_var($input, constant( $requirements[$key][1]) ) === false){
                $errors = true;
            }
        }
    }

The constant function returns the (integer) value of the filter that is string.
read P.P-s answer too.


text:
Q: Solving allocation through cost minimization I have limited knowledge when it comes to math notation so please excuse my crude example:
I am looking to allocate a number of units into boxes in a way that minimizes a total cost. Boxes have a known (1) maximum they can hold, (2) a minimum they can hold (always non-negative but sometimes a value), and each box has a (3) cost per unit.
Example: I have a pile of units totaling 100 units that must be separated into n boxes ($x_1, x_2, x_3, ... x_n$).
Where number of boxes n = 3,
Constraints:
Known maximum number of units a box can hold ($x_1 \leq 45$, $x_2 \leq 45$, $x_3 \leq 50$).
Known minimum number of units a box can hold ($x_1 \geq 15$, $x_2 \leq 0$, $x_3 \leq 0$).
Known cost (C) associated with putting units into a box is ($c_{x_1}=1$, $c_{x_1}=2, c_{x_1}=3$).
Minimize: $y = \sum_{i=1}^n{(X_i*C_i)}$
or $y = x_1*c_{x_1} + x_2*c_{x_2} + x_3*c_{x_3}$
subject to the above constraints, to solve the units per box.
This example is simple enough to solve without any calculus but for more intimidating problems I am guessing one can use Lagrange optimization but I can't quite get over the hump of inequality constraints/using slack variables. How can I solve this?
Any help and/or easy to digest references for tackling this problem would be appreciated.


text:
Q: How to jqGrid dynamic multiselecet? I hava jqGrid checkbox column,This dynamic build
                colNames: ['Id', 'True/False'],
            colModel: [
                { name: 'Id', index: 'Id', sorttype: "int", hidden: false },
                {
                    name: "Selected", index: 'Selected', width: 70, align: "center",
                    formatter: "checkbox", formatoptions: { disabled: false },
                    editable: false, editoptions: { value: "True:False", defaultValue: "No" },
                    stype: "select", searchoptions: {
                        sopt: ["eq", "ne"],
                        value: ":Any;true:Yes;false:No"
                    },
                },

this code selected columns is checkbox how to this column is multiple selection with its own feature jqGrid
Multiselect: true
And I cant checkbox value (true or false ) How can I do it? ;
If selected column value is true, get multiselect (jqGrid feature) true
If selected column false,get multiselect column false
Thank you in advance for your help. I wish you a good day.

A: JavaScript is sensitive on the code:
To enable multiselection use the following code:
$("#grid_id").jqGrid({
  ...
  multiselect : true,
  ...
});

To get the selected rows when a multiselect is enabled do:
var selectedRows =  $("#grid_id").jqGrid('getGridParam', 'selarrrow');

The selectedRows variable is array which every element is a selected row id. If notihing is selected the array is empty - i.e selectedRows.length = 0;


text:
Q: How to setup Spring Cloud LoadBalancer with RestTemplate? Is there a way to setup the new Spring Cloud LoadBalancer to work with RestTemplate? The only tutorials I find are using Flux and Project Reactor for microservice communications.

A: Yes, there is. You can see this branch for a working demo.


text:
Q: Dependency Injection in scala I have a trait
trait Tt[T]{
   //tens of methods
}

and
class St{ tt: Tt[T] =>
  type T = //...
  //some methods
}

object St{
    def apply[T](tt: Tt[T]) = new St with tt //error
}

The issue is the objects of Tt are generated by a library. Is there a way to avoid implementing all these tens of methods and just "inject the instance"?
I cannot just pass it as a parameter, because of the type variable declaration that is defined inside the class.
Extracting the type variable declaration to the type parameter is not possible.

A: How about class St(val tt: Tt[St#T]) { type T = ... }
There is something else with your apply though: St wants the type parameter to Tt to be the same as it's own type T (you gotta start using more letters for these types), but apply is parametrized with T, which is yet another different type, that just happens to use the same letter. So, def apply[T](tt: Tt[T]) = new St(tt) won't compile, it needs to be def apply(tt: Tt(St#T)) = new St(tt)


text:
Q: How could I take only the items in an array of objects that match the users input I have a response body that looks something like this:
        {
            "id": "provider-a7d49a99-53c0-4b7c-9be3-8b9efc828f1b",
            "fullName": "Dr. Tim Lucca, FSE",
            "firstName": "Tim",
            "lastName": "Lucca",
            "prefix": "Dr.",
            "suffix": "FSE",
            "phone": "(303) 520-4571",
            "state": "CO",
            "doseSpotID": 185012,
            "active": "active",
            "capabilities": {
                "demographic": [
                    "adolescent",
                    "adult",
                    "child"
                ],
                "geographic": [
                    "CO",
                    "TX"
                ],
                "linguistic": [
                    "english",
                    "spanish"
                ],
                "credentialedPayors": null
            },
            "invitePending": false
        },
        {
            "id": "provider-450de310-fcb5-4e71-9d72-b6b320b2eb0a",
            "fullName": "Mr Doc Torr",
            "firstName": "Doc",
            "lastName": "Torr",
            "prefix": "Mr",
            "suffix": "",
            "phone": "(303) 520-4571",
            "state": "CO",
            "doseSpotID": 186856,
            "active": "active",
            "capabilities": {
                "demographic": [
                    "adult",
                    "adolescent",
                    "child"
                ],
                "geographic": [
                    "CO",
                    "TX"
                ],
                "linguistic": [
                    "english"
                ],
                "credentialedPayors": null
            },
            "invitePending": false
        }
    ]

I have a search field for the user that they are able to search by fullName, phone, and geographic. Im trying to understand how to sort the list returned and display only the items in the list that have a match for the users input. What would be a good way to sort through the array of objects and creating an array of matches for the users search? Right now my component is just displaying all of the items returned.

A: for an exect match i would do this
let to_sort =
    [
        {
            "id": "provider-a7d49a99-53c0-4b7c-9be3-8b9efc828f1b",
            "fullName": "Dr. Tim Lucca, FSE",
            "firstName": "Tim",
            "lastName": "Lucca",
            "prefix": "Dr.",
            "suffix": "FSE",
            "phone": "(303) 520-4571",
            "state": "CO",
            "doseSpotID": 185012,
            "active": "active",
            "capabilities": {
                "demographic": [
                    "adolescent",
                    "adult",
                    "child"
                ],
                "geographic": [
                    "CO",
                    "TX"
                ],
                "linguistic": [
                    "english",
                    "spanish"
                ],
                "credentialedPayors": null
            },
            "invitePending": false
        },
        {
            "id": "provider-450de310-fcb5-4e71-9d72-b6b320b2eb0a",
            "fullName": "Mr Doc Torr",
            "firstName": "Doc",
            "lastName": "Torr",
            "prefix": "Mr",
            "suffix": "",
            "phone": "(303) 520-4571",
            "state": "CO",
            "doseSpotID": 186856,
            "active": "active",
            "capabilities": {
                "demographic": [
                    "adult",
                    "adolescent",
                    "child"
                ],
                "geographic": [
                    "CO",
                    "TX"
                ],
                "linguistic": [
                    "english"
                ],
                "credentialedPayors": null
            },
            "invitePending": false
        }
    ]
let user_fullName = 'Dr. Tim Lucca, FSE'
let phone = '(303) 520-4571'
let geographic = 'CO'
let result = to_sort.filter((obj)=>{
    if(obj.fullName !== user_fullName){
        return false
    }
    if(obj.phone !== phone){
        return false
    }
    if(!obj.capabilities.geographic.includes(geographic)){
        return false
    }
    return true
});

to check if 1 of the properties is the same (not gonna put the data in is its quite big)
let user_fullName = 'Dr. Tim Lucca, FSE'
let phone = '(303) 520-4571'
let geographic = 'CO'
let result = to_sort.filter((obj)=>{
    if(obj.fullName === user_fullName || obj.phone === phone || obj.capabilities.geographic.includes(geographic)){
        return true
    }
    return false
});

in both cases result is an array of objects which have met the criteria


text:
Q: Send XML using XMLHttpRequest using GWT Currently I use the JavaScript code to send XML data in GWT. Is there an easier way to send them?
 sendRequest.addClickHandler(new ClickHandler() {

      @Override
      public void onClick(ClickEvent event) {
        // RegisterBuiltin.register(ResteasyProviderFactory.getInstance());
        // ItemExtension client = ProxyFactory.create(ItemExtension.class, "http://localhost:8081");

        sendXMLFFI(restInput.getText());

 protected native void sendXMLFFI(String text)
  /*-{
    var xmlhttp=false;

    if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
      try {
      xmlhttp = new XMLHttpRequest();
      } catch (e) {
      xmlhttp=false;
      }
    }

    if (!xmlhttp && window.createRequest) {
      try {
          xmlhttp = window.createRequest();
        } catch (e) {
          xmlhttp=false;
        }
    }

    xmlhttp.open("POST", "./REST/Items",true);
    xmlhttp.setRequestHeader("Content-Type", "application/xml")
    xmlhttp.send("<?xml version='1.0' encoding='UTF-8'?>\n\n"+
           "<item barcode='111'><name>Foo</name><quantity>100</quantity></item>");
  }-*/;

A: RequestBuilder rb = new RequestBuilder(RequestBuilder.POST, "./REST/Items");
rb.setHeader("Content-Type", "application/xml");
rb.sendRequest("<?xml version='1.0' encoding='UTF-8'?>\n\n"+
    "<item barcode='111'><name>Foo</name><quantity>100</quantity></item>",
    new RequestCallback() { ... }
);


text:
Q: Differential amplifier with feedback resistor
In this circuit, if a resistor of 1 M\$\Omega\$ is connected between A and B, what is the effect on the stability of the quiescent point?
The analysis I made led me to believe it would provide positive feedback and thus won't stabilize the point, but I dont feel safe enough as to assure it. Which is a good method for verifying this? I couldn't think of a way to check it in a circuit simulation

A:
The analysis I made led me to believe it would provide positive
  feedback and thus won't stabilize the point, but I dont feel safe
  enough as to assure it

Your analysis is correct. If point A rises slightly, T2's collector drops slightly. When T2's collector drops slightly it turns on Q9 more and its drain rises in voltage and, if that drain (point B) is attached to point A it will raise point A a bit more and rapidly the circuit hits the rails due to positive feedback.

A: For positive-feedback to cause oscillation, you'll need a total loop gain (Forward Gain * Feedback Gain) greater than ONE.
If you want extremely precise settling, even a small bit of positive feedback can cause over-shoot, or under-shoot, and thus invalidate your settling predictions.
I suggest your install the 1MegOhm feedback, and then apply 1 millivolt squarewave to Vs (left hand back of the diffpair). If that looks well-behaved, then apply 1 volt just for fun.


text:
Q: "The name 'msg' doesn't exist in the current context" - ASPX Error I am programming a website as a part of my own project, and I have a registration form with a javascript validating first the email, password, fname, and etc and only then it submits the form. From there the c# takes over and checks if there is a user with such username in the database, and if there's I want to show an error as a paragraph in the registration form or show alert using JS.
Website:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="register.aspx.cs" Inherits="EquimaxSchool.register" %>

    <form id="register" runat="server" method="post" >

Login Form

<input class="form-control" type="text" name="username" placeholder="Username" runat="server" id="username"/>

<input class="form-control" type="text" name="email" placeholder="Email" runat="server" id="email">

<input class="form-control" type="password" name="password" placeholder="Password" runat="server" id="password">

<input class="form-control" type="text" name="fName" placeholder="First Name" runat="server" id="fName" />

<input class="form-control" type="text" name="lName" placeholder="Last Name" runat="server" id="lName" required/>

<input class="form-control" type="date" name="birthdate" runat="server" id="birthdate" placeholder="Birthdate" required/>

<input class="form-control" title="Phone Number" name="phonenumber" placeholder="Phone Number" runat="server" id="phonenumber" />

<select id="gender" name="gender" class="form-control" style="color:#6c757d" required>
                                        <option value="Gender" disabled="disabled" selected="selected">Gender</option>
                                        <option value="Male">Male</option>
                                        <option value="Female">Female</option>
                                        <option value="Other">Other</option>
            </select>

<select id="camera" name="camera-brand" class="form-control" style="color:#6c757d" required>
                                        <option value="Camera Brand" disabled="disabled" selected="selected">Camera Brand</option>
                                        <option value="Nikon">Nikon</option>
                                        <option value="Canon">Canon</option>
                                        <option value="Fuji">Fuji</option>
                                        <option value="Sony">Sony</option>
                                        <option value="Other">Other</option>
            </select>

<input class="form-control" type="text" name="lens" placeholder="Lens" id="lens"/>

<select id="genre" name="genre" runat="server" class="form-control" style="color:#6c757d" required>
                                    <option value="Sport">Sports</option>
                                    <option value="Wildlife">Wildlife</option>
                                    <option value="Landscape">Landscape</option>
                                    <option value="Portrait">Portrait</option>
                                    <option value="Architecture">Architecture</option>
            </select>

<button class="btn btn-primary btn-block" type="submit" runat="server" id="submit">Sign up</button>

        <%= msg %> <===== **THIS IS WHERE THE ERROR OCCURS**
        </form>

(Please note I've redacted unnecessary tags and etc)
The JS of validation of form:

The code behind it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace EquimaxSchool
{
    public partial class register : System.Web.UI.Page
    {
        public string msg = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Form["submit"] != null)
            {
                string email = Request.Form["email"];
                string password = Request.Form["password"];
                string gender = Request.Form["gender"];
                string fName = Request.Form["fName"];
                string lName = Request.Form["lName"];
                string phoneNumber = Request.Form["phonenumber"];
                string camera = Request.Form["camera-brand"];
                string birthdate = Request.Form["birthdate"];
                string genre = Request.Form["genre"];
                string username = Request.Form["username"];
                string fileName = "UsersData.mdf";
                string tableName = "usersTbl";
                string sqlSelect = "SELECT * FROM " + tableName + " WHERE Username = '" + username + "'";

                if (Helper.IsExist(fileName, sqlSelect))
                {
                    msg = "Username has been taken already.";
                }
            }

        }
    }
}

Helper.cs for those asking

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

///
/// Summary description for Helper
///
///

public class Helper
{
    public static SqlConnection ConnectToDb(string fileName)
    {
            string path = HttpContext.Current.Server.MapPath("App_Data/") + fileName;
        //string connString = @"Data Source=.\SQLEXPRESS;AttachDbFileName=" + path + ";Integrated Security=True;User Instance=True";
        //string connString = @"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = |DataDirectory|\" + fileName + " Integrated Security = True";
        //string connString = @"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = " + path + " Integrated Security = True";

        //string connString = @"";

        string connString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=" + path + ";Integrated Security=True;Connect Timeout=30";

        SqlConnection conn = new SqlConnection(connString);
            return conn;
    }

    public static void DoQuery(string fileName, string sql)
    {
        SqlConnection conn = ConnectToDb(fileName);
        conn.Open();
        SqlCommand com = new SqlCommand(sql, conn);
        com.ExecuteNonQuery();
        conn.Close();
    }

    public static bool IsExist(string fileName, string sql)
    {

        SqlConnection conn = ConnectToDb(fileName);
        conn.Open();
        SqlCommand com = new SqlCommand(sql, conn);
        SqlDataReader data = com.ExecuteReader();

        bool found = Convert.ToBoolean(data.Read());
        conn.Close();
        return found;

    }

    public static DataTable ExecuteDataTable(string fileName, string sql)
    {
        SqlConnection conn = ConnectToDb(fileName);
        conn.Open();

        DataTable dt = new DataTable();

        SqlDataAdapter tableAdapter = new SqlDataAdapter(sql, conn);

        tableAdapter.Fill(dt);

        return dt;
    }

}

https://i.stack.imgur.com/b5GmQ.png

A: Your page inherits the class 'EquimaxSchool.login'
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="register.aspx.cs" Inherits="EquimaxSchool.login" %>

However, your C# class is named 'EquimaxSchool.Webform1'
namespace EquimaxSchool
    {
        public partial class WebForm1 : System.Web.UI.Page
        {

Have you shown us the correct codebehind file?  Is there a class called 'login' in the register.aspx.cs file?


text:
Q: Can't understand a step in the advanced calculus book by thomas P. Dence On page 9 of the Advanced calculus book by Thomas P. Dence he defines the set $S_1 = \{x\in \Bbb Q: x\geq 0, x^2 \leq 5\}$
and he said that the supremum $U$ is less than $u=3$ and that $U$ is nonnegative
and then he said that $$x= \frac{3U+5}{3+U}$$
I don't understand how we reached this final step

A: The author is asking you to assume that $U$ is the supremum of $S_1$ and is also a member of $S_1$, which means it is rational. He then ask you to suppose the following equation is true: $$x= \frac{3U+5}{3+U}$$
At this point, $x$ is just any variable; not necessarily a member of $S_1$ yet. The equation seems to come from nowhere but the author knows where he's going with it. Sometimes proofs are done this way. Read the rest of his argument and it might make sense. He's trying to show that the supremum of $S_1$ is not a member of $S_1$.


text:
Q: Why implicit object has precedence over val in Scala 2.13-M5? I'm wondering if this is a bug or an expected behaviour in Scala 2.13-M5.
Following snippet compiles and outputs "object in package object":
package object test {
  implicit val a: TS = new TS("val in package object")
  implicit object b extends TS("object in package object")
}

package test {
  class TS(override val toString: String)

  class Inner {
    implicit val f: TS = new TS("val in inner class")
    val resolve = implicitly[TS]
  }
  object Test extends App {
    println(new Inner().resolve)
  }
}

With commented out third line implicit object b extends TS("object in package object" there is an ambiguous implicit compile error which is what I would expect in first case as well:
Error:(11, 29) ambiguous implicit values:
 both value a in package test of type => test.TS
 and value f in class Inner of type => test.TS
 match expected type test.TS
    val resolve = implicitly[TS]

A: In your example, a, b and f all seem to be eligible implicit values. As the FAQ says (emphasis mine):

[...] this entails selecting a narrower type or a value defined in a subclass relative to other eligible values

therefore, the object b is selected, because b.type is a strict subtype of TS.

Here is another example that demonstrates the same behavior, but without packages or objects:
case class TS(str: String)

object test {
  implicit val a: TS = new TS("val in package object")
  // implicit object b extends TS("object in package object")
  class MoreSpecial() extends TS("I'm special")
  implicit val s: MoreSpecial = new MoreSpecial()

  class TS(override val toString: String)

  class Inner {
    implicit val f: TS = new TS("val in inner class")
    val resolve = implicitly[TS]
  }
  object Test {
    def run(): Unit = {
      println(new Inner().resolve)
    }
  }
}

test.Test.run()

it will print "I'm special", because the instance of class MoreSpecial thinks that it's the most specific one, simply because its type MoreSpecial is a strict subtype of TS.
Moreover,

*

*if you uncomment the b line, it gives ambiguous implicits error (b: b.type <: TS conflicts with s: MoreSpecial <: TS)

*if you comment the s line, it also gives ambiguous implicits error (a: TS conflicts with f: TS)

*only if ((s is commented) XOR (b is commented)), then it compiles (both b: b.type and s: MoreSpecial win over a: TS and f: TS)

That's all as expected. This holds for 2.12.6, so it doesn't seem specific to 2.13-Mx.


text:
Q: java - Solr localhost:8983 Not Found I am new to solr. Following the tutorial from here i Can't Get Past Step 2 in the Tutorial. After running java -jar start.jar and  then connecting to http://localhost:8983/solr/

i get this error page which says:
HTTP ERROR: 404

Problem accessing /solr/. Reason:

    Not Found

Powered by Jetty://

I changed the port from 8983 to 8080 but the problem persisted.
On running ant ant example i get this error message build.xml does nto exist
I am working with windows 7 and the downloaded version of solr is solr-4.9.0.zip.

A: Please check wheather the port(8983) is already in use or not. You can start solr in alternate port(like 4983) by using the following command
java -Djetty.port=4983 -jar start.jar
And now hit your browser with your doamin name or localhost:port as shown below:
http://yourdoamin.com:4983/solr
If you are still unable to start solr ,then solr log at the follwoing path
../solr-4.9.0/example/logs

A: Can you please post your solr.log?
Also when you start the solr with: java -Djetty.port=4983 -jar start.jar
Are you able to see server started in the console from where you are executing this?
How are you changing jetty port in solr? Through commands i mentioned above or by changing jetty.xml.
Note: changing port in jetty.xml dont work properly.


text:
Q: How to install ZIP-based OS in VirtualBox? I'm trying to run LineageOS in VirtualBox. I have already downloaded the ZIP-file and tried to create a bootable ISO-file of the content with mkisofs. This was not successful because VirtualBox could not find a bootable medium (before booting I added the ISO to the optical drive).

A: In your comment, you say

I know that LineageOS is not build for the PC but I want to try it out without the need of flashing it to my phone. It is possible to run the original Android image in VirtualBox although it is not build for this purpose.

As you point out, LineageOS is not built for the Intel x86 architecture used in PC processors, but for the ARM architecture used in most mobile devices.
When you say the "original Android image" can be run in VirtualBox, perhaps you're thinking of the Android x86 project? This is a version of Android that has been modified to run on x86 processors. Similarly, in order to run on x86 processors (and in VirtualBox) someone would need to port the LineageOS code itself and create a compatible build. You won't be able to run the OnePlus 3 version in VirtualBox as it is built for ARM processors.
If you want to try it out without flashing it to your phone, perhaps you could use some sort of Android Device Emulator for the PC?

A: Actually, there IS a LineageOS build for x86 PCs - including emulators (such as vmWare and VirtualBox).  You are thinking (like all too many) that x86 is not a valid target - despite x86 being not only a valid generic target, but a Google-supported target - going all the way back to Lollipop.  What has been lacking is NOT the support in Android - but in the generic x86-emulation support community (neither vmWare or Oracle VirtualBox supports Android  as a guest); you have to make VirtualBox (for example) think that Android is Linux to get it to run at all.  Alternatively, you can take that same ISO and run it on a USB stick (that is something that I personally have done since the days of Lollipop-x86).


text:
Q: Removing specific index from list while iterating / improving nested loops I am in a situation where I have 3 nested loops. Every x iterations, I want to restart the 2nd for loop.
If an element in the 3rd for loop meets a certain condition, I want to remove that element from the list.
I'm not sure how to implement this and using a list comprehension or creating a new list wouldn't really work based on the similar questions I read.
Example pseudocode:
items_of_interest = ["apple", "pear"]

while True: # restart 10,000 iterations (API key only last 10,000 requests)
    api_key = generate_new_api_key()
    for i in range(10000):
        html = requests.get(f"http://example.com/{api_key}/items").text
        for item in items_of_interest:
            if item in html:
                items_of_interest.remove(item)

The original code is a lot bigger with a lot of checks, constantly parsing an API for something, and it's a bit messy to organize as you can tell. I'm not sure how to reduce the complexity.

A: Without knowing the full picture, it's hard to say which approach is optimal. In any case, here's one approach using comprehension.
items_of_interest = ["apple", "pear"]

while True: # restart 10,000 iterations (API key only last 10,000 requests)
    api_key = generate_new_api_key()
    for i in range(10000):
        html = requests.get(f"http://example.com/{api_key}/items").text

        # Split your text blob into separate strings in a set
        haystack = set(html.split(' '))
        # Exclude the found items!
        items_of_interest = list(set(items_of_interest).difference(haystack))

A: It works much like you suggest. The relevant keyword is del. eg
>>> x = range(5)
>>> for i in ['a','b','c']:
...     print ('i:' + str(i) )
...     for j in x:
...         print('j:' + str(j))
...     if j == 3:
...             del x[j]
...
i:a
j:0
j:1
j:2
j:3
i:b
j:0
j:1
j:2
j:4
i:c
j:0
j:1
j:2
j:4

3 has been removed from the list x for the later passes.
See also Python doco https://docs.python.org/3.7/tutorial/datastructures.html and SO answers like Difference between del, remove and pop on lists


text:
Q: Javascript date constructor defaults to daylight savings even when current time is standard time For Example:
var rd = new Date(2013, 2, 15, 10, 0, 0, 0);
rd.toString();

Will return "Fri Mar 15 2013 10:00:00 GMT-0700 (Pacific Daylight Time)"  Even though the current active time on the platform is "Pacific Standard Time"..
This makes no sense - it should either return TZ as the current active TZ
Why does the constructor do this?

A: I am going to say that this is because DST starts on March 10. So if I wanted to use JS to enter a meeting I plan to have at 10:00 am, I'm going to want that to be 10:00 AM PDT.
I tested a few scenarios, I set my TZ to Pacific, and ran your code, it tells me the same as you, 10:00 PDT, I switched the date to the 9th and it said 10:00 PST, I then told my clock to ignore DST and set it back to the 15th and it then told me 10:00 PST.
I would have to say that this is working exactly how I would expect it to work based on the time settings on my local machine.
P.S.: IE is much more responsive to changes to my local machines time settings, I had to close and re-open chrome to get it to recognize I changed my clock.


text:
Q: ConnectionException while trying to query SymbolTable While trying to query SymbolTable from ApexClassMember I recieve ConnectionException.
ToolingConnection con = ...;//get connection here
String query = "SELECT FullName, SymbolTable FROM ApexClassMember";
QueryResult qr = con.query(query);//it causes exception

If I am doing query without SymbolTable everything is ok.
Here is exception:
com.sforce.ws.ConnectionException: Unexpected element. Parser was expecting element 'urn:tooling.soap.sforce.com:returnType' but found 'urn:tooling.soap.sforce.com:visibility'
at com.sforce.ws.bind.TypeMapper.verifyTag(TypeMapper.java:411)
at com.sforce.ws.bind.TypeMapper.verifyElement(TypeMapper.java:440)
at com.sforce.soap.tooling.Method.setReturnType(Method.java:36)
at com.sforce.soap.tooling.Method.loadFields(Method.java:71)
at com.sforce.soap.tooling.Method.load(Method.java:64)
at com.sforce.ws.bind.TypeMapper.readSingle(TypeMapper.java:662)
at com.sforce.ws.bind.TypeMapper.readArray(TypeMapper.java:553)
at com.sforce.ws.bind.TypeMapper.readObject(TypeMapper.java:531)
at com.sforce.soap.tooling.SymbolTable.setMethods(SymbolTable.java:177)
at com.sforce.soap.tooling.SymbolTable.loadFields(SymbolTable.java:392)
at com.sforce.soap.tooling.SymbolTable.load(SymbolTable.java:381)
at com.sforce.ws.bind.TypeMapper.readSingle(TypeMapper.java:662)
at com.sforce.ws.bind.TypeMapper.readObject(TypeMapper.java:529)
at com.sforce.soap.tooling.ApexClassMember.setSymbolTable(ApexClassMember.java:485)
at com.sforce.soap.tooling.ApexClassMember.loadFields(ApexClassMember.java:580)
at com.sforce.soap.tooling.ApexClassMember.load(ApexClassMember.java:557)
at com.sforce.ws.bind.TypeMapper.readSingle(TypeMapper.java:662)
at com.sforce.ws.bind.TypeMapper.readArray(TypeMapper.java:553)
at com.sforce.ws.bind.TypeMapper.readObject(TypeMapper.java:531)
at com.sforce.soap.tooling.QueryResult.setRecords(QueryResult.java:153)
at com.sforce.soap.tooling.QueryResult.loadFields(QueryResult.java:250)
at com.sforce.soap.tooling.QueryResult.load(QueryResult.java:240)
at com.sforce.ws.bind.TypeMapper.readSingle(TypeMapper.java:662)
at com.sforce.ws.bind.TypeMapper.readObject(TypeMapper.java:529)
at com.sforce.soap.tooling.QueryResponse_element.setResult(QueryResponse_element.java:37)
at com.sforce.soap.tooling.QueryResponse_element.loadFields(QueryResponse_element.java:68)
at com.sforce.soap.tooling.QueryResponse_element.load(QueryResponse_element.java:62)
at com.sforce.ws.bind.TypeMapper.readSingle(TypeMapper.java:662)
at com.sforce.ws.bind.TypeMapper.readObject(TypeMapper.java:529)
at com.sforce.ws.transport.SoapConnection.bind(SoapConnection.java:180)
at com.sforce.ws.transport.SoapConnection.receive(SoapConnection.java:154)
at com.sforce.ws.transport.SoapConnection.send(SoapConnection.java:99)
at com.sforce.soap.tooling.ToolingConnection.query(ToolingConnection.java:588)

Thanks in advance!

A: The problem has been solved by setting correct endpoint API version when getting ToolingConnection.


text:
Q: Как убрать типы при формировании опций через ng-options? Всем привет. Подскажите, как убрать тип в options при выводе в селекте:
Формирую так
<select name="userId"  ng-model="userId" ng-options="user.id as user.title for user in usersSelectOptions">

Получаю
<option label="Все пользователи" value="number:0">Все пользователи</option>

Как убрать number:?


text:
Q: How do I start Foreman server on background on production? I have successfully deployed my rails Application on a VPS using Ubuntu server with Digital ocean. I am using foreman to start many processes, I can start my foreman server with foreman start if I ssh into my server but when I close the terminal all the processes stop. how do I make it run continuously on the background?
thanks in advance.

A: *

*ssh into the remote machine

*start tmux by typing tmux into the shell

*start the process you want inside the started tmux session

*leave/detach the tmux session by typing Ctrl+B and then D

You can now safely logoff from the remote machine, your process will keep running inside tmux. When you come back again and want to check the status of your process you can use tmux attach to attach to your tmux session.
If you want to have multiple session running side-by-side you should name each session using Ctrl-B and $. You can get a list of the currently running sessions using tmux list-sessions.
tmux can do much more advanced things then handle a single window in a single session. For more information have a look in man tmux or http://tmux.github.io/ . A FAQ about the main differences between screen and tmux is available here.

A: A better question would be "how do I run a Rails application as a service?".
Foreman is a great tool for development, but it does not offer process supervision, automatic start on server up, log rotation or the ability to manage processes with Unix signals.
If your Ubuntu is 15.04, you have systemd installed, and should use that instead. Foreman can even export your config via foreman export systemd (see the foreman manpage).
If your Ubuntu is older than that, you will have Upstart, which, again, Foreman can export to (foreman export upstart).
Using nohup, screen or tmux for running processes is horrible advice and will make your life unnecessarily hard even in the short run.


text:
Q: Display all predictions and their percentages in the title of a figure Im working on a project in deep learning. I have two variables for storing predictions and their percentages.
This is done using a for loop for every image in a cell array C. Both predictions and percentages are stored in separate column vectors which Ill need for later use
for i=1:size(C)

img=im2uint8(C{i});
img2=imresize(img,[224 224]);
[prediction,pred_val] = classify(n_net,img2)
predictions(i,:)=prediction;
pred_vals(i,:)=pred_val;
figure
imshow(img2)

title(sprintf("%s %s",[labels,num2str(100*pravdepodobnost_predikciesnimky(i,:))]));
end

Now, I want to display all of the predictions and percentages, so lets say the network predicts that image consists of 80%ocean and 20% people, so the title in the figure displays both predictions not just the dominant one. Which is the best way to do this?
Edit: here is a sample for clarification (the titles and labels are in my native language):
labels=string(categories(scenes_training.Labels)') %creates 1x2 string array
labels =
"Pobrežie"    "Ulica"

After one iteration from the for loop above I get this:
prediction = categorical
 Ulica

pred_vals = 1×2 single row vector
0.0046    0.9954

And (after modification) a figure
So my goal is to write the title like this:
Pobrežie 0.45644 %; Ulica 99.5436 %

A: Given the variables described above then you can use sprintf to do what you want.
% Use the dummy data from above
labels = ["Pobrežie", "Ulica"];
pred_vals = [0.0046, 0.9954];
% now format a string to use as a title
img_title=sprintf("%s %s%%; ", [labels', num2str(100*pred_vals')]');
%img_title now equals "Pobrežie  0.46%; Ulica 99.54%; "

Basically sprintf will cycle through all values it is supplied with, repeating the string format until it is done.  You can use this to list the contents of a matrix of data.  Putting the data in a matrix and transposing it is just a way of interleaving the names and the values.
The nested transposing in the sprintf input arguments is just to persuade matlab to deal correctly with the different value types - it is a little hacky but then MATLAB often is.  If I can find a nicer way then I'll update the answer.
If you don't want the final "; " at the end of the string, then you can trim that off with a subsiquent step.


text:
Q: Laravel how do I get info from several Controllers into ONE view I am building an app using Laravel. It has the following structure:
one user -> haOne -> Profile -> hasMany -> Discussions -> HasMany -> Replies HasMany -> Likes
I have as usual one Controller per Model with the typical CRUD functionality: DiscussionController, PaymentController, ImageController, ProfileController, RoleController, PostsControllers, MessageController.
In the Admin area I manage and view all relevant information about each user.
The route in web.php is:
Route::resource('admin-profiles', 'AdminProfileController');

My problem is in the admin.profiles.show view which is served from this method AdminProfileController@show:
public function show($slug)
{
    $profile = Profile::where('slug', $slug)->first();
    $page_name = $profile->name;

    return view('admin.profiles.show', compact('profile', 'page_name'));
}

Here I need all the information concerning a user (profile, discussions, answers to posts, images, likes, payments, channels, etc).
I could build a GIANT show method in the AdminController and pass a whole bunch of variables to that view, like this:
    $discussions = Discussion::where('profile_id', $profile->id)get);
    $replies= Reply::where('profile_id', $profile->id)->paginate(4);
...
    and so on until 27 queries

but it looks to me like a bad solution, since I have already one controller per model.
I did call the UserController like this:
    <span class="mt-3 small pull-right">
Accumulated Likes: {{ $user->profile->all_likes($user->id) }}
</span>

and in the userController I did:
public function all_likes($id) {

    $user = User::find($id);
    $profile = Profile::where('user_id', $user->id);
    $discussions = Discussion::where('profile_id', $profile->id)->get();
    $replies = array();
    $all_likes = "";
    foreach ($discussions as $discussion) {
        foreach ($discussion->replies as $reply) {
            $all_likes = $all_likes + count($reply->likes);
        }
    }

    return $all_likes;
}

But it did not work.
How do I call methods in different controllers from a HTML view?

A: If you have everything built on relationships, then use them
one user -> hasOne -> Profile -> hasMany -> Discussions -> HasMany -> Replies -> HasMany -> Likes
one user -> hasOne -> Profile
in UserModel:
public function profile()
{
  return $this->hasOne(ProfileModel::class);
}

and in Controller:
$user->profile;

in ProfileModel:
public function discussions()
{
  return $this->belongsToMany(DiscussionsModel::class, ... youre fields);
}

// similar to the following relationships Replies
and in Controller :
$profile->discussions;

$user->profile; //it's Collections relationships one by one
$user->profile->discussions; //it's Collections relationships hasMany
$user->profile->discussions->first()->replies; //replies to first user discussions. you can go foreach. and so on

and in view :
Controller
public function show(int $id)
{
    $user = UserModel::find($id);

    return view('admin.profiles.show', [
      'user' => $user
    ]);
}

View
<body>
    {{ $user->profile; }}
    {{ $user->profile->discussions; }}
    {{ $user->profile->discussions->first()->replies; }}
</body>

A: The best way to do this is to use resources and collections.
E.g. you can create resources for a user with these commands:
php artisan make:resource UserResource
php artisan make:resource UserCollection
then you include it into your controller, by importing it like so:
use App\Http\Resources\UserCollection;
In your method, you can return something like this:
return new UserCollection(User::all());
The second last step is to make sure you have correctly defined relationships inside your models:
for example, in the User model:
public function discussions() {
   return $this->hasMany(Discussion::class);
}
public function profile() {
   return $this->belongsTo(Profile::class);
}

final step is to call this relationship in your resource, so in your resource, you will be returning like so:
return [
    'id' => $this->id,
    'profile' => $this->profile, // model relationship
    'discussions' => $this->discussions, // model relationship
];

with this method, you can do it for all your relationships you need to get for a user.
Lastly, the best practice is to use whenLoaded for a relationship inside your resource:
return [
    'id' => $this->id,
    'profile' => $this->whenLoaded('profile'),
    'discussions' => $this->whenLoaded('discussions'),
];

this way it will load the discussions and profile only if with() is used inside the controller:
return new UserCollection(User::with('discussions')->with('profile')->get());

this can also prevent unwanted loops, e.g.
User->discussions->User.... etc.
Hope this helps, good luck with your project :)


text:
Q: How to prove that $X$ is a random variable? I was trying to show a function is a random variable.  But I got confused. I could not identify the process. Can you please tell me how to solve it?
The function was
$$X(\omega)=\begin{cases}\omega &,\text{ if } 0\le \omega\le \frac12 \\\omega-\frac12 &,\text{ if } \frac12<\omega\le1\end{cases}$$
Is $X$ a random variable?

A: It appears that you are taking the basic space to be $[0,1]$ with Borel sigma algebra and you want to prove measurability of $X$ defined by $X(w)=w$ for $0 \leq w \leq \frac  1 2$ and $X(w)=w-\frac  1 2 $ for $\frac  1 2< w \leq   1$ .  You can write $X$ as $YI_A+Z_B$ where $Y(w)=w$ for all $w$,$Z(w)=w-\frac  1 2$ for all $w$ and $A=[0,\frac 1 2],B=A^{c}$. Since $Y$ and $Z$ are continuous they are Borel measurable. $I_A$ and $I_B$ are measurable because $A$ is  a Borel set. Sums of measurable functions and products of measurable functions are measurable. Hence $X$ is measurable.


text:
Q: How to solve greater & less / inequal equation Two farmers, Eric and Josef where talking. "How many sheeps do you have?" asked Eric. "If I divide my sheeps in $2, 3, 4, 5,$ or $6$ groups, there will always be 1 sheep left." Josef answered. How many sheeps did Josef have if he had more than $100$, but less than $150$?
How do you solve this with an equation then?
The answer is $121$.

A: We have$$x\equiv1\pmod2$$
$$x\equiv1\pmod3$$
$$x\equiv1\pmod4$$
$$x\equiv1\pmod5$$
$$x\equiv1\pmod6$$
Using Chinese remainder theorem we have
$$x\equiv1\pmod{60}\implies x=60k+1$$
where $k\in\mathbb N$
Now I'll leave it to you!

A: Because the remainder is always $1$, we need to find $ n+1,$ where n divides $2\cdots6$. It is a factor of the LCM, that is, $60$. Becuase $2\cdot60+1$ is the only number in the range $100\le x \le 150$, $121$ is your answer.

A: all equations are the same and they say $x-1=x-1$ after cancelling the common numerators, therefore we get all solutions $x$ with $100<x<150$


text:
Q: React application with users roles I started working with React/Redux about 2 months ago and I want to make an application with user roles. When a user logs in I want to change my Route component:
<Route path={"/"} component={MainPage}></Route>

To component
<Route path={"/"} component={MainPageUser}></Route>

If admin
<Route path={"/"} component={MainPageAdmin}></Route>

But if I make a switch with my Router I get the error
Warning: [react-router] You cannot change <Router routes>; it will be ignored

I want make access based on the type of account.

A: One option is to create a single component for the / path, and within that component return a different component based on the user role.
<Route path={"/"} component={Home} userRole={userRole}></Route>

class Home extends React.Component {
  render() {
    return this.props.userRole === "admin" ? <HomeAdmin /> : <HomeVisitor />;
  }
}

A: I recommend you rootPageComponent wrapping the switchs.
How about this?
(Below is a just simple sample code. Please note that it does not work correctly)
<Route path={"/"} component={RootPage}></Route>

// RootPage.js
export default const RootPage({role}) => {
    switch(role) {
        case USER: return <MainPageUser />
        case ADMIN: return <AdminPage />
        default: return <MainPage />
    }
}


text:
Q: Can not upload file to the text field(there is hidden file field) I have trouble with file upload. Introducing everything step-by-step.
I have one file upload in the form. But the field's type is text. But in the back, there is a hidden field, that its type is a file upload.
Visible field (text field):

                         Please provide bank account statement                         <input _ngcontent-ete-c120="" type="text" readonly="" class="form-control ng-untouched ng-pristine ng-valid">
 –

Hidden field
<input _ngcontent-juf-c120="" type="file" ng2fileselect="" class="uploader" accept="application/pdf,application/acrobat,application/nappdf,application/x-pdf,image/pdf,image/jpeg,image/pjpeg,image/png">

I make a hidden field and can add files with invoke-command. But the file's name doesn't written in the text field that I see. That is why can not pass the form. You can see the hidden field at the top where I added the file. Also, the text field that I am uploading file from UI. The file's name I must in this field.
UI Screenshot

A: Do you use libraries like "cypress-file-upload" ? Its really good and i haven't had issues with it so far.


text:
Q: For Hive partition based on date, why use string type? why not int? If I'm defining a table in Hive, and will be partitioning based on date, and my dates are in the format YYYYMMDD, which should I choose for the type, int or string?
If it was just a field, and therefore in the files I'm supplying for the table, I could see using a string, even if only so that I can search for and identify malformed entries that might work their way into my data. But since I will be specifying the partition as part of the load process, I know I'll always have correctly formed values.
When used in a Where clause, the partition field will normally be equality or less-than/greater-than logic.

A: Dates are typically treated as strings in Hive. If you look at all the date manipulation UDFs available, they use string types, so if you were using integers you would have to cast them every time.
Conceptually also I think it makes more sense to use strings, your YYYYMMDD is just a literal representation of a date object, but it is implicitly equivalent to something like YYYY-MM-DD or DDMMYYYY. So if you were using an integer here, it becomes painful to do such comparisons.
Note that you can also compare strings in Hive with equality/greater/lower-than operators, if you want to select a range of partitions you can easily do that with these operators.
The only case I would see using a "date" as an integer is using a timestamps (Unix-style) because it is a continuous value and represents a real measurable quantity.

A: Because YYYY-MM-DD is the standard for date representation and is the output of hive's to_date() UDF
it also allows you to do lazy things like select * from foo where day>'2013'
http://xkcd.com/1179/


text:
Q: d3 table - adding specific hyperlink to value I have a d3-generated table and have added a hyperlink to the value (name) in the first column. How can I make the link specific for each student based on their StudentID. In other words I want the link to be http: //mysite.php?studentid=129508 for the first student, http: //mysite.php?studentid=129562 for the second rather than http: //mysite.php for every student.
var data = [{"StudentID":"129508","FirstName":"Madison", "Math":"69.6","English":"64.1","History":"63.2"},          {"StudentID":"129562","FirstName":"Virginia","Math":"52.7","English":"64.1","History":"82.3"},          {"StudentID":"129770","FirstName":"Lucinda","Math":"93.4","English":"87.9","History":"84.6"},           {"StudentID":"129427","FirstName":"Ella","Math":"62.3","English":"64.1","History":"60.7"},          {"StudentID":"129203","FirstName":"Nicholas","Math":"74.9","English":"66.2","History":"73.2"}];
function tabulate(data, columns) {
    var table = d3.select("body").append("table")
        .attr("style", "margin-left: 100px")
        .style("border-collapse", "collapse")
        .style("border", "2px black solid"),
    thead = table.append("thead"),
    tbody = table.append("tbody");

thead.append("tr")
    .selectAll("th")
    .data(columns)
    .enter()
    .append("th")
        .text(function(column) { return column; });

var rows = tbody.selectAll("tr")
    .data(data)
    .enter()
    .append("tr");

var cells = rows.selectAll("td")
    .data(function(row) {
        return columns.map(function(column) {
            return {column: column, value: row[column]};
        });
    })
    .enter()
    .append("td")
    .attr("style", "font-family: Courier")
    .html(function(d, i) {
                if (i === 0) { return "" + d.value + "";
                } else {return d.value;
                }
        });
return table;
}
var resultsTable = tabulate(data, ["FirstName", "Math", "English", "History"]);

A: Two changes needed.
First you need to store the id as well when you make the data:
var cells = rows.selectAll("td")
        .data(function (row) {
        return columns.map(function (column) {
            console.log(row)
            return {
                column: column,
                value: row[column],
                id: row.StudentID //storing the id
            };
        });
    })

Second link the id in the url
if (i === 0) {
            console.log(d)
            return "" + d.value + "";
        } else {
            return d.value;
        }
    });

Working code here.


text:
Q: Wcf : Where are all the responses going? I have some REST web services implemented like this :
[ServiceContract]
public interface IRESTService
{
    [WebGet(UriTemplate = "GetEveryone", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    [OperationContract]
    EveryoneDTO GetEveryone();
}

public class RESTService : IRESTService
{
    public EveryoneDTO GetEveryone()
    {
        // [...] Some processing
        return everyone;
    }
}

Where is going my everyone object? I mean, it must happens some things to transform the objects to JSON and send them. My debbugging won't lead me any further.
I'm interested in this because, let's say, I want to process every string contained in every objects I send back (maybe for encoding purposes), how/where would I be able to implement a middleware that intercept every object and be able to alter them easily before sending them?

A: A good solution is to implement a Custom Message Inspector.
There are two interfaces you can implement, depending on client or server side:
IClientMessageInspector for client and IDispatchMessageInspector  for server. You can implement both on same class and assembly and use what is more convenient, because message inspectors are extensions and you can configure (Web.config for  instance) which you want to use.
IDispatchMessageInspector implements AfterReceiveRequest and BeforeSendReply methods, so you can intercept messages when you receive the request and before to send the reply, very usefull to your scenario.
Here is the MSDN message-inspectors documetation
A simple example of implementation:
    public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
    {
        MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);
        request = buffer.CreateMessage();
        var m = buffer.CreateMessage().ToString();
        return null;
    }

Note that you must copy the original message, so you can extract the XML and convert to an object to your pourpose  (log, change, etc)

A: If i understood well, you would like to intercept WCF data output before sending it to your client.
there are various ways of doing that, what's in the link below is one of them :
https://www.codeguru.com/csharp/.net/net_wcf/learn-to-create-interceptors-in-wcf-services.htm
Hope it helps


text:
Q: Calculating the length Can someone break this script in to a few lines so that I know what I am doing?
I understand the code about finding the length of a Polyline, but how to break this into step by step?
Here is the long line script:
a[f[0] for f in arcpy.da.SearchCursor("polyline.shp", 'SHAPE@LENGTH')][0]

and as a beginner I want it something like this:
for f in cursor:
     print("The length of Polyline is", "SHAPE@LENGTH")[0]

But I am not sure if I can get a result from this, and what does [0] do here?

A: You will need something like the following.
with arcpy.da.SearchCursor("polyline.shp", "SHAPE@LENGTH") as cursor:
    for f in cursor:
        print ("The length of the polyline is: ", f[0])

The [0] in this case refers to the the first available field in the cursor ("SHAPE@LENGTH")
If you use a list of fields, they can be accessed by their index in the cursor, e.g.:
with arcpy.da.SearchCursor("polyline.shp", ["SHAPE@LENGTH","OBJECTID"]) as cursor:
    for f in cursor:
        print ("The length of the polyline is: ", f[0], " The Object ID of the polyline is: ", f[1])

To get a list of all the fields which you can then pass into the cursor:
fields = []
field_objects = arcpy.ListFields("polyline.shp")`
for obj in field_objects:
    fields.append(obj.name)

You can then use fields as follows:
with arcpy.da.SearchCursor("polyline.shp", fields) as cursor:
    for f in cursor:
         # access any field by its index (starting at 0)


text:
Q: when is C++ std::foreach useful
Possible Duplicate:
Should I use std::for_each?

I've come from a predominantly C# background, and have used a fairly large number of languages aside from that with foreach loop capabilities.  It seems to me that the need of a function object to provide the functionality to the foreach loop is very... long-winded? within C++.  Other languages just use it as another for loop (but more efficient for the coder as opposed to less efficient).
It is pretty rare that there is a feature in C++ that isn't made as it is for a good reason, so can someone provide me with a specific, real-world example where a for-each loop in C++ would be a better decision than another looping structure (like for, while)?


text:
Q: ngx-slick - slick.js - viewing 3 slides - scrolling only one I am using ngx-slick. I have a slider with
slidesToShow=3 and slidesToScroll=1;
The thing is that when I scroll the carousel, I can scroll with my mouse more than one slide, but then it goes back and scrolls exactly one slide like I set in the config.
Can you show me the direction where to look to LOCK the carousel after scrolling exactly one slide, not being possible to scroll further (just one slide at a time)?
I read a lot of topics on the internet, but nothing really relates to this specific problem.


text:
Q: Uncaught Error: Module name "dist/lib/clientExports" has not been loaded yet for context: _. Use require([]) I am trying to display data using ag-grid in my ASP.NET Web forms application but, I am getting the following error:

require.js:143 Uncaught Error: Module name "dist/lib/clientExports"
  has not been loaded yet for context: _. Use require([])
  http://requirejs.org/docs/errors.html#notloaded

TypeScript file:
require(['node_modules/ag-grid/main', ], function (agGridObj) {
    document.addEventListener("DOMContentLoaded", function () {
        var eGridDiv = document.getElementById('#AllProjectBuildInfoGrid');
        //new ag.grid.Grid(eGridDiv, gridOptions);
        new agGridObj.Grid(eGridDiv, gridOptions);
    });
});
var columnDefs = [
    { headerName: "Make", field: "make" },
    { headerName: "Model", field: "model" },
    { headerName: "Price", field: "price" }
];

var rowData = [
    { make: "Toyota", model: "Celica", price: 35000 },
    { make: "Ford", model: "Mondeo", price: 32000 },
    { make: "Porsche", model: "Boxter", price: 72000 }
];

var gridOptions = {
    columnDefs: columnDefs,
    rowData: rowData
};

earlier, I used NPM to download the ag-grid into my project. What am I doing wrong? How do I reference ag-grid in my typescript file? Any suggestion is appreciated.

A: Cross reference how you are packing with the below link
https://www.ag-grid.com/understanding-packaging-for-javascript-typescript-commonjs-and-everything-else/
Not sure how you reference external JS libs in for non angular TS projects. Have you considered as explained in the below thread.
https://github.com/ceolter/ag-grid/issues/717


text:
Q: java.lang.ClassFormatError: Code attribute in native or abstract methods in class file I'm instrumenting a code with asm library and receive such error. What does it mean? Does anybody know how it can be fixed?
Please, note that i'm skipping interfaces in Agent agentmain method:
if (clazz.isPrimitive() || clazz.isInterface() || clazz.isLocalClass() || clazz.isArray() || clazz.isAnonymousClass() || clazz.isMemberClass() || clazz.isPrimitive()) {
    continue;
}

Error stack:
java.lang.ClassFormatError: Code attribute in native or abstract methods in class file com/mysql/jdbc/ConnectionProperties
    java.lang.ClassLoader.defineClass1(Native Method)
    java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    java.security.AccessController.doPrivileged(Native Method)
    java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    java.lang.ClassLoader.defineClass1(Native Method)
    java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    java.security.AccessController.doPrivileged(Native Method)
    java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    java.lang.ClassLoader.defineClass1(Native Method)
    java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    java.security.AccessController.doPrivileged(Native Method)
    java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:282)
    java.sql.DriverManager.getConnection(DriverManager.java:571)
    java.sql.DriverManager.getConnection(DriverManager.java:215)
    org.apache.jsp.welcome_jsp._jspService(welcome_jsp.java:92)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:723)

A: This issue was resolved.
I skipped an instrumenting for interfaces and abstract classes in Agent agentmain function. However it doesn't work for libraries that loaded during runtime. So this check (if class is interface) should be done inside Agent transform method. I moved that check there and now it works.
Thanks


text:
Q: As per checking vs as per check I always start my email with "As per checking,......" but I found out there is someone else who used to write "As per check,...".
Sentence example :

As per checking, we found out the issue was caused from our side.

In this case, is my sentence wrong? Should I change to check/checked instead? But checking sounds a lot more suitable than check.

A: "As per" is a preposition, meaning according to/in accordance with. 'As per checking' does not sound natural to me. I'd rather use "upon checking."


text:
Q: width doesnt change in a media query rest of the properties change At first the container is given a width of  80% and when this is changed with a media query for a width of 992px it does not change but when the background-color is specified for the same media query it changes.
JSfiddle - https://jsfiddle.net/q4hqq2ro/

HTML

 Spirituality Forums

Register

Login

            X

            <input type="search" class="search">

CSS
    @import url(http://fonts.googleapis.com/css?family=Niconne);

    body{
        background: #e6e3d7;
        font-size: 16px;
    }

    /*-----------------Header----------------------*/

    .container{
        max-width: 80%;
        margin:0 auto;
    }

    header{
        background-color: #b47941;
        padding-left: 1%;
        margin: 0 auto;
        display: block;
    }

    .logo{
        background: url("images/small.jpg") no-repeat;
        width: 150px;
        height:90px;
        float: left;
    }

    header h1 {
        display: inline-block;
        font:200% cursive ;
        color: white;
        line-height: 90px;
        margin-left: 2%;
        color: #daccb7;
        z-index: 2;
    }

    .light{
        color: #f5f3ea;
    }

    .clear{
        clear: both;
        display: inline-block;
    }

    /*---------------register-------------*/

    .register{
        margin-left: 2%;
        margin-right: 2%;
    }

    .user{
        display: inline-block;
        float: right;
        color: white;
        margin-top: 62px;
        background: #e6e3d7;
        width:10%;
        font: 100%/160% arial;
        text-align: center;
        color: #a35800;
        line-height: 187%;
        cursor: pointer;
    }

    /*---------------search-------------*/
    .search{
        display: none;
        position: absolute;
        margin-top: 64px;
        right: 30%;
        width: 18%;
        height: 26px;
    }

    .close{
        color: grey;
        position: absolute;
        top: 68px;
        right: 30%;
        display: none;
        z-index: 2;
        cursor: pointer;
        background: #e6e3d7;
        width: 2%;
    }

    input[type="search"]{
        border: 0;
        color: #a35800;
        background: #e6e3d7;
        padding: .5%;
        -webkit-box-sizing: border-box;
        -moz-box-sizing: border-box;
        box-sizing: border-box;
        font-size: 100%;
    }

    .search-icon{
        background:url("images/search.gif") no-repeat;
        width:32px;
        height:23px;
        display: inline-block;
        float: right;
        margin-right: 2%;
        margin-top: 66.5px;
        cursor: pointer;
    }

    /*-----------advertisment------------*/

    .advertisment{
        height: 320px;
    }

    /*-----------Media Queries----------*/

     @media (max-width : 992px) {

        .container {
            width: 90%;
            background: green;
        }

    }

A: The problem is that you set before:
.container{
  max-width: 80%;
  margin:0 auto;
}

And the media query does not override that. I tested your code, replace either the max-width with just width on the previous line, or use max-width: 90% on the media query. That would do the trick.
Cheers.

A: Its Because your old code is not gets Replaced by new Code
use !important with your new Code
.container{
    max-width: 80% !important;
    margin:0 auto;
}

A: width and max-width are different properties. If you want to deactivate max-width you have to override it to it's initial value of none so width will be the only property that will affect element's width.
.container {
    max-width: none;
}

Reference: MDN - max-width

A: you can use max-width in place of width ,it will work.
in media query width is the only properties that affect.


text:
Q: How can I conditionally sum values from different columns after aggregation? I have this dataframe to begin with:
ID PRODUCT_ID        NAME  STOCK  SELL_COUNT DELIVERED_BY PRICE_A PRICE_B
1         P1  PRODUCT_P1     12          15          UPS   32,00   40,00
2         P2  PRODUCT_P2      4           3          DHL    8,00     NaN
3         P3  PRODUCT_P3    120          22          DHL     NaN  144,00
4         P1  PRODUCT_P1    423          18          UPS   98,00     NaN
5         P2  PRODUCT_P2      0           5          GLS   12,00   18,00
6         P3  PRODUCT_P3     53          10          DHL   84,00     NaN
7         P4  PRODUCT_P4     22           0          UPS    2,00     NaN
8         P1  PRODUCT_P1     94          56          GLS     NaN   49,00
9         P1  PRODUCT_P1      9          24          GLS     NaN    1,00

What I'm trying to achieve is - after aggregating by PRODUCT_ID, to sum PRICE_A or PRICE_B depending on whether they have a value or not (prioritizing PRICE_A if both are set).
Based on @WeNYoBen 's helping answer, I now know how to conditionally apply aggregation functions depending on different columns:
def custom_aggregate(grouped):

    data = {
        'STOCK': grouped.loc[grouped['DELIVERED_BY'] == 'UPS', 'STOCK'].min(),
        'TOTAL_SELL_COUNT': grouped.loc[grouped['ID'] > 6, 'SELL_COUNT'].sum(min_count=1),
        'COND_SELL_COUNT': grouped.loc[grouped['SELL_COUNT'] > 10, 'SELL_COUNT'].sum(min_count=1)
        # THIS IS WHERE THINGS GET FOGGY...
        # I somehow need to add a second condition here, that says
        # if PRICE_B is set - use the PRICE_B value for the sum()
        'COND_PRICE': grouped.loc[grouped['PRICE_A'].notna(), 'PRICE_A'].sum()
    }

    d_series = pd.Series(data)
    return d_series

result = df_products.groupby('PRODUCT_ID').apply(custom_aggregate)

I really don't know if this is possible by using the .loc function.
One way to solve this could be to create an additional column before calling .groupby that already contains the correct price values.
But I thought there might be a more flexible way of doing this.
I'd be happy to somehow apply a custom function for the 'COND_PRICE' value calculation that gets executed before passing the results to sum(). In SQL I could nest x levels of CASE WHEN END statements in order to implement this kind of logic. Just curious about how to implement this flexibility in pandas.
Thanks a lot.

A: So here is the solution we need fillna
def custom_aggregate(grouped):

    data = {
        'STOCK': grouped.loc[grouped['DELIVERED_BY'] == 'UPS', 'STOCK'].min(),
        'TOTAL_SELL_COUNT': grouped.loc[grouped['ID'] > 6, 'SELL_COUNT'].sum(min_count=1),
        'COND_SELL_COUNT': grouped.loc[grouped['SELL_COUNT'] > 10, 'SELL_COUNT'].sum(min_count=1),
        # Fillna if A have the value A return , if not check with B , both nan will keep the value as nan
        'COND_PRICE': grouped['PRICE_A'].fillna(grouped['PRICE_B']).sum()
    }

    d_series = pd.Series(data)
    return d_series