text:
Q: How do I align text in a excel cell with javascript? I am developing an Excell add-in. Using a GUI I am passing two variables to a function. X being the value of the input from the GUI and the other is a location pointer to set the cell. If the value of the input is 7, I want to set the cell horizontal alignment to left. I have tried all kinds of different syntax that I found online but none work, nor do they give an error.
I have tried:
if (x == 7) { range.horizontalAlignment = "left" }
if (x == 7) { range.Excel.horizontalAlignment = "left" }
if (x == 7) { range.format.horizontalAlignment = "left" }
if (x == 7) { range.horizontalAlignment = Excel.horizontalAlignment = "left" }

and some others I don't remember.
    function getValue(x, y) {
        Excel.run(function (context) {
            var text = document.getElementById(x).value;
            var sheet = context.workbook.worksheets.getItem("Sheet1");
            var range;
            if (y == 1) { range = sheet.getRange("F5") };
            if (y == 2) {
                range = sheet.getRange("F9");
                if (x == 7) { range.horizontalAlignment = "left" } // Problem line, I think
            };
            range.values = (text); // Put into cell 'range'
            return context.sync()
        });
}


text:
Q: C# solving with Iteration I need to make code in console  that will make the number of the line appear on the line its self and also its position on the line. My program only outputs one single line of ***** and I cant seem to make it make more. Help would be amazing thanks heaps in advance
eg 1*****
   *2****
   **3***
   ***4**

I currently have,
static void Main(string[] args)
{
    int n = 0;
    string s = "";

    //check if 2 args
    if (args.Length == 2)
    {
        if (int.TryParse(args[0], out n))
        {
            //successful parse, so use n
            s = args[1]; //second argument is character

            //draw a line of characters
            DrawChars(n, s);
        }
        else
        {
            //unsuccessful parse, so no n value
        }
    }

    //wait for user to have read output
    Console.WriteLine();
    Console.Write("Press enter to finish:");
    Console.ReadLine();
}

/// <summary>
/// Method to draw a line of characters
/// </summary>
/// <param name="n">number of characters to draw</param>
/// <param name="s">character to draw n times</param>
static void DrawChars(int n, string s)
{
    for (int i = 1; i <= n; i++)
    {
        Console.Write(s);
    }
    Console.WriteLine();
}

A: Your current code only prints one line.  You need an outer loop to print multiple lines, plus a conditional check to know whether to print the row number or the string in the appropriate column of the line.
Change your DrawChars(int n, string s) to
/// <summary>
/// Method to draw a line of characters
/// </summary>
/// <param name="n">number of characters to draw</param>
/// <param name="s">character to draw n times</param>
static void DrawChars(int n, string s)
{
    for (int row = 1; row <= n; row++)
    {
        for (int col = 1; col <= n; col++)
        {
            Console.Write(col == row ? col.ToString() : s);
        }
        Console.WriteLine();
    }
}

Usage:
DrawChars(5, "*");

Results:
1****
*2***
**3**
***4*
****5

A: If I can understand your requirement properly, you can use nested for loop to print:
static void Main()
        {
            const int maxLineNumber = 5;
            for (var itr = 1; itr <= maxLineNumber; itr++)
            {
                for (var innerItr = 1; innerItr <= maxLineNumber; innerItr++)
                {
                    if (innerItr == itr)
                    {
                        Console.Write(itr);
                    }
                    else
                    {
                        Console.Write("*");
                    }
                }
                Console.WriteLine();
            }
            Console.ReadLine();
        }

It'll print:
1****
*2***
**3**
***4*
****5

redpajama_set_name: RedPajamaStackExchange


text:
Q: Line integral over a lemniscate verification The task is to find $\int_L {x\sqrt{x^2-y^2}}$ds, where $L: (x^2+y^2)^2 = a^2 (x^2 - y^2),\ x\ge0$.
The curve is a right loop of a lemniscate. By tranistioning to polar coordinates I found:
$$r^2 = a^2 (cos^2(\theta)-sin^2(\theta)),\ r'=\frac{-2cos(\theta)sin(\theta)}{\sqrt{cos^2(\theta)-sin^2(\theta)}}$$
Then the integral becomes $\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}} r^2 cos(\theta) \sqrt{cos^2(\theta)-sin^2(\theta)}\sqrt{r^2+(r')^2} d\theta$.
The problem is that after plugging in the value of $r$, I get something increadibly messy and most likely not integrable in elementary functions. And the task is supposed to have an elementary simple answer and actually is aimed at people familiar only with some basics of integration, by far not assuming the knowledge of non-elementary functions and curves like lemniscate.
Maybe I'm missing something obvious? Or it is really that horrible...
Edit: yeah, now I see that my calculations aren't correct

A: Letting $x=r\cos\theta, y=r\sin\theta$ we have that the relation between $r$ and $\theta$ is given by
$$ r^2 = a^2\cos(2\theta) $$
or $r=a\sqrt{\cos(2\theta)}$, for $\theta\in\left[-\frac{\pi}{4},\frac{\pi}{4}\right]$. Given
$$ x=a\cos\theta\sqrt{\cos(2\theta)},\quad y=a\sin\theta\sqrt{\cos(2\theta)} $$
we have
$$ ds = \sqrt{\dot{x}^2+\dot{y}^2}\,d\theta =\frac{a}{\sqrt{\cos(2\theta)}}\,d\theta$$
hence the wanted integral equals
$$ \int_{-\pi/4}^{\pi/4}a\cos\theta\sqrt{\cos(2\theta)}\cdot a\cos(2\theta)\cdot \frac{a}{\sqrt{\cos(2\theta)}}\,d\theta $$
and I guess you can see the nice simplification here. The outcome is
$$ a^3 \int_{-\pi/4}^{\pi/4}\cos(\theta)\cos(2\theta)\,d\theta = \frac{2\sqrt{2}}{3}a^3.$$


text:
Q: How to install system-wide nuget packages? How can I install a nuget package system-wide on visual studio 2015?
I mean, yeah, you can install nuget packages per-project and per-solution... but, is it possible to install them system-wide so they'll be available for sources using vs2015 compiler?
Right now I'm coding some swig c++ modules to be used on python with cmake and having these libraries available system-wide so I can include them like any other system header would be quite convenient.
Just to clarify, the generated project by cmake will be ninja(using vs compiler)+ST (no package manager involved)... but still I'd like to be able of using the goodies provided by nuget to have my library set ready to be used by the swig modules

A: Nuget package management system does not have a "system-wide" install mode.
Downloaded packages are cached, so that you are not forced to re-download them each time for each project/solution referencing them.
You can also specify a path where to put the packages, but as far as I know for C++ projects this has some drawbacks, including the fact that project files are injected with *.props file paths relative to the solution, that causes Nuget system to be hardly usable from same projects included in different solutions at different path levels.
It seems that Microsoft is moving toward a different package manager for C++ native projects, you may want to look at VCPKG on Github.


text:
Q: Uninstalling UserPassChange script I installed a script http://www.googleappsscript.org/home/force-google-apps-users-to-change-password-periodically. Idea was to force Google Apps - users in my organisation to change their passwords every 3 months. Script works well. However, there are certain accounts whose password must remain the same and therefore I would need to uninstall the script.
Would anyone be able to help me out?
Thanks in advance.

A: An alternative method would be to add 3 exceptions to this list using an IF/ELSE statement, and a method to ignore the 3 users. I'll provide you with an example in C#, since that's the language I'm most fluent in:
if (username == "VIP1")
  { ignore(string username)}
else if (username == "VIP2")
  { ignore(string username)}
else if (username == "VIP3")
  { ignore(string username)}
else
  { passchange()}

You'd also need to provide an overload for the user in the ignore() method. If you have a relatively small userbase (under, say, 200 users), this idea would be very effective. If you have a larger userbase, this may be a bit of an expensive process, since you have to run through the entire userlist for each iteration of the if/else statement.

A: Users that installed the script and authorized it have received an email with uninstall instruction. This message shows a link to uninstall the script, this link is easy to re-build if ever they lost it :
 use the link of the script and replace the ending part with /manage/uninstall.
for example, this script url
https://script.google.com/d/1DsMPFCPo-870TuOFM4Sg9BY0c28gyj8NY_________n0upV1AOG2MAsxy/edit?usp=drive_web

would be changed to
https://script.google.com/d/1DsMPFCPo-870TuOFM4Sg9BY0c28gyj8NY_________n0upV1AOG2MAsxy/manage/uninstall

that will direct the user to a page looking like this :


text:
Q: Putting .SVG images into tkinter Frame I have been trying to put the image from https://betacssjs.chesscomfiles.com/bundles/web/favicons/safari-pinned-tab.f387b3f2.svg into a Tkinter frame. I found from the post here that it is possible with the help from rsvg and cairo.
I was using python 3.6 on Windows 10. I got rsvg from here and cairo from here and then extracted the folders to the 'C:\Users...\site_packages' folder. They import fine but I cannot figure out how to use them. I tried using the code:
import tkinter as tk
main=tk.Tk()
frame=tk.Frame(main)
def svgPhotoImage(self,file_path_name):
        from PIL import Image,ImageTk
        import rsvg,cairo
        svg = rsvg.Handle(file=file_path_name)
        width, height = svg.get_dimension_data()[:2]
            surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, int(width), int(height))
            context = cairo.Context(surface)
            #context.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
            svg.render_cairo(context)
            tk_image=ImageTk.PhotoImage('RGBA')
            image=Image.frombuffer('RGBA',(width,height),surface.get_data(),'raw','BGRA',0,1)
            tk_image.paste(image)
            return(tk_image)
    tk_image=self.svgPhotoImage(filename)
    frame.configure(image=tk_image)

and
#rsvg.py
import os
try:
    import rsvg
    WINDOWS=False
except ImportError:
    print"Warning, could not import 'rsvg'"
    if os.name == 'nt':
        print "Detected windows, creating rsvg."
        #some workarounds for windows

        from ctypes import *

        l=CDLL('librsvg-2-2.dll')
        g=CDLL('libgobject-2.0-0.dll')
        g.g_type_init()

        class rsvgHandle():
            class RsvgDimensionData(Structure):
                _fields_ = [("width", c_int),
                            ("height", c_int),
                            ("em",c_double),
                            ("ex",c_double)]

            class PycairoContext(Structure):
                _fields_ = [("PyObject_HEAD", c_byte * object.__basicsize__),
                            ("ctx", c_void_p),
                            ("base", c_void_p)]

            def __init__(self, path):
                self.path = path
                error = ''
                self.handle = l.rsvg_handle_new_from_file(self.path,error)

            def get_dimension_data(self):
                svgDim = self.RsvgDimensionData()
                l.rsvg_handle_get_dimensions(self.handle,byref(svgDim))
                return (svgDim.width,svgDim.height)

            def render_cairo(self, ctx):
                ctx.save()
                z = self.PycairoContext.from_address(id(ctx))
                l.rsvg_handle_render_cairo(self.handle, z.ctx)
                ctx.restore()

        class rsvgClass():
            def Handle(self,file):
                return rsvgHandle(file)

        rsvg = rsvgClass()).
h = rsvg.Handle("box.svg")
s = cairo.ImageSurface(cairo.FORMAT_ARGB32, 100, 100)
ctx = cairo.Context(s)
h.render_cairo(ctx)

After trying those scripts, I kept getting the error message:
AttributeError: module 'rsvg' has no attribute 'Handle'

I am sure I did something wrong in the process but after hours of searching still could not figure out how to get it to work. I also tried installing pycairo (via pip) but got the error message
ERROR: Command "'c:\...\python36-32\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\...\\pip-install-peqhj3x1\\pycairo\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\...\Temp\pip-record-jfozfbuc\install-record.txt' --single-version-externally-managed --compile" failed with error code 1 in C:\...\pip-install-peqhj3x1\pycairo\

I have no clue as to what to do now

EDIT: I was finally able to obtain pycairo from
  https://www.lfd.uci.edu/~gohlke/pythonlibs/ and now  have it working.
  I finally got rsvg to not give me the error message above by referring
  here
  and got the nessary DLL files from
  here. Cairo is
  working fine but RSVG is creating a blank screen. I tried another
  7-liner
  here
  and get the output of a blank file instead of a converted one.
  Evidently RSVG is not working and I think it is an installation issue
  (eg. incorrect .dll's). Help?

If am trying to use cairo and rsvg because they take up little space and are really fast; wand or some other library is not an option. I just want to be able to put an SVG file into a tkinter frame. If anyone knows how install rsvg properly, I'd appreciate knowing.
Any help would be hugely appreciated.
Thank you for any suggestions.

A: I've managed to do it using svglib:
from svglib.svglib import svg2rlg
from reportlab.graphics import renderPDF, renderPM

drawing = svg2rlg("safari-pinned-tab.f387b3f2.svg")
renderPM.drawToFile(drawing, "temp.png", fmt="PNG")

from tkinter import *

tk = Tk()

from PIL import Image, ImageTk

img = Image.open('temp.png')
pimg = ImageTk.PhotoImage(img)
size = img.size

frame = Canvas(tk, width=size[0], height=size[1])
frame.pack()
frame.create_image(0,0,anchor='nw',image=pimg)

tk.mainloop()

A: I have finally managed to convert SVGs with Python 3 and PyCairo on Windows, but without rsvg. Rsvg still won't cooperate, but apparently it is still possible to load SVGs without it.
The installation process is not very straightforward, but hey, it works!

Instructions:
Note that these instructions are Windows-specific. On Linux, one can simply install pycairo via pip and use PyGObject's rsvg.

*

*Download the pycairo .whl file for your Windows installation from https://www.lfd.uci.edu/~gohlke/pythonlibs/.

*Install the downloaded file via pip: pip install /path/to/your/pycairo/whl.whl If that doesn't work, try using a different file from the above link. It may take a few tries.

*Run pip install tinycss cssselect2 defusedxml. This will install the dependacies for the next step.

*Go to https://github.com/Kozea/CairoSVG. Download and extract the cairosvg folder to your site packages folder, enabling your code to import it.

*Go to the cairosvg folder and open the file surface.py.

*Look for the line that says import cairocffi as cairo and replace it with import cairo
That should be enough to use PyCairo on Windows without a C++ compiler. Unfortionately, this still doesn't fix the rsvg issues (instead it replaces rsvg), but at least it works.

Here are some examples of how to use it:
To convert an SVG to a PNG:
import cairosvg
cairosvg.svg2png(url="example.svg", write_to="output.png")

To put an SVG into a Tkinter window without downloading the output:
import cairosvg
import io
import tkinter as tk
from PIL import Image,ImageTk

main=tk.Tk()

image_data = cairosvg.svg2png(url="example.svg")
image = Image.open(io.BytesIO(image_data))
tk_image = ImageTk.PhotoImage(image)

button=tk.Label(main, image=tk_image)
button.pack(expand=True, fill="both")
main.mainloop()

Since it still uses Cairo, this solution is very quick, and has few dependencies.
Hopefully this answer will be useful for anyone reading this in the future!

A: Here is another way to do it:
from pylunasvg import Document
import numpy as np
from urllib import request
from PIL import Image

contents = request.urlopen("https://betacssjs.chesscomfiles.com/bundles/web/favicons/safari-pinned-tab.f387b3f2.svg").read()

document = Document.loadFromData(contents)
bitmap = document.renderToBitmap()

svgArray = np.array(bitmap, copy=False)
img = Image.fromarray(svgArray)

# Insert tkinter code here

Disclaimer: I wrote the bindings for the library, here is the github link: pylunasvg and link to the original library written in c++: lunasvg


text:
Q: Mean of iid uniform RVs on the cube roots of 1 If $Y_{n} = \Sigma_{i=1}^{n}X_{i}$,
where $X_{1}, X_{2}, \dots X_{n}$ are iid uniformly distributed on the three cube roots of 1,
We want to show that $\frac{Y_{n}}{\sqrt{n}}$ converges in distribution to a multivariate Gaussian and find its covariance matrix.
Why would this be multivariate? Isn't an instantiation of each $X_{i}$ simply a real or complex number (i.e. one of 1, $-1/2+\frac{\sqrt-3}{2}$, $-1/2-\frac{\sqrt-3}{2}$)?

A: It is multivariate if you consider the real and imaginary parts separately.  You are expected to show that each one converges to a normal distribution and find the mean, variance, and correlation coefficient.


text:
Q: How to have string from "a" and increase each time generate a new instance I have this bit of code here trying to get a string from a, increase every time a new instance is created.
class TypeVariable{
    private static int variable_id = 96;
    private static String variable_name;

    public TypeVariable(){
        variable_id++;
        variable_name = String.valueOf((char)variable_id);
        }

    @Override
    public String toString() {
        return this.variable_name;
    }
}

but when I do this
TypeVariable one = new TypeVariable();
TypeVariable two = new TypeVariable();
TypeVariable three = new TypeVariable();
System.out.println(one);
System.out.println(two);
System.out.println(three);

the output is:
c
c
c

instead of:
a
b
c

what can i do to make it right? thanks

A: Make variable_name non-static, private String variable_name;.
The problem with static is that your variable is shared between instances. Hence if you do :
TypeVariable one = new TypeVariable();
System.out.println(one);
TypeVariable two = new TypeVariable();
System.out.println(two);
TypeVariable three = new TypeVariable();
System.out.println(three);

Then it will work. However, with your previous code, you first instantiated the variables, hence, the constructor did variable_id++; each time. Afterwards, you change variable_name, since it is shared between instances (static) all instances will see the updated variable_name.

A: You are printing the static field variable_name so you always will get the same if you do the printing after creation of the instances.
You probably want to change it to instance field:
private String variable_name;

A: is working but you are not considering that variable_name is static too, so if you need that static then consider the time you print it...
TypeVariable one = new TypeVariable();
System.out.println(one);

TypeVariable two = new TypeVariable();
System.out.println(two);

TypeVariable three = new TypeVariable();
System.out.println(three);

but if you remove the static keyword then you can do:
TypeVariable one = new TypeVariable();
TypeVariable two = new TypeVariable();
TypeVariable three = new TypeVariable();
System.out.println(one);
System.out.println(two);
System.out.println(three);


text:
Q: How do I render a nested data structure with Node.js/Jade In my .js file I have the following data structure
var menu = { "Sport":"Racing",
    "Region":{
        "AUS":{ "name":"APrk", "key":"1234" },
        "GB":{ "name":"Cran", "key":"5678" }
    }
};
res.render('layout.jade', {locals: {menu: menu}});

In my layout.jade I have the following
for item in menu
  p= item

This produces the following output

Racing
[object Object]

Which is on the right track.  What I would like to know is how can I access the nested structures?

A: I believe you're looking for this
// layout.jade
each value, key in locals.menu
  // may nest more iteration
  each v, k in value

Iteration of object key/value does not grantee order. You may want to use array.
Details: https://github.com/visionmedia/jade#a9


text:
Q: Rewrite a script so it takes option arguments to control its behaviour I created a script and it moves files with different extensions to their specified directories.
If the directory is not there, it creates another one (where the files will go), and it creates another directory where the remaining files with different extensions will go.
My first problem is that I want when I put -d and full path on the terminal it should move only media files, -l and full path to move all text files, then -x to change the extension to uppercase, then -u to lowercase.
Can somebody modify it for me and show me how to overcome this problem?
#!/bin/bash
From="/home/elg19/lone/doc"
To="/home/elg19/mu"
WA="/home/elg19/du"
MA="/home/elg19/dq"
WQ="/home/elg19/d2"

# this function checks if the directory exits and creates one if it does not then moves all doc files

function mama(){
if [[ ! -d "$WA" ]]; then
      mkdir -p "$WA"
fi
cd "$From"
for i in pdf txt doc; do
  find . -type f -name "*.${i}" -exec mv "{}" "$WA" \;
done
}

# this function checks if the directory exits and creates one if it does not then moves all media files

function so(){
if [[ ! -d "$To" ]]; then
      mkdir -p "$To"
fi
cd "$From"
for i in mp3 mp4 swf; do
  find . -type f -name "*.${i}" -exec mv "{}" "$To" \;
done
}

# this function checks if the directory exits and creates one if it does not then moves all image files

function soa(){
if [[ ! -d "$MA" ]]; then
      mkdir -p "$MA"
fi
cd "$From"
for i in jpg gif png; do
  find . -type f -name "*.${i}" -exec mv "{}" "$MA" \;
done
}

# this function checks if the directory exits and creates one if it does not then moves all the remaining files

function soaq(){
if [[ ! -d "$WQ" ]]; then
      mkdir -p "$WQ"
fi
cd "$From"
for i in *; do
  find . -type f -name "*.${i}" -exec mv "{}" "$WQ" \;
done
}
mama
so
soa
soaq

A: I don't know if the options suggested are mnemonic in your native language, but they are counter-mnemonic in English.  I would suggest something more like:
-m path    Move media files
-t path    Move text files
-u         Change extensions to upper-case
-l         Change extensions to lower-case

The command to use for regular argument parsing like this is getopts (plural - many systems also have a command getopt, singular, which has different characteristics altogether).
The referenced page gives an example of how to use it:

The following example script parses and displays its arguments:

aflag=
bflag=
while getopts ab: name
do
    case $name in
    a)    aflag=1;;
    b)    bflag=1
          bval="$OPTARG";;
    ?)   printf "Usage: %s: [-a] [-b value] args\n" $0
          exit 2;;
    esac
done
if [ ! -z "$aflag" ]; then
    printf "Option -a specified\n"
fi
if [ ! -z "$bflag" ]; then
    printf 'Option -b "%s" specified\n' "$bval"
fi
shift $(($OPTIND - 1))
printf "Remaining arguments are: %s\n" "$*"

The option -a doesn't take an argument; the option -b requires an argument.


text:
Q: Selenium .GetAttribute("value") for Input is returning empty I have a web app using AngularJs.  I am testing it using specflow and Selenium. I had it working just fine till the other day I saw it failing on getting the values.  element.SendKeys(value) is working and I see the text in the textbox when it runs.
however when it calls element.GetAttribute("value"); it returns an empty string.  I tried seeing if the value wasn't beeing set till it lost focus by sending a tab hit after the value but that didn't help.
I have been googling but everything I find says to use .GetAttribute("value"); and thats what I am using.
Thanks in advance


text:
Q: PGSQL - Change all columns of a specific datatype to text I'm trying to change all the USER-DEFINED columns to TEXT in a specific view using pgsql.
Is it possible to do that in a single alter table query ou do I need to check first what columns contain that dataype and then perform the dataype change one by one?
This is what I'm trying:
ALTER TABLE if exists "schemaName"."Table_A"
ALTER COLUMN (
select column_name
from information_schema.columns inf
where table_name = 'Table_A' and inf.data_type = 'USER-DEFINED')
TYPE TEXT;

I'm getting and error in the subquery start "("

A: You need to do this one by one. Generally speaking such DDL statements cannot work on several objects in one statement.
For ALTER TABLE, see: https://www.postgresql.org/docs/12/sql-altertable.html.
FOR ALTER VIEW, see: https://www.postgresql.org/docs/current/sql-alterview.html


text:
Q: Prolog list and filtering I have a problem with a Prolog exercise. I'm trying to study Computer Science alone at my home, and I'm doing a series of exercises I've taken from the Internet.
The question is the following;

Construct a predicate called filteringPairsAtoms/3 so that given an atom (first argument), and a list of pairs, unify a third parameter with the filtered list of pairs by selecting only the pairs that have the first component as the atom of the first argument.

Example
filteringPairsAtoms(sA,[[basA,absAb],[ab,bbsA],[sA,abbsB],[bsA,sAsB],[sA,bb]],X)

must result in
X = [[sA,abbsB],[sA,bb]]

I'm trying to solve it but I don't have anyone to ask, because I'm learning alone, and don't have a professor to write to or something.
Any help is welcome.
Thanks!!!

A: You can start from what you already have:
filteringPairsAtoms(sA, [[basA,absAb],[ab,bbsA],[sA,abbsB],[bsA,sAsB],[sA,bb]], X) :-
    X = [[sA,abbsB],[sA,bb]].

That's as good a start as any. But we know more: it must be the case that
filteringPairsAtoms(sA, [[sA,abbsB],[bsA,sAsB],[sA,bb]], X) :-
    X = [[sA,abbsB],[sA,bb]].

%% and
filteringPairsAtoms(sA, [[bsA,sAsB],[sA,bb]], X) :-
    X = [[sA,bb]].

%% and
filteringPairsAtoms(sA, [[sA,bb]], X) :-
    X = [[sA,bb]].

%% and
filteringPairsAtoms(sA, [], X) :-
    X = [].

Comparing the sequential clauses, we also notice that it must be
filteringPairsAtoms(sA, [[sA,abbsB] | [[bsA,sAsB],[sA,bb]] ], X) :-
    sA = sA,
    X = [[sA,abbsB] | Y],
    filteringPairsAtoms(sA, [[bsA,sAsB],[sA,bb]], Y).

(this is just the first two clauses from above, combined); and
filteringPairsAtoms(sA, [[bsA,sAsB] | [[sA,bb]] ], X) :-
    dif( sA, bsA),
    X = Y,
    filteringPairsAtoms(sA, [[sA,bb]], Y).

All that's left for you to do, is generalize this by replacing concrete terms with logical variables. Like this:
filteringPairsAtoms(SA, [Head | Tail ], X) :-
    Head = [BsA, _]
    dif( SA, BsA),
    X = Y,
    filteringPairsAtoms(SA, Tail, Y).

and carry this out fully to the end.


text:
Q: Lock sessions to the IP address from which they originated After enabling "Lock sessions to the IP address from which they originated" still able to login to workbench in same session and callouts are also working.
Didn't understand the working of it.How does it affect callouts,exposed REST services from salesforce and workbench sessions?

A: According to the definition

Lock sessions to the IP address from which they originated

Determines whether user sessions are locked to the IP address from which the user logged in, helping to prevent unauthorized persons from hijacking a valid session.
Since you are already using same machine to access Salesforce and workbench and other things thats why it is taking the same session.
You cannot use this session Id from different machine to login.
By the way, if you want to revoke those sessions then go to user record and revoke under OAuth Connected Apps.

A: *

*connect to wifi

*login to salesforce

*disconnect current wifi network and connect with other wifi network

*now try to access salesforce. You have to login in again with current wifi network


text:
Q: How to handle time consuming webservice operation through Javascipt Callbacks I have the following operation to so in one of my Web applications. I have a function that returns a value. This value should be passed to a web service method that runs separately to my web application. This web service operation takes some time to complete, so this has to be run in the background and should return a message once it is completed. I wanted to do this through Javascript callbacks. The basic flow of the code is as follows;
 Dim shr_intfB_Common_LCI As clsCreamsCommon
 Dim stringResult As StringResult
 shr_intfB_Common_LCI = New clsCreamsCommon
 Call shr_intfB_Common_LCI.CreamsBooking(clsTapsCreamsPropsDtl,
                               intRetCode, strMessage, intRequestId
                               )

// This intRequestId needs to be passed to the following web service.
Do
   Threading.Thread.Sleep(10 * 1000) '10 Second
   stringResult = objService.CheckRequestStatus(objServiceUser, intRequestId)
   Loop Until stringResult Is Nothing Or stringResult.ReturnCode <> 2

//The stringResult includes the followings which I have to display.
MessageBox(Me, stringResult.ReturnCode, stringResult.ReturnData + stringResult.ReturnMessage)

I want to do this without using Threads or Task since this is a web application, but using JavaScript callbacks. Please help out me on this.

A: To establish a call back function in JavaScript you can use jQuery ajax or PageMethods call
Both option will run separately, once the web method complete execution, will return,either success or failure call back
PageMethods in JavaScript
https://www.codeproject.com/Questions/631342/Calling-csharp-function-in-javascript


text:
Q: Java ProcessBuilder: curl: (1) Protocol "'https" not supported or disabled in libcurl I'm trying to call a cUrl command within Java to an https url.
I'm simply using the following:
ProcessBuilder pb = new ProcessBuilder("curl", "-X", "GET", "https://...");
Process p = pb.start();

The errorStream prints the following:
curl: (1) Protocol "'https" not supported or disabled in libcurl

But if I execute the cUrl command in the terminal, it answers without any problem.
I also tried the following:
pb = new ProcessBuilder("curl", "-V");

which returns:
curl 7.54.0 (x86_64-apple-darwin16.0) libcurl/7.54.0 SecureTransport zlib/1.2.8
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp smb smbs smtp smtps telnet tftp
Features: AsynchDNS IPv6 Largefile GSS-API Kerberos SPNEGO NTLM NTLM_WB SSL libz UnixSockets

I don't understand why the command works in the terminal, but not in Java context.

A: I've found the cause.
I've noticed that my original command had apexes in the url argument, like this:
pb = new ProcessBuilder("curl", "-X", "GET", "'https://www.google.com'");

The apex cause the error above.
The solution is removing any apex in each argument, and it works perfectly.


text:
Q: Possible to see a list + CPU use of all user processes in a locked down Windows environment? We work in a locked down privilege environment, to the point that we are not able to see the the list of processes and CPU usage of the windows services running on one of our development servers through the Task Manager.
Is there another (command line for instance) tool that we could use on Windows Server to get a list of all processes running on the machine + CPU usage, even with the Task Manager's disabled "Show processes from all users" checkbox locked down?

A: You could try Sysinternals Process Explorer.
If you can get the Cygwin cygwin1.dll and the ps executable together, you might be able to do
ps -Wafl


text:
Q: Getting values of elements passed in data attribute through JQuery I have some field names populated in the data element.  I'm trying to form a query string with the field names and their corresponding values in the form for using in jquery ajax.  The following code however, does not work for me.
$(".linkedfill").change(function(){
  var params = $(this).data("select-params").split(",");
  $.each(params, function(index,value){
     pname = value.slice(value.IndexOf("["), value.IndexOf("]"));
     pval = $(this).parents().find("[name='"+value+"']").val();
     addparams = addparams + "&" + pname + "=" + pval;
  });
});

The field name will be like header['fldname'] and the field is available somewhere in the same form.  The data-select-params will be like data-select-params="header['fld1'],header['fld2']".
Update : My html for fields would look like this:
<input name='header[fld1]' />
<input name='header[fld2]' />
<select class='linkedfill' name='pselect' data-select-params="header[fld1],header[fld2]">
  <option value="opt1">Option 1</option>
  <option value="opt2">Option 2</option>
</select>

What am trying to do with jquery is get the values of header[fld1] & header[fld2] and form a query string out of the data.
Can anyone help me fix this?  Thanks in advance.

A: Why don't you make an array of parameters , like :
//if you need you can iterate the header[h1]..header[hn] push inside the function below
$('.linkedfill').data('select-params', ["header[h1]","header[h2]",...,"header[hn]"]);

and then access it with
$.each($('.linkedfill').data() , function() {
 console.log($('.linkedfill').data());
// ..do your stuff..
})

here is it a fiddle http://jsfiddle.net/DgbRn/

A: Try this:
var data="header['fld1'],header['fld2']";
var params = data.split(",");
var addparams='';
$.each(params, function(index,value){
     console.log(value.indexOf("['")+','+value.indexOf("']")+','+value);
     pname = value.substring(value.indexOf("['")+2, value.indexOf("']"));
     pval = $('form').find("header["+pname+"]").val();
     addparams = addparams + "&" + pname + "=" + pval;
     console.log(addparams);
});

Fiddle: http://jsfiddle.net/Ju297/1/
I don't know what you want but you can make it simple like,
var data="fld1,fld2";
var params = data.split(",");
var addparams='';
$.each(params, function(index,value){
     pval = $('form').find("header["+value+"]").val();
     addparams = addparams + "&" + value + "=" + pval;
     console.log(addparams);
});


text:
Q: Is it possible to send the result of a cut command to a pre defined directory? I'm currently learning how to code shell scripts and as part of the assignment I need to sort the files I've been given into different directories based on the date inside the file.
The date is on the first line of the file and all of the functionalities have to be inside the same script.
My current idea is to translate into the format required and then to create multiple directories with a mkdir -p function, then use cut to select the section of the date that I want to highlight in the data and return them, ideally I want to be able to now take these outputs from the SelectYear, SelectMonth and SelectDay function and put those files into the corresponding directories that I already set up with the CreateAllDirectories function.
Is this possible?
Here is the end result that I need to achieve with this script, making a directory for each year that appears in the files, then in each of these year directories making another directory for the months, then inside the months directory having a directory for the days, followed by a list of all files which contain that exact date inside them like this:
[~/filesToSort] $ ls -R
.:
2000  2001  2002  2003  2004  2005  2006  2007  2008  2010  2011  2012  2013  2014  2015  2016  2017  2018  2019

./2000:
02  03  04  09  10  11  12

./2000/02:
09

./2000/02/09:
ff_1646921307 ….

Currently this is the script I have:
#!/bin/bash

#Changes the date format from YYYY-MM-DD to YYYY/MM/DD

function ChangeSeperater{
head -n 1 ~/filesToSort/ff_* | tr '-' '/'
}

#Makes multiple directories
function CreateAllDirectories{
mkdir -p /year/month/day
}

#Cuts year from file
function SelectYear{
head -n 1 ~/filesToSort/ff_* | cut -c1-4
}

#Cuts month from file
function SelectMonth{
head -n 1 ~/filesToSort/ff_* | cut -c6-7
}

#Cuts day from file
function SelectDay{
head -n 1 ~/filesToSort/ff_* | cut -c9-10
}

EDIT: Thanks for all the help!
Here is the finished script in case anyone is interested:
#!/bin/bash

#Changes the date format from YYYY-MM-DD to YYYY/MM/DD

#Change Seperator function, gets the date from its parameter, changes the date from YYYY-MM-DD to YYYY/MM/DD
function ChangeSeperator() {
    echo "$1" | tr '-' '/'
}

#Sorts the files into the correct directories, cuts the entire date from the file and turns it into a directory, uses the ChangeSeperator function from earlier make the parent directory and all sub directories
for file in  ~/filesToSort/ff_*
do
    directory=$(ChangeSeperator $(head -c 10 "$file"))
    mkdir -p "$directory"
    mv "$file" "$directory"
done

A: First you'll probably need a loop somewhere to sieve through all the files and you might consider processing them one by one.
As for the date, you should probably look in the documentation for date that can give you most of your information right there.
By example :
date -d 2018-07-01 +"%Y/%m/%d"
2018/07/01

and by the way you can always do something like :
d=$(date -d 2018-07-01 +"%Y/%m/%d")
echo "d="$d
d=2018/07/01
mkdir -p $d

Hope it's enough pointer...not here to do your assignement :)

A: You don't need all those functions, just the one to translate the date from yyyy-mm-dd to the pathname yyyy/mm/dd should be enough.
for file in  ~/filesToSort/ff_*
do
    directory=$(ChangeSeperator $(head -c 10 "$file"))
    mkdir -p "$directory"
    cp "$file" "$directory"
done

The ChangeSeperator function needs to get the date from its parameter:
ChangeSeperator() {
    echo "$1" | tr '-' '/'
}


text:
Q: Alphabetize Multiple Drop-Down List Boxes I have an Infopath form which has several drop-down lists. These drop-down lists are being fed from a separate list (separate from the list being posted to). I need to have each of these drop-down lists to be alphabetized. Through the instructions in this post, I am able to get the first drop-down alphabetized, but then how do I get subsequent drop-downs alphabetized?
Can I utilize separate list views, sort the list ascending on the column, then attach this as a separate data connection to feed the proper drop-down list? If this does work, is it the most efficient way to make it happen (if I can create separate data connections from the same list ... not even sure if I specify a view on this or just the list itself)?

A: Each drop-down that feeds external data should have a data connection that you can sort by. You can have multiple data connections to the same location (with different sort order)...


text:
Q: Laravel 8 application - Unable to reach the site when i try to download zipped file I am new to the forum, I hope I have complied with all the forum guidelines in posting my answer.
In my web application that I am developing with Laravel 8, I need to download .zip files
To do this, looking online I decided to use the maennchen/zipstream-php package.
For the creation of the zip I followed the guidelines of the package documentation and then download the newly created .zip.
But as in the title, when from my view I click on the download file button I get the error message Unable to reach the site.
This is my code but I can't figure out what this error is coming from.
public function exportZipFile(Request $request){

            // create a new zipstream object
            $zip = new \ZipStream\ZipStream('example.zip', $options);

            // create a file named 'hello.txt'
            $zip->addFile('hello.txt', 'This is the contents of hello.txt');

            // add a file named 'some_image.jpg' from a local file 'path/to/image.jpg'
            $zip->addFileFromPath('some_image.jpg', 'path/to/image.jpg');

            // add a file named 'goodbye.txt' from an open stream resource
            $fp = tmpfile();
            fwrite($fp, 'The quick brown fox jumped over the lazy dog.');
            rewind($fp);
            $zip->addFileFromStream('goodbye.txt', $fp);
            fclose($fp);

            $response = Response::create(200);
            $response->header('Content-Type', 'application/zip');
            $response->header('Cache-Control', 'public');
            $response->header('Content-Disposition', 'attachment; filename="file.zip"');

            return $response()->stream(function() use ($zip){
                $zip->finish();
            });

}

I appreciate any advice or suggestions
Thanks in advance to everyone


text:
Q: Find intersection points for two stock timeseries Background
I am trying to find intersection points of two series. In this stock example, I would like to find the intersection points of SMA20 & SMA50. Simple Moving Average (SMA) is commonly used as stock indicators, combined with intersections and other strategies will help one to make decision. Below is the code example.
Code
You can run the following with jupyter.
import pandas as pd
import matplotlib.pyplot as plt

%matplotlib inline

datafile = 'output_XAG_D1_20200101_to_20200601.csv'
#This creates a dataframe from the CSV file:
data = pd.read_csv(datafile, index_col = 'Date')

#This selects the 'Adj Close' column
close = data['BidClose']
#This converts the date strings in the index into pandas datetime format:
close.index = pd.to_datetime(close.index)
close

sma20 = close.rolling(window=20).mean()
sma50 = close.rolling(window=50).mean()

priceSma_df = pd.DataFrame({
      'BidClose' : close,
      'SMA 20' : sma20,
      'SMA 50' : sma50
     })

priceSma_df.plot()
plt.show()

Sample Data
This is the data file used in example output_XAG_D1_20200101_to_20200601.csv

Date,BidOpen,BidHigh,BidLow,BidClose,AskOpen,AskHigh,AskLow,AskClose,Volume
01.01.2020 22:00:00,1520.15,1531.26,1518.35,1527.78,1520.65,1531.75,1518.73,1531.73,205667
01.02.2020 22:00:00,1527.78,1553.43,1526.72,1551.06,1531.73,1553.77,1528.17,1551.53,457713
01.05.2020 22:00:00,1551.06,1588.16,1551.06,1564.4,1551.53,1590.51,1551.53,1568.32,540496
01.06.2020 22:00:00,1564.4,1577.18,1555.2,1571.62,1568.32,1577.59,1555.54,1575.56,466430
01.07.2020 22:00:00,1571.62,1611.27,1552.13,1554.79,1575.56,1611.74,1552.48,1558.72,987671
01.08.2020 22:00:00,1554.79,1561.24,1540.08,1549.78,1558.72,1561.58,1540.5,1553.73,473799
01.09.2020 22:00:00,1549.78,1563.0,1545.62,1562.44,1553.73,1563.41,1545.96,1562.95,362002
01.12.2020 22:00:00,1562.44,1562.44,1545.38,1545.46,1562.95,1563.06,1546.71,1549.25,280809
01.13.2020 22:00:00,1545.46,1548.77,1535.78,1545.1,1549.25,1549.25,1536.19,1548.87,378200
01.14.2020 22:00:00,1545.1,1558.04,1543.79,1554.89,1548.87,1558.83,1546.31,1558.75,309719
01.15.2020 22:00:00,1554.89,1557.98,1547.91,1551.18,1558.75,1558.75,1548.24,1554.91,253944
01.16.2020 22:00:00,1551.18,1561.12,1549.28,1556.68,1554.91,1561.55,1549.59,1557.15,239186
01.19.2020 22:00:00,1556.68,1562.69,1556.25,1560.77,1557.15,1562.97,1556.61,1561.17,92020
01.20.2020 22:00:00,1560.77,1568.49,1546.21,1556.8,1561.17,1568.87,1546.56,1558.5,364753
01.21.2020 22:00:00,1556.8,1559.18,1550.07,1558.59,1558.5,1559.47,1550.42,1559.31,238468
01.22.2020 22:00:00,1558.59,1567.83,1551.8,1562.45,1559.31,1568.16,1552.11,1564.17,365518
01.23.2020 22:00:00,1562.45,1575.77,1556.44,1570.39,1564.17,1576.12,1556.76,1570.87,368529
01.26.2020 22:00:00,1570.39,1588.41,1570.39,1580.51,1570.87,1588.97,1570.87,1582.33,510524
01.27.2020 22:00:00,1580.51,1582.93,1565.31,1567.15,1582.33,1583.3,1565.79,1570.62,384205
01.28.2020 22:00:00,1567.15,1577.93,1563.27,1576.7,1570.62,1578.22,1563.61,1577.25,328766
01.29.2020 22:00:00,1576.7,1585.87,1572.19,1573.23,1577.25,1586.18,1572.44,1575.33,522371
01.30.2020 22:00:00,1573.23,1589.98,1570.82,1589.75,1575.33,1590.37,1571.14,1590.31,482710
02.02.2020 22:00:00,1589.75,1593.09,1568.65,1575.62,1590.31,1595.82,1569.85,1578.35,488585
02.03.2020 22:00:00,1575.62,1579.56,1548.95,1552.55,1578.35,1579.87,1549.31,1556.4,393037
02.04.2020 22:00:00,1552.55,1562.3,1547.34,1554.62,1556.4,1562.64,1547.72,1556.42,473172
02.05.2020 22:00:00,1554.62,1568.14,1552.39,1565.08,1556.42,1568.51,1552.73,1567.0,365580
02.06.2020 22:00:00,1565.08,1574.02,1559.82,1570.11,1567.0,1574.33,1560.7,1570.55,424269
02.09.2020 22:00:00,1570.11,1576.9,1567.9,1571.05,1570.55,1577.25,1568.21,1573.34,326606
02.10.2020 22:00:00,1571.05,1573.92,1561.92,1566.12,1573.34,1574.27,1562.24,1568.12,310037
02.11.2020 22:00:00,1566.12,1570.39,1561.45,1564.26,1568.12,1570.71,1561.91,1567.02,269032
02.12.2020 22:00:00,1564.26,1578.24,1564.26,1574.5,1567.02,1578.52,1565.81,1576.63,368438
02.13.2020 22:00:00,1574.5,1584.87,1572.44,1584.49,1576.63,1585.29,1573.28,1584.91,250788
02.16.2020 22:00:00,1584.49,1584.49,1578.7,1580.79,1584.91,1584.91,1579.06,1581.31,101499
02.17.2020 22:00:00,1580.79,1604.97,1580.79,1601.06,1581.31,1605.33,1581.31,1603.08,321542
02.18.2020 22:00:00,1601.06,1612.83,1599.41,1611.27,1603.08,1613.4,1599.77,1613.34,357488
02.19.2020 22:00:00,1611.27,1623.62,1603.74,1618.48,1613.34,1623.98,1604.12,1621.27,535148
02.20.2020 22:00:00,1618.48,1649.26,1618.48,1643.42,1621.27,1649.52,1619.19,1643.87,590262
02.23.2020 22:00:00,1643.42,1689.22,1643.42,1658.62,1643.87,1689.55,1643.87,1659.07,1016570
02.24.2020 22:00:00,1658.62,1660.76,1624.9,1633.19,1659.07,1661.52,1625.5,1636.23,1222774
02.25.2020 22:00:00,1633.19,1654.88,1624.74,1640.4,1636.23,1655.23,1625.11,1642.59,1004692
02.26.2020 22:00:00,1640.4,1660.3,1635.15,1643.99,1642.59,1660.6,1635.6,1646.42,1084115
02.27.2020 22:00:00,1643.99,1649.39,1562.74,1584.95,1646.42,1649.84,1563.22,1585.58,1174015
03.01.2020 22:00:00,1584.95,1610.94,1575.29,1586.55,1585.58,1611.26,1575.88,1590.33,1115889
03.02.2020 22:00:00,1586.55,1649.16,1586.55,1640.19,1590.33,1649.6,1589.43,1644.16,889364
03.03.2020 22:00:00,1640.19,1652.81,1631.73,1635.95,1644.16,1653.51,1632.1,1639.05,589438
03.04.2020 22:00:00,1635.95,1674.51,1634.91,1669.36,1639.05,1674.9,1635.3,1672.83,643444
03.05.2020 22:00:00,1669.36,1692.1,1641.61,1673.89,1672.83,1692.65,1642.75,1674.46,1005737
03.08.2020 21:00:00,1673.89,1703.19,1656.98,1678.31,1674.46,1703.52,1657.88,1679.2,910166
03.09.2020 21:00:00,1678.31,1680.43,1641.37,1648.71,1679.2,1681.18,1641.94,1649.75,943377
03.10.2020 21:00:00,1648.71,1671.15,1632.9,1634.42,1649.75,1671.56,1633.31,1637.07,793816
03.11.2020 21:00:00,1634.42,1650.28,1560.5,1578.29,1637.07,1650.8,1560.92,1580.01,1009172
03.12.2020 21:00:00,1578.29,1597.85,1504.34,1528.99,1580.01,1598.36,1505.14,1530.09,1052940
03.15.2020 21:00:00,1528.99,1575.2,1451.08,1509.12,1530.09,1576.05,1451.49,1512.94,1196812
03.16.2020 21:00:00,1509.12,1553.91,1465.4,1528.57,1512.94,1554.21,1466.1,1529.43,1079729
03.17.2020 21:00:00,1528.57,1545.93,1472.49,1485.85,1529.43,1546.74,1472.99,1486.75,976857
03.18.2020 21:00:00,1485.85,1500.68,1463.49,1471.89,1486.75,1501.6,1464.64,1474.16,833803
03.19.2020 21:00:00,1471.89,1516.07,1454.46,1497.01,1474.16,1516.57,1455.93,1497.82,721471
03.22.2020 21:00:00,1497.01,1560.86,1482.21,1551.45,1497.82,1561.65,1483.22,1553.09,707830
03.23.2020 21:00:00,1551.45,1631.23,1551.45,1621.05,1553.09,1638.75,1553.09,1631.35,164862
03.24.2020 21:00:00,1621.05,1636.23,1588.82,1615.77,1631.35,1650.03,1601.29,1618.47,205272
03.25.2020 21:00:00,1615.77,1642.96,1587.7,1628.31,1618.47,1649.81,1599.87,1633.29,152804
03.26.2020 21:00:00,1628.31,1630.48,1606.76,1617.5,1633.29,1638.48,1616.9,1622.8,307278
03.29.2020 21:00:00,1617.5,1631.48,1602.51,1620.91,1622.8,1643.86,1612.55,1623.77,291653
03.30.2020 21:00:00,1620.91,1626.55,1573.37,1574.9,1623.77,1627.31,1575.24,1579.1,371507
03.31.2020 21:00:00,1574.9,1600.41,1560.13,1590.13,1579.1,1603.42,1570.75,1592.43,412780
04.01.2020 21:00:00,1590.13,1619.76,1582.42,1612.07,1592.43,1621.1,1583.37,1614.49,704652
04.02.2020 21:00:00,1612.07,1625.21,1605.39,1618.63,1614.49,1626.83,1607.69,1621.37,409490
04.05.2020 21:00:00,1618.63,1668.35,1608.59,1657.77,1621.37,1670.98,1609.7,1663.43,381690
04.06.2020 21:00:00,1657.77,1671.95,1641.84,1644.84,1663.43,1677.53,1643.4,1650.46,286313
04.07.2020 21:00:00,1644.84,1656.39,1640.1,1644.06,1650.46,1657.43,1643.46,1646.66,219464
04.08.2020 21:00:00,1644.06,1689.66,1643.05,1682.16,1646.66,1691.13,1644.83,1686.74,300111
04.12.2020 21:00:00,1682.16,1722.25,1677.35,1709.16,1686.74,1725.48,1680.49,1718.28,280905
04.13.2020 21:00:00,1709.16,1747.04,1708.56,1726.18,1718.28,1748.88,1709.36,1729.72,435098
04.14.2020 21:00:00,1726.18,1730.53,1706.67,1714.35,1729.72,1732.97,1708.95,1717.25,419065
04.15.2020 21:00:00,1714.35,1738.65,1707.83,1715.99,1717.25,1740.35,1708.93,1720.09,615105
04.16.2020 21:00:00,1715.99,1718.46,1677.16,1683.2,1720.09,1720.09,1680.55,1684.97,587875
04.19.2020 21:00:00,1683.2,1702.49,1671.1,1694.71,1684.97,1703.46,1672.02,1697.29,412116
04.20.2020 21:00:00,1694.71,1697.66,1659.42,1683.4,1697.29,1698.44,1662.3,1686.58,502893
04.21.2020 21:00:00,1683.4,1718.21,1679.61,1713.67,1686.58,1719.19,1680.71,1716.91,647622
04.22.2020 21:00:00,1713.67,1738.59,1706.93,1729.89,1716.91,1739.47,1707.72,1731.83,751833
04.23.2020 21:00:00,1729.89,1736.31,1710.56,1726.74,1731.83,1736.98,1711.03,1727.71,608827
04.26.2020 21:00:00,1726.74,1727.55,1705.99,1713.36,1727.71,1728.55,1706.72,1715.29,698217
04.27.2020 21:00:00,1713.36,1716.52,1691.41,1707.66,1715.29,1718.02,1692.51,1710.22,749906
04.28.2020 21:00:00,1707.66,1717.42,1697.65,1711.58,1710.22,1718.57,1698.4,1715.42,630720
04.29.2020 21:00:00,1711.58,1721.94,1681.36,1684.97,1715.42,1722.79,1681.91,1687.92,631609
04.30.2020 21:00:00,1684.97,1705.87,1669.62,1699.92,1687.92,1706.33,1670.81,1701.66,764742
05.03.2020 21:00:00,1699.92,1714.75,1691.46,1700.42,1701.66,1715.83,1692.96,1702.17,355859
05.04.2020 21:00:00,1700.42,1711.64,1688.55,1703.04,1702.17,1712.55,1690.42,1706.71,415576
05.05.2020 21:00:00,1703.04,1708.1,1681.6,1685.18,1706.71,1708.71,1682.33,1688.33,346814
05.06.2020 21:00:00,1685.18,1721.95,1683.59,1715.17,1688.33,1722.53,1684.8,1716.91,379103
05.07.2020 21:00:00,1715.17,1723.54,1701.49,1704.06,1716.91,1724.42,1702.1,1705.25,409225
05.10.2020 21:00:00,1704.06,1712.02,1691.75,1696.68,1705.25,1713.03,1692.45,1697.58,438010
05.11.2020 21:00:00,1696.68,1710.94,1693.56,1701.46,1697.58,1711.31,1693.92,1703.32,369988
05.12.2020 21:00:00,1701.46,1718.11,1698.86,1716.09,1703.32,1718.69,1699.4,1718.63,518107
05.13.2020 21:00:00,1716.09,1736.16,1710.79,1727.71,1718.63,1736.55,1711.33,1731.38,447401
05.14.2020 21:00:00,1727.71,1751.56,1727.71,1743.94,1731.38,1752.1,1728.89,1744.96,561909
05.17.2020 21:00:00,1743.94,1765.3,1727.4,1731.73,1744.96,1765.92,1728.08,1732.99,495628
05.18.2020 21:00:00,1731.73,1747.76,1725.05,1743.52,1732.99,1748.24,1726.29,1746.9,596250
05.19.2020 21:00:00,1743.52,1753.8,1742.04,1747.22,1746.9,1754.28,1742.62,1748.48,497960
05.20.2020 21:00:00,1747.22,1748.7,1717.14,1726.56,1748.48,1751.18,1717.39,1727.82,557122
05.21.2020 21:00:00,1726.56,1740.06,1723.33,1735.67,1727.82,1740.7,1724.41,1736.73,336867
05.24.2020 21:00:00,1735.67,1735.67,1721.61,1727.88,1736.73,1736.73,1721.83,1730.25,164650
05.25.2020 21:00:00,1727.88,1735.39,1708.48,1710.1,1730.25,1735.99,1709.34,1712.21,404914
05.26.2020 21:00:00,1710.1,1715.93,1693.57,1708.36,1712.21,1716.3,1694.04,1709.85,436519
05.27.2020 21:00:00,1708.36,1727.42,1703.41,1717.28,1709.85,1727.93,1705.85,1721.0,416306
05.28.2020 21:00:00,1717.28,1737.58,1712.55,1731.2,1721.0,1738.26,1713.24,1732.07,399698
05.31.2020 21:00:00,1731.2,1744.51,1726.98,1738.73,1732.07,1745.11,1727.93,1742.56,365219

Problem
This is the result for this code and I'm looking for ways to find intersections for SMA20 (yellow) and SMA50 (green) lines and thus able to get alerts whenever these lines cross.

Solution
Print out intersections indication crossing from above or below relative to each series.
import numpy as np

g20=sma20.values
g50=sma50.values
# np.sign(...) return -1, 0 or 1
# np.diff(...) return value difference for (n-1) - n, to obtain intersections
# np.argwhere(...) remove zeros, preserves turning points only
idx20 = np.argwhere(np.diff(np.sign(g20 - g50))).flatten()

priceSma_df.plot()
plt.scatter(close.index[idx20], sma50[idx20], color='red')
plt.show()

A: import numpy as np

f=close.values
g20=sma20.values
g50=sma50.values
idx20 = np.argwhere(np.diff(np.sign(f - g20))).flatten()
idx50 = np.argwhere(np.diff(np.sign(f - g50))).flatten()

priceSma_df = pd.DataFrame({
  'BidClose' : close,
  'SMA 20' : sma20,
  'SMA 50' : sma50
 })

priceSma_df.plot()
plt.scatter(close.index[idx20], sma20[idx20], color='orange')
plt.scatter(close.index[idx50], sma50[idx50], color='green')
plt.show()


text:
Q: Mercado Pago API Exception I'm receiving this exception everytime that i call one "PreferenceClient" method, pls someone save me
The Java code
public static void main(String[] args) throws MPException,  MPApiException {

    String DOMINIO = "127.0.0.1:2020";
    String SUCESSO = "/pagamento/aprovado";
    String FRACASSO = "/pagamento/recusado";

    PreferenceClient client = new PreferenceClient();

    PreferenceItemRequest item =
        PreferenceItemRequest.builder()
            .id("1")
            .title("Camiseta 1")
            .description("Salve")
            .quantity(1)
            .currencyId("BRL")
            .unitPrice(new BigDecimal("100"))
            .build();

    PreferenceBackUrlsRequest backUrls =
        PreferenceBackUrlsRequest.builder()
            .success(DOMINIO + SUCESSO)
            .failure(DOMINIO + FRACASSO)
            .build();

    List<PreferenceTrackRequest> tracks = new ArrayList<>();
    PreferenceTrackRequest googleTrack =
        PreferenceTrackRequest.builder()
            .type("google_ad")
            .build();

    tracks.add(googleTrack);

    PreferenceRequest request =
        PreferenceRequest.builder()
            .backUrls(backUrls)
            .items(Arrays.asList(item))
            .tracks(tracks)
            .build();

    client.create(request);
}
}

The exception:
Exception in thread "main" com.mercadopago.exceptions.MPApiException: Api error. Check response for details
at com.mercadopago.net.MPDefaultHttpClient.send(MPDefaultHttpClient.java:142)
at com.mercadopago.client.MercadoPagoClient.send(MercadoPagoClient.java:56)
at com.mercadopago.client.MercadoPagoClient.send(MercadoPagoClient.java:78)
at com.mercadopago.client.preference.PreferenceClient.create(PreferenceClient.java:123)
at com.mercadopago.client.preference.PreferenceClient.create(PreferenceClient.java:98)
at me.alexfrocha.mercadopago.mp.controllers.HomeController.main(HomeController.java:83)


text:
Q: RoR: Create parent through child I am new to rails and keep struggling with the following issue. Unfortunately, hours of search have not led to a solution, so I would be more than happy to get your input.
On creating an order, I attempt to create a client (as parent) and order items (as child). The latter works fine. However, on saving the order, both order and client are stored in the database with the exception that the *client_id* is not passed to the order record.
Here follows my code:
Company Model
class Company < ActiveRecord::Base

  has_many :orders,     foreign_key: "client_id"
  accepts_nested_attributes_for :orders

  validates :name,
            :presence => true,
            :uniqueness => { :case_sensitive => false }

  validates_associated  :users,
                        :orders

  attr_accessible :name,
                  :account,
                  :users_attributes,
                  :orders_attributes,
                  :company_id
end

Order Model
class Order < ActiveRecord::Base

    has_many :order_items
    accepts_nested_attributes_for   :order_items

    belongs_to  :client, class_name: "Company",
                                    foreign_key: "id"
    accepts_nested_attributes_for   :client

    attr_accessible :order_items_attributes,
                    :order_number,
                    :client_attributes,
                    :client_id

    validates_associated    :order_items

    validates_presence_of   :order_number
                            :client_id
end

Orders Controller
  def create
    @order = @client.orders.build(params:[orders])
    puts @order.to_yaml

    respond_to do |format|

      if @order.save!
        format.html { redirect_to @order, notice: 'Order was successfully created.' }
        format.json { render json: @order, status: :created, location: @order }
      else
        format.html { render action: "new" }
        format.json { render json: @order.errors, status: :unprocessable_entity }
      end
    end
  end

New Order Form
<%= simple_form_for @order, :html => { :class => 'form-horizontal' } do |f| %>
    <%= render 'shared/error_messages', :object => @order %>
  <div class = "span3">
    <%= f.simple_fields_for :client do |client_builder| %>
      <%= client_builder.input  :name,
                                :label => 'Client' %>
    <% end %>

    <%= f.input :order_number %>
    <%= f.simple_fields_for :order_items do |items_builder| %>
        <%= items_builder.input :reference_number %>
        <%= items_builder.input :item_description %>
    <% end %>

    <%= f.button  :submit,
                  :class => 'btn'%>
    <%= link_to t('.cancel', :default => t("helpers.links.cancel")),
                              orders_path, :class => 'btn' %>
  </div>
<% end %>

Thanks for your help in advance!
Stefan

A: belongs_to  :client, class_name: "Company", foreign_key: "id"

Should be
belongs_to  :client, class_name: "Company", foreign_key: "client_id"

Also i would update your migration and make that field not nullable, better to get an exception than saving an order without client


text:
Q: How to get webglcontextrestored fired I want to have a fairly large number of HTML canvas that I draw on using  WebGL. But if I draw more than 8 or 16 or a similar, client-dependent number, earlier ones disappear.
Based on the WebGL wiki I thought that reacting on webglcontextlost and webglcontextrestored would fix this… but it does not seem to be the case.
I essentially tried this code:
  canvas.addEventListener('webglcontextlost', e => {
    e.preventDefault();
  });
  canvas.addEventListener('webglcontextrestored', e => {
    render();
  });

with full fiddle available.
Do I have a coding error, or a conceptual error?

A: You can:t have more than 8 or 16 WebGL canvas. That's just a limit browsers put because WebGL uses lots of resources.
The best your code would do is make one fail and another re-start but I suspect most browsers don't handle that case well.
You probably don't actually want multiple WebGL canvases if you can avoid it since they can't share resources.
There are other solutions:
One is using a single canvas that doesn't scroll with the screen. Putting placeholder elements in your document and then looking where those elements are. If they are on the screen then draw a scene in the appropriate place in the canvas.
A three.js example. A WebGL example. Also a S.O question that kind of talks about this and other solutions
Another might be virtualizing the WebGL contexts so there's really only one context. That's slower but the the various users of th canvas don't have to co-operate


text:
Q: Why "\newcommand{\bal}{\begin{align}} doesn't work? I have this string in my preamble:
\def\bala#1\eala{\begin{align*}#1\end{align*}}

and I tried to rewrite it as:
\def\bala{\begin{align*}}
\def\eala{\end{align*}}

or as:
\newcommand{\bala}{\begin{align*}}
\newcommand{\eala}{\end{align*}}

but I noticed that it doesn't work for the align ambient (starred or not). It works for others math ambients like eqnarray, equation etc.
This is a Minimal NOT working Example:
\documentclass[11pt]{article}
\usepackage{amsmath}

\newcommand{\bala}{\begin{align}}

\newcommand{\eala}{\end{align}}

\begin{document}
My aligned equations
\bala
1+1&=2\\
2+2&=4
\eala

\end{document}

But the next one works:
\documentclass[11pt]{article}
\usepackage{amsmath}

\newcommand{\bala}{\begin{eqnarray}}

\newcommand{\eala}{\end{eqnarray}}

\begin{document}
My aligned equations
\bala
1+1&=&2\\
2+2&=&4
\eala

\end{document}


text:
Q: Regular Expression to match open and closed html tags I want to come up with Regular Expression to return true if the a closed html tag is matched with an open one in specific text that gets passed in JavaScript. If there is an unmatched tag, it should return false;
For example, if the following text is passed "
Test
" it should return true
but if the following text gets passed "
Test

Boom" it should return false
I can only get it to match the first div tags to return true with the following expression
    var text = "
Test
;
    var text2 = "
Test

;
    var regex = /[^<>]*<(\w+)(?:(?:\s+\w+(?:\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)>[^<>]*<\/\1+\s*>[^<>]*|[^<>]*<\w+(?:(?:\s+\w+(?:\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/>[^<>]*||^[^<>]+$/;
    var match = regex.test(text);
    console.log(match); // true
    var match = regex.test(text2);
    console.log(match2); // still true should be false

How can I fix it so it functions the way I want it to.

A: The test method returns true for match2 because it has found a match.
In order to fix it, change your regex this way:
^(?:<(\w+)(?:(?:\s+\w+(?:\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)>[^<>]*<\/\1+\s*>|<\w+(?:(?:\s+\w+(?:\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/>||[^<>]+)*$

Description (click to enlarge)

Demo
http://jsfiddle.net/r2LsN/
Discussion
The regex defines all the allowed patterns firstly:

*

*Tags with body:  <tag>...</tag>

*Tags without body: <tag/> (here we can find zero or more spaced before /)

*Comments

*Any text that is not < or >.

then these patterns can appear zero or more times between the beginning and the end of the tested string: ^(?:pattern1|pattern2|pattern3|pattern4)*$.


text:
Q: Question on Summation of a equation Find $$\sum_{x= 1/2}^{25 / 2} x^3 + 3x + 2.$$ Are there any simpler methods to solve this summation ? I will be thankful to any helps.
Counting is in the format of ${1 \over2}, 1, {3 \over2},....   $

A: Put $\frac y2 = x$.  Then the lower limit, which was $x=\frac12$, becomes $\frac y2=\frac12$, so $y=1$, and the upper limit, which was $x=\frac{25}2$, becomes $\frac y2=\frac{25}2$, so $y=25$.  We now want to sum $y$ from 1 to 25:
$$\sum_{y=1}^{25}\left(\frac18y^3 + \frac32y + 2\right) \\
= \frac18\sum_{y=1}^{25} y^3 + \frac32\sum_{y=1}^{25} y + \sum_{y=1}^{25}2
$$
Do you know how to evaluate the three sums separately?
(The important thing to check here it that we didn't somehow mess up the sums by changing the index from $x$ to $y$.  There are 25 terms in the sum now, and there should have been 25 in the sum before.  You said that is correct ($\frac12, 1, \frac32,\ldots \frac{25}2$ is 25 terms) so this substitution is correct. If the sum before had had only 13 terms ($\frac12,\frac32,\ldots \frac{25}2$ is only 13 terms) then new summation would not be the same.)


text:
Q: Formula to Calculate Each Pie Angle Where the Intercepted Arc is NOT the Center Point of the Circle AND All Slices are Equal Sized
I saw this picture titled "How to Start a Fight at Thanksgiving" and it made me laugh and then it made me wondered how to cut a pie into (N) number of pieces of equal surface area, but the central point of arc interception (C) is NOT the center point, instead it's located somewhere else inside the pie at coordinates X,Y.
Is there a formula to calculate the different angles so that each slice has the same surface area?
For discussion assume (r) Radius 4.5", (n) Number of slices is 6, (c) central point of arc interception is 1" moved to the left (west) of the true center point of the circle and 1.5" towards the top (north).
$\frac{\pi r^2}{n} = $ ~10.603 sq.inches for each slice, so what would be the different angles so that each slice equals ~10.603 sq. inches?
Assumption: the first single cut is the shortest line possible from the common point to the perimeter and were dealing with 3 or more (n) number of slices.
I thought this would be a fun Thanksgiving puzzle to solve. Thanks for playing.

A: Let's place the point at which all of the cuts converge at the origin and the center of the circular pie at $(h,0)$ so that the circle can be parameterized as $x=h+r\cos t$, $y=r\sin t$. The parameter $t$ represents the angle at the center of the pie. If $\Gamma$ is the arc of the circle that goes from $t_1$ to $t_2$ then the area of the slice is $$\frac12\int_\Gamma x\,dy-y\,dx = \frac r2\int_{t_1}^{t_2}r+h\cos t\,dt = \frac r2\left(r(t_2-t_1)+h(\sin t_1-\sin t_0)\right).$$ If we want $n$ equally-sized slices, this area must be equal to $\pi r^2/n$, which leads to the equation $$rt_2+h\sin t_2 = \frac{2\pi r}n+rt_1+h\sin t_1.$$ If we fix $t_1$, this can be solved for $t_2$. Unfortunately, there's no closed-form solution, but you can get a numerical approximation good enough for making the slices.
Taking your example, $h=\sqrt{1^2+1.5^2}\approx1.803$ and the area of each slice is approximately $10.603.$ The first cut is at $t=0$, and since there's an even number of slices, we know that there will be another at $t=\pi$. By symmetry, we only need to compute two more cuts. Setting $t_1=0$ produces $t_2\approx 0.77$, and working backwards from the other cut, setting $t_2=\pi$ yields $t_1\approx 1.70$. The resulting pie slices look something like this:

If we relax the requirement that all of the cuts radiate from a common point, then there are many more ways to divvy up the pie.

A: Here's an answer to a related problem.
If it's an elliptical pie and the cuts start at a focus then Kepler's equal area theorem provides the answer. Just send a planet around the edge of the dish and time the orbit.


text:
Q: Some properties of symmetric difference
Definition
For any $A,B$ we define
$$
A\Delta B:=\{x\in A:x\notin B\}\cup\{x\in B:x\notin A\}
$$
  and we call it symmetric difference of $A$ and $B$.
Obsertavion
Clearly $A\Delta B\equiv A\setminus B\cup B\setminus A$
Proposizion
The following properties hold

*

*$A\Delta\varnothing=A$

*$A\Delta A=A$

*$A\cap(B\Delta C)=(A\cap B)\Delta (A\cap C)$

*if $A\Delta B=A\Delta C$ then $B=C$

*$A\Delta B=B\Delta A$

*$(A\Delta B)\Delta C=A\Delta(B\Delta C)$
Proof. Clearly $A\Delta A=A\setminus A\cup\varnothing\setminus A=A\cup\varnothing=A$ and moreover$A\Delta A=A\setminus A\cup A\setminus A=\varnothing\cup\varnothing=\varnothing$ thus we have proved the points $1$ and $2$.
Now previously we observe that for any $X,Y,Z$ it follows that
  $$
x\in(X\cap Y)\setminus(Z\cap X)\leftrightarrow x\in X\wedge x\in Y\wedge\{x\notin Z\lor x\notin X\}\leftrightarrow x\in X\wedge x\in Y\wedge x\notin Z\leftrightarrow x\in X\wedge x\notin Y\setminus Z\leftrightarrow x\in X\cap Y\setminus Z
$$
  and so we conclude that $X\cap Y\setminus Z=(X\cap Y)\setminus(Z\cap X)$. So it follows that
  $$
A\cap(B\Delta C)=A\cap(B\setminus C\cup C\setminus B)=(A\cap B\setminus C)\cup(A\cap C\setminus B)=(A\cap B)\setminus (C\cap A)\cup(A\cap C)\setminus (B\cap A)=(A\cap B)\Delta(A\cap C)
$$
  and so we have proved the point $3$.
Now if $A\Delta B=B\Delta A$, that is $A\setminus B\cup B\setminus A=A\setminus C\cup C\setminus A$; and so it follows that
  $$
A\setminus B=(A\setminus B\cup B\setminus A)\cap A=(A\Delta B)\cap A=(A\Delta C)\cap A=(A\setminus C\cup C\setminus A)\cap A=A\setminus C
$$
  and so
  $$
A\cap B=A\setminus(A\setminus B)=A\setminus(A\setminus C)=A\cap C
$$
  and then
  $$
C\setminus A=(A\setminus C\cup C\setminus A)\setminus A=(A\Delta C)\setminus A=(A\Delta B)\setminus A=(A\setminus B\cup B\setminus A)\setminus A=B\setminus A
$$
  and so we conclude that $B=C$, thus we have proved the point 4.
  Then though the commutativity of union it easy to see that $A\Delta B=B\Delta A$ and so we have proved $5$.

So as you can see I can't prove the point 6 and so I ask to prove it. Then I ask if I have well proved the point 1 to 5. So could someone help me, please?

A: I'm inclined to agree with Luke Collins: indicator (or characteristic) functions make this easier. In $(6)$, for instance, I would let $X=A\cup B\cup C$ and define the indicator functions
$$\begin{align*}
&\mathbf{1}_A:X\to\{0,1\}:x\mapsto\begin{cases}
1,&\text{if }x\in A\\
0,&\text{if }x\notin A
\end{cases}\\
&\mathbf{1}_B:X\to\{0,1\}:x\mapsto\begin{cases}
1,&\text{if }x\in B\\
0,&\text{if }x\notin B\
\end{cases}\\
&\mathbf{1}_C:X\to\{0,1\}:x\mapsto\begin{cases}
1,&\text{if }x\in C\\
0,&\text{if }x\notin C\;.
\end{cases}
\end{align*}$$
Now verify that $\mathbf{1}_{A\triangle B}=\mathbf{1}_A\oplus\mathbf{1}_B$, where $\oplus$ is pointwise addition modulo $2$:
$$(\mathbf{1}_A\oplus\mathbf{1}_B)(x)=\big(\mathbf{1}_A(x)+\mathbf{1}_B(x)\big)\bmod 2$$
for each $x\in X$. Then for each $x\in X$ you can simply appeal to the associativity of $\oplus$ to argue that
$$\begin{align*}
x\in(A\triangle B)\triangle C&\text{ iff }\mathbf{1}_{(A\triangle B)\triangle C}(x)=1\\
&\text{ iff }\mathbf{1}_{A\triangle B}(x)\oplus\mathbf{1}_C(x)=1\\
&\text{ iff }\big(\mathbf{1}_A(x)\oplus\mathbf{1}_B(x)\big)\oplus\mathbf{1}_C(x)=1\\
&\text{ iff }\mathbf{1}_A(x)\oplus\big(\mathbf{1}_B(x)\oplus\mathbf{1}_C(x)\big)=1\\
&\text{ iff }\mathbf{1}_A(x)\oplus\mathbf{1}_{B\triangle C}(x)=1\\
&\text{ iff }\mathbf{1}_{A\triangle(B\triangle C)}(x)=1\\
&\text{ iff }x\in A\triangle(B\triangle C)\;.
\end{align*}$$
$(1)$, $(2)$, and $(5)$ also follow easily from properties of $\oplus$: the constant $0$ function is an identity element, each indicator function is its own inverse with respect to $\oplus$, and $\oplus$ is commutative.
Then $(4)$ is immediate from $(1)$, $(2)$, $(5)$, and $(6)$: if $A\triangle B=A\triangle C$, then
$$\begin{align*}
B&\overset{(1)}=B\triangle\varnothing\overset{(5)}=\varnothing\triangle B\overset{(2)}=(A\triangle A)\triangle B\overset{(6)}=A\triangle(A\triangle B)\\
&=A\triangle(A\triangle C)\overset{(6)}=(A\triangle A)\triangle C\overset{(2)}=\varnothing\triangle C\overset{(5)}=C\triangle\varnothing\overset{(1)}=C\;.
\end{align*}$$
That leaves only $(3)$, which succumbs quickly when you realize that $\mathbf{1}_{A\cap B}=\mathbf{1}_A\otimes\mathbf{1}_B$,where $\otimes$ is pointwise multiplication, which distributes over pointwise addition modulo $2$:
$$(\mathbf{1}_A\otimes\mathbf{1}_B)(x)=\mathbf{1}_A(x)\cdot\mathbf{1}_B(x)\;.$$
For getting a better intuitive grasp of the symmetric difference I agree with Greg Martin: it's useful to know (and follows easily from the indicator function approach) that the members of a symmetric difference of a finite family of sets are the things that are in an odd number of those sets.

A: As Luke mentioned in the comments, indicator functions are a productive approach.
If $\oplus$ denotes 'exclusive or' the we see that
$1_{A \triangle B} = 1_A \oplus 1_B$.
It is easy to verify that $x \oplus y = y \oplus x$. This gives 5.
It is not hard to verify (use an 8 place truth table at worst) that $x\oplus (y \oplus z) = (x\oplus y) \oplus z$. This gives 6.


text:
Q: How to add leaderboard feature of OpenFeint in Android? I am developing a game in Android, by extending a class with view. I have integrated OpenFeint in it by studying the tutorial provided  on OpenFeint site url is(http://support.openfeint.com/dev/getting-started-with-of-android-1-10-2-integrate-openfeint-in-your-game/), but I am not able to add a leaderboard feature in my app.  How can I do that?
My game class is like this:
public class GameActivity extends Activity {
Intent i;

  Grapic g;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(new Grapic(this));

and Grapic is a class which extends view and where scoring is done with touch events.

A: i solved problem by myself
The link
http://support.openfeint.com/dev/getting-started-with-of-android-1-10-2-add-openfeint-features-to-your-game/
had the code
and first create achievement feature for your game and then leader board in also and refer the code below where you put scores
@Override
        public void onFinish()
        {
             new Achievement("123456").unlock(new Achievement.UnlockCB () {

                 @Override
                 public void onFailure(String exceptionMessage) {
                   Toast.makeText( getContext(),"Error (" + exceptionMessage + ") unlocking achievement.", Toast.LENGTH_SHORT).show();
                   ((Activity) getContext()).setResult(Activity.RESULT_CANCELED);
                   ((Activity) getContext()).finish();
                 }
               @Override
               public void onSuccess(boolean newUnlock) {
                       // TODO Auto-generated method stub
                       ((Activity) getContext()).setResult(Activity.RESULT_OK);
                       ((Activity) getContext()).finish();

               }
               });
       long scoreValue = Long.parseLong(nit) ;
       Score s = new Score(scoreValue, null); // Second parameter is null to indicate that custom display text is not used.
       Leaderboard l = new Leaderboard("234567");
       s.submitTo(l, new Score.SubmitToCB() {
         @Override public void onSuccess(boolean newHighScore) {                 // sweet, score was posted
                       ((Activity) getContext()).setResult(Activity.RESULT_OK);
                       ((Activity) getContext()).finish();
         }
         @Override public void onFailure(String exceptionMessage) {
           Toast.makeText(((Activity) getContext()), "Error (" + exceptionMessage + ") posting score.", Toast.LENGTH_SHORT).show();
               ((Activity) getContext()).setResult(Activity.RESULT_CANCELED);
               ((Activity) getContext()).finish();
         }
       });
            handler.post(new Runnable() {
                public void run() {
               Intent i=new Intent(new Intent(getContext(),Androidfacebook.class));

               i.putExtra("aman", nit);

                              context.startActivity(i);
                }});
        }


text:
Q: Need assistance getting a sum of a column based on the date range in another column I'm using Microsoft Access and I have a table that has 3 columns, Employee_Name, In Actual Time, and Out Actual Time.
I want to get a sum of hours worked based on a date range; for example, get a sum of hours worked between 7/19/21 - 7/25/21, and group them by Employee_Name.  I was able to use DateDiff to get a raw amount of hours per day/row, but I can't figure out how to make a query make a sum of those raw hours based on the date range in the [In Actual Time] field.  I tried to find the answer on my own but it seems I'm spinning my wheels and I have no working prototypes as of yet.
I would greatly appreciate any insight anyone may be able to provide on an easy way to do this.


text:
Q: Comprobar login en Laravel 5.7 desde script externo Tengo una aplicación en Laravel y necesito comprobar, desde un script externo si hay un usuario logueado o no y cual es. Para ello uso las siguientes líneas de código, para cargar Laravel:
require_once __DIR__.'/../../../vendor/autoload.php';

$app = require_once __DIR__.'/../../../bootstrap/app.php';

$app->make('Illuminate\Contracts\Http\Kernel')
    ->handle(Illuminate\Http\Request::capture());

/*if (Cookie::get(config('session.cookie')) != "") {
    $id = Cookie::get(config('session.cookie'));
    Session::driver()->setId($pericod);
    Session::driver()->start();
}*/

$isAuthorized = Auth::check();
if(!$isAuthorized){
    echo "NO AUTORIZADO";
    exit();
}

Con estas líneas tengo acceso a cualquier función de Laravel y de hecho, la comprobación de login me funciona correctamente para peticiones GET, pero cuando es una petición POST me falla, no es capaz de reconocer el login, de hecho, creo que reinicia la sesión porque no es capaz de recuperar la que existía.
He hecho muchas pruebas y creo que tampoco carga o usa ciertas partes del Laravel, como por ejemplo no reconoce las rutas, no carga los middlewares, etc...
Uso Laravel 5.7 actualizado hoy mismo y este mismo código me ha llegado a funcionar, creo recordar que en Laravel 5.4.
¿alguna idea de lo que puede estar fallando?
muchas gracias.

A: He descubierto el problema.
El truco estaba en que la ruta del fichero php que cargo es externa a laravel, eso hace que el route resolver de laravel la identifique como que es /.
Todo estaba funcionando con peticiones GET porque en mi fichero routes.php de Laravel tengo la ruta / como tipo get. Si cambio el tipo de ruta a any, todo funciona correctamente.
No estaba viendo el problema porque no estaba terminando la ejecución de Laravel. Si cambio la parte de verificación de usuario logueado, si consigo ver el error:
$isAuthorized = Auth::check();
if(!$isAuthorized){
    echo "NO AUTORIZADO";

    $response->send();
    $kernel->terminate($request, $response);

    exit();
}

Estas dos lineas finalizan la ejecución de Laravel, haciendo que se desvele el problema real, mostrando el error: "405 Method Not Allowed".
$response->send();
$kernel->terminate($request, $response);

Muchas gracias por vuestra ayuda.


text:
Q: MS SQL Transpose data to next column, max.transposed items = 5 Below is my data format
Name           Tel           Email
John           25671234      abc@abc.com
Peter          98047766      aaa@kk.com
Peter          98047766      bbb@sc.com
Peter          98047766      ccc@kd.com
Peter          98047766      ddd@kk.com
Peter          98047766      eee@sc.com
Peter          98047766      fff@kd.com
Mary           33456789      987@dkh.com

Now I would like to change the formal as below. How would I do this using SQL Server?
Name           Tel           Email        Email1      EMAIL2      EMAIL3      EMAIL4     EMAIL5
John           25671234      abc@abc.com
Peter          98047766      aaa@kk.com   bbb@sc.com  ccc@kd.com  ccc@kd.com  ddd@kk.com eee@sc.com
Mary           33456789      987@dkh.com

A: You can enumerate the values and pivot.  I would use conditional aggregation:
select name, telephone,
       max(case when seqnum = 1 then email end) as email_1,
       max(case when seqnum = 2 then email end) as email_2,
       max(case when seqnum = 3 then email end) as email_3,
       max(case when seqnum = 4 then email end) as email_4,
       max(case when seqnum = 5 then email end) as email_5
from (select t.*,
             row_number() over (partition by name order by (select null)) as seqnum
      from t
     ) t
group by name, telephone


text:
Q: Unable to handle event in another class I am kinda new to visual basic and was wondering if it is possible to trigger events in a class, based on action with in form.
So the following is my problem:
I have a form called Main, with a picture box called picPID
And a class called add_new
What I want to do is:
when the right mousebutton is clicked, the code for the event handling is placed within the class called add_new
I thought i could just declare it in the following way:
Sub meMouseDown(sender As Object, e As MouseEventArgs) Handles Main.picPID.MouseDown
But I get an error saying i have to declare it withEvents, I tried to declare the picturebox as:
Public shared withEvents as picturebox
but it dident help, any sugestions? It is not a problem having the code within the Main form, but it would result in a lot of code, so I was hoping to split it up.

A: So you have the class with an eventhandler:
Public Class add_new

    Public Sub PictureBoxEventHandler(sender As Object, e As MouseEventArgs)
        'Your Implementation
    End Sub

End Class

Then you need an instance of this class within the form containing the picturebox:
Public Class Form1

    Private add_New_Command As New add_new ' hold a reference to the command

    'constructor
    Public Sub New()

        InitializeComponent()

        ' and add the handler to the event of the picture box ... hook it up
        AddHandler PictureBox1.MouseDown, AddressOf add_New_Command.PictureBoxEventHandler

    End Sub

End Class


text:
Q: If statement, differential equation I've got problem with If statement. It doesn't work. I've never used Mathematica before, probably it's a problem with syntax.
wynik1 = 0
For[u = 0, u <= 1, u = u + 0.1,
 s = NDSolve[{x1'[t] == u*(10*x2[t] - x1[t]), x1[0] == 1,
    x2'[t] == u*(x1[t] - 10*x2[t]) - (1 - u)*x2[t], x2[0] == 0}, {x1,
    x2}, {t, 0, 1}];
 wynik = 1 - Evaluate[{x1[1] /. s} + {x2[1] /. s}];
 If[wynik > wynik1, wynik1 = wynik; Print[wynik1]]]

Any ideas?

A: Since you are only interested in the values of your functions evaluated at a specific point, you may want to use ParametricNDSolveValue to approach your problem in a more direct way
First generate an implicit family of solutions of your differential system returning the values of x1[1] and x2[1] as a function of your parameter u:
Clear[u, x1, x2, t]
solutions = ParametricNDSolveValue[
   {
    x1'[t] == u*(10*x2[t] - x1[t]), x1[0] == 1,
    x2'[t] == u*(x1[t] - 10*x2[t]) - (1 - u)*x2[t], x2[0] == 0
   },
   {x1[1], x2[1]}, {t, 0, 1}, u
   ];

Then calculate all pairs of values of x[1] and x[2] for each value of $u$ of interest in the range $(0, 1)$:
valuesforu = solutions /@ Range[0, 1, 0.1]

(* Out:
{{1., 0.}, {0.931991, 0.0426269}, {0.902059, 0.0618784}, {0.889307, 0.071569},
 {0.884889, 0.0771448}, {0.884867, 0.0808241}, {0.887377, 0.0835529}, {0.891474, 0.0857601},
 {0.896641, 0.0876553}, {0.902577, 0.0893498}, {0.909092, 0.0909076}}
*)

Finally, you seem to be interested in the maximum of the function 1 - x1[1] +x2[1], so we can calculate values of this function and separately find the highest one as follows:
1 - #1 + #2 & @@@ valuesforu
Max[%]

(* Out: {0., 0.110636, 0.15982, 0.182262, 0.192255, 0.195957, 0.196176, 0.194287,
         0.191014, 0.186773, 0.181815} *)

(* Out: 0.196176 *)

A: Try this:
wynik1 = 0;
For[u = 0, u <= 1, u = u + 0.1,
 s = NDSolve[{x1'[t] == u*(10*x2[t] - x1[t]), x1[0] == 1,
    x2'[t] == u*(x1[t] - 10*x2[t]) - (1 - u)*x2[t], x2[0] == 0}, {x1,
    x2}, {t, 0, 1}];
 wynik = First[1 - x1[1] + x2[1] /. s];
 (*Print[wynik];*)
 If[wynik > wynik1, wynik1 = wynik; Print[wynik1]];
 ]
wynik1


text:
Q: Critical view on object based application structure in AngularJS As i tried to learn some Angular in the past weeks, i have adopted a certain application architecture.
Assuming a intermediate large SPA, i create the view and apply a maincontroller:
<html ng-app="app">
    <body ng-controller="appCtrl">
        <!-- All of the view goes in here -->
    </body>
</html>

Now i think about the stuff that my application will have to do. Assuming that this one would have to store some data and working with it, i would create a provider to build a "class".
    var data = angular.module('data', []);

data.provider('$dataObject',function(){

    this.$get = function($http){

            function DataObject(){

                var field = "testvalue";
                var object = {
                    // ...
                }
            }

            DataObject.prototype.processData = function(){
               // do something
            };

        return {
            Shipment: function(){
                return new Shipment();
            }
        }
    }
});

I would then create an instance of that class in my maincontroller, storing all of the necessary data from the view into that object, processing it by calling the class methods.
If the application would need another functionality, e.g a dialog to pick some stuff, i would repeat the steps above and create a class for that dialog.
Now, while i am quite comfortable to do things that way, i still wonder if someone would consider this bad practice, and if so, why is that and what could i do better?

A: Creating services/providers for your models/data (with APIs to expose the data), and then injecting them into controllers is the "Angular way."
When I design an angular app, I think about the models I need and create services for them.  I then (or in parallel) think about the views and design those.  I normally create custom directives at this point also.  Lastly, each view gets a controller, whose job it is to glue the models/data from the services that the view needs.  (Make controllers as thin as possible.)


text:
Q: Selection of cheapest products, for a variable quantity (hourly demand) We have two tables:

*

*One with bids (price & quantity) by numerous suppliers, for every hour of
the year.

*A second table listing total consumer demand for every hour (quantity)

We need to generate:

*

*A third table that lists all the cheapest supplier bids, but only for the quantity summing to total consumer demand. Eg while there might be 10 bids at quantity (1), only the cheapest 5 will be selected if demand for that hour equals (5).

There is only product, and it is homogeneous. The only relevant parameters are thus price and quantity. Prices are per unit of quantity (ie not the total of the whole quantity).
Example:
Supplier bids (offered quantity)

Hour
Supplier
Price
Quantity

1
Siemens
1
10

1
Siemens
4
20

1
Fuji
7
20

2
ABB
1
10

2
Hitachi
2
15

2
Siemens
4
10

Total demand

Hour
Quantity

1
10

2
25

Then the generated table should look like this:
Awarded bids (cheapest, totaling to demand)

Hour
Supplier
Price
Quantity

1
Siemens
1
10

2
ABB
1
10

2
Hitachi
2
15

As you can see, the sum of all bids in this table equals the total demand from the second table. Even if there are additional bids, these are not included here because demand is fulfilled.
Often, the sum of supplier bids won't exactly total demand, eg if demand is 100 but every quantity equals 30. In that case, the quantity for the last bid added to the table is 'cut-off' (ie, only the quantity to meet demand is taken from that bid).
We thought of handling this via PLSQL, following these steps:

*

*We create a CURSOR that selects all bids for a certain hour, ordered by price

*A loop INSERTs the bids into the new table, UNTIL the sum of the inserted bids (quantity) has reached total demand for that hour.

*The process is repeated, by re-declaring the CURSOR in a loop that goes over every hour (over a period of 10 years, meaning about 90k iterations).

As we are simple economists with limited background in SQL, this seems the most straightforward way to handle this. However, it appears that this approach is very resource intensive. There are namely over 15 million rows of supplier bids, and the amount of hours to loop through are around 90 000.
We therefore were wondering if those among you who are more educated in SQL matters than us would have any suggestions as to our approach. Eg. - is this is the only way to handle this? Is there a better, more efficient way?

A: Assumptions made...

*

*Unfulfilled demand does not carry over to the subsequent hour

*The price is the price per item (not the total price for the whole batch)

*When "cutting off", only the required quantity is paid for (not the quantity in the original bid)
This reduces the algorithm to simply aggregating bids in ascending price order, until sum(quantity) exceeds demand
This can be worked out using analytic functions (also known as window functions) rather than loops.

*

*https://oracle-base.com/articles/misc/analytic-functions

For example...
WITH
  hourly_cumulative AS
(
  SELECT
    demand.hour,
    demand.quantity    AS demand,
    bid.supplier,
    bid.price,
    bid.quantity       AS supply,
    SUM(bid.quantity)
      OVER (
        PARTITION BY demand.hour
            ORDER BY bid.price
      )
        AS fulfilled_demand
  FROM
    demand
  LEFT JOIN
    bid
      ON bid.hour = demand.hour
)
SELECT
  hour,
  demand,
  supplier,
  price,
  supply  AS potential_supply,
  CASE
    WHEN fulfilled_demand > demand
    THEN supply - (fulfilled_demand - demand)
    ELSE supply
  END
    AS actual_supply
FROM
  hourly_cumulative
WHERE
  fulfilled_demand - supply < demand

Be sure that you have indexes on hour, and for the bids, preferably on at least hour, price.

*

*The indexes will make the joins cheaper

*If they match the PARTITION and ORDER in the window clause, they'll make that cheaper too

A: I'm not sure about your tables' names, so I've called them bids and demands:
select
   b.Hour
  ,b.Supplier
  ,b.Price
  ,b.Quantity-greatest(0,(b.running_total_quantity-d.quantity)) as quantity
from
    (
      select
         Hour,Supplier,Price,Quantity
        ,nvl(
          sum(Quantity)
            over( partition by Hour
                  order by Price
                  rows between unbounded preceding and 1 preceding
                )
         ,0) as running_total_quantity
      from bids
    ) b
    join demands d
      on  b.hour=d.hour
      and b.running_total_quantity<d.Quantity
order by b.hour,b.price,b.running_total_quantity

As you can see we calculate running total quantity for each row up to this row order by price, but not including a quantity of the current row. Then we join these results with demands by hour and until we get the required quantity.
Full test case with test data:
-- test data:
with
 bids(Hour,Supplier,Price,Quantity) as (
    select 1, 'Siemens' , 1, 10 from dual union all
    select 1, 'Siemens' , 4, 20 from dual union all
    select 1, 'Fuji'    , 7, 20 from dual union all
    select 2, 'ABB'     , 1, 10 from dual union all
    select 2, 'Hitachi' , 2, 15 from dual union all
    select 2, 'Siemens' , 4, 10 from dual
)
,demands(Hour,Quantity) as (
    select 1, 10 from dual union all
    select 2, 25 from dual
)-- end of test data
--main query
select
   b.Hour
  ,b.Supplier
  ,b.Price
  ,b.Quantity-greatest(0,(b.running_total_quantity-d.quantity)) as quantity
from
    (
      select
         Hour,Supplier,Price,Quantity
        ,nvl(
          sum(Quantity)
            over( partition by Hour
                  order by Price
                  rows between unbounded preceding and 1 preceding
                )
         ,0) as running_total_quantity
      from bids
    ) b
    join demands d
      on  b.hour=d.hour
      and b.running_total_quantity<d.Quantity
order by b.hour,b.price,b.running_total_quantity

Results:
      HOUR SUPPLIER       PRICE   QUANTITY
---------- --------- ---------- ----------
         1 Siemens            1         10
         2 ABB                1         10
         2 Hitachi            2         15


text:
Q: Reverse strings in SQL Server I have a table with product values as below:

*

*apple iphone

*iphone apple

*samsung phone

*phone samsung
I want to delete those products from the table which are exact reverse(as I consider them as duplicates), such that instead of 4 records, my table just have 2 records

*

*apple iphone

*samsung phone
I understand that there is REVERSE function in SQL Server, but it will reverse the whole string, and its not what I'm looking for.
I'd greatly appreciate any suggestions/ideas.

A: It seems to me that you are complicating this too much, a simple update statement would work:
UPDATE table SET productname = 'apple iphone' WHERE productname = 'iphone apple'

A: Assuming that your dictionary does not include any XML entities (e.g. > or <), and that it is not practical to manually create a bunch of UPDATE statements for every combination of words in your table (if it is practical, then simplify your life, stop reading this answer, and use Justin's answer), you can create a function like this:
CREATE FUNCTION dbo.SplitSafeStrings
(
   @List       NVARCHAR(MAX),
   @Delimiter  NVARCHAR(255)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
   RETURN
   ( SELECT Item = LTRIM(RTRIM(y.i.value('(./text())[1]', 'nvarchar(4000)')))
     FROM ( SELECT x = CONVERT(XML, ''
          + REPLACE(@List, @Delimiter, '') + '').query('.')
      ) AS a CROSS APPLY x.nodes('i') AS y(i));
GO

(If XML is a problem, there are other, more complex alternatives, such as CLR.)
Then you can do this:
DECLARE @x TABLE(id INT IDENTITY(1,1), s VARCHAR(64));

INSERT @x(s) VALUES
  ('apple iphone'),
  ('iphone Apple'),
  ('iphone samsung hoochie blat'),
  ('samsung hoochie blat iphone');

;WITH cte1 AS
(
  SELECT id, Item FROM @x AS x
  CROSS APPLY dbo.SplitSafeStrings(LOWER(x.s), ' ') AS y
),
cte2(id,words) AS
(
  SELECT DISTINCT id, STUFF((SELECT ',' + orig.Item
    FROM cte1 AS orig
    WHERE orig.id = cte1.id
    ORDER BY orig.Item
    FOR XML PATH(''), TYPE).value('.[1]','nvarchar(max)'),1,1,'')
  FROM cte1
),
cte3 AS
(
  SELECT id, words, rn = ROW_NUMBER() OVER (PARTITION BY words ORDER BY id)
  FROM cte2
)
SELECT id, words, rn FROM cte3
-- WHERE rn = 1 -- rows to keep
-- WHERE rn > 1 -- rows to delete
;

So you could, after the three CTEs, instead of the final SELECT above, say:
DELETE t FROM @x AS t
  INNER JOIN cte3 ON cte3.id = t.id
  WHERE cte3.rn > 1;

And what should be left in @x?
SELECT id, s FROM @x;

Results:
id  s
--  ---------------------------
1   apple iphone
3   iphone samsung hoochie blat

A: I don't know how to do this in SQL, but in a language where you interface with SQL, you can do this:
You can tokenize each line so that you have an array of words, so that "iphone apple" becomes {"iphone","apple"} and then you can switch the order of the elements using a common swap statement so that it becomes {"apple","iphone"} and then you can turn it back into a string to make "apple iphone"
Although the process I describe above isn't all that hard to do, finding out which ones are duplicates of each other (knowing which ones to flip) might be a harder problem

A: Basing on data examples you've provided you could try something like this:
In case the "proper" format for productname is <brand> <product_type> you can just delete all products with productname not like '<brand>%'.
In case above won't help - are there any product naming rules?
As above idea cannot be applied, create Split function:
CREATE FUNCTION [dbo].[Split]
(
    @String NVARCHAR(4000),
    @Delimiter NCHAR(1)
)
RETURNS TABLE
AS
RETURN
(
    WITH Split(stpos,endpos)
    AS(
        SELECT 0 AS stpos, CHARINDEX(@Delimiter,@String) AS endpos
        UNION ALL
        SELECT endpos+1, CHARINDEX(@Delimiter,@String,endpos+1)
            FROM Split
            WHERE endpos > 0
    )
    SELECT 'Id' = ROW_NUMBER() OVER (ORDER BY (SELECT 1)),
        'Data' = SUBSTRING(@String,stpos,COALESCE(NULLIF(endpos,0),LEN(@String)+1)-    stpos)
FROM Split
)

And use it in query:
select
    (SELECT (', ' + Data)
     FROM Split(t.textVal, ' ')
     order by [Data]
     FOR XML PATH( '' )
    )
from
    test t

This will provide you with product name with sorted words. With this you can easily find duplicates.
Second query is rough around the edges as i gotta go afk, but you should manage to smooth it out :)
Good luck

A: here's a solution for two or more words separated by space. basically the idea is to use a recursive CTE to split by space and then for xml to put the names back together sorted. Then you can group by the new name column to get your deduplicated list:
with split as (
  select id,
    convert(varchar(max), left(name, charindex(' ', name + ' ') - 1)) word,
    stuff(name, 1, charindex(' ', name + ' '), '') name
  from products

  union all

  select id,
    convert(varchar(max), left(name, charindex(' ', name + ' ') - 1)) word,
    stuff(name, 1, charindex(' ', name + ' '), '') name
  from split where name > ''
),
hom as (
  select id,
    (select word + ' '
     from split where id=o.id
     order by word for xml path('')) name
  from split o
)

select name, min(id) id from hom group by name

SQLFiddle