text:
Q: How to get a secured ip with bazinga geocoder I'm using the bazinga geocoder in a project on Symfony at work. We use several geolocation part on our application, so we cant use the local ip (127.0.0.1 or our docker IP). We need a fakeIp to work with those geolocation. Moreover we use a proxy in local to get an https connection.
The problem is that when we re-write the ip with our fakeip, symfony consider she can't be trust so we get an error because the re-write don't come from a trusted proxy. Then when we add it to the trustedProxies to tell symfony it's a good ip you can trust her the fakeIp is no more recognize as our IP.
And symfony starts to use my docker IP.I did few researchs on the internet i thought this could be a solution but it only work partially (https://symfony.com/blog/fixing-the-trusted-proxies-configuration-for-symfony-3-3)
Sorry for my english. And i hope you can understand my prb
Here is my code of the fakeRequest listener, and there is no other modification
 /**
 * @var string
 */
protected $fakeIp = null;

public function __construct($fakeIp)
{
    $this->fakeIp = $fakeIp;
}

public function onKernelRequest(GetResponseEvent $event)
{
    if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
        return;
    }

    if (null !== $this->fakeIp && !empty($this->fakeIp)) {
        $event->getRequest()->setTrustedProxies(array($this->fakeIp));
        $event->getRequest()->server->set('REMOTE_ADDR', $this->fakeIp);
    }
}

public function getFakeIp()
{
    return $this->fakeIp;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Self-Destructing Cocoa Application I'm looking for ways to design a self-destructing Cocoa application. The idea is to detect at launch if the application is being retro-engineering (which is always done in several attempts) and delete/corrupt it in case of. Of course, a zealous hacker could re-download and retro-engineer the destruction process, but it would make it really annoying and painful!
For checking code integrity, hashsums on the executable should do the trick.
With regards to the corruption process, I am pretty sure that an application can't edit its bundle while running.
I have one idea :
-spawning a "middle application" dedicated to destruction, launching it while quitting the first . Would it work ?
-Would spawing a Shell Script(which would wait to for application to terminate) before quitting do the trick ?
Any ideas are welcomed !
EDIT : With regards to Cocoaster link :
1.Stripping debug symbols : it is very easy to trace "verification" methods, even without explicit methods name, mostly by looking for NSString calls (@"validated", @"license")
2.PT_DENY_ATTACH : there are ways to attach anyway, but breaking on ptrace() and modifying return value (and if I could find this in my basic retro-engineering training, anyone can).
3.Checking checksum, quitting otherwise : that's exactly the kind of thing I'm trying to avoid : it is easy with gdb to trace the call to [NSApplication shouldTerminate:]) and modify the test (or the valid MD5 string)to pass it. The whole point is that instead of just having to reload gdb, the hacker will need to download/install it again (thus making the process REALLY time-consuming).
Imagine this :
1.At launch time, the mainApplication creates a shell/bash script which would be something like :
 wait(decent time)
 rm /*Dynamic Application Path*/Contents/MacOS/exe

or better :
  sed -i 's/a/b/g' /*Dynamic Application Path*/Contents/MacOS/exe
//Will completly screw the code

2.If checksum fail , launch script and terminate application quietly.
My question is : is NSTask Application-dependant (can I launch a NSTask and quit the application who launched it)?

A: Could this be what you're looking for?
http://www.seoxys.com/3-easy-tips-to-prevent-a-binary-crack/
http://www.cocoabuilder.com/archive/cocoa/283683-detecting-if-you-re-being-debugged.html
http://www.cocoabuilder.com/archive/cocoa/109505-detect-debugger.html


text:
Q: tkMessageBox popup invisible when run from desktop, visible when run from boot I am trying to write a program that allows the user to press different buttons in a full screen Tkinter GUI. The operations these buttons preform does not matter for my question, but I am having trouble creating a popup dialogue (askokcancel) to confirm that the user wants to press a button, then run the rest of that buttons code normally if "ok" is pressed. Currently, I have this program running from boot through the /etc/profile file, accessed via
sudo nano /etc/profile
Here I change the directory to the folder containing my python file and have it load my code, and upon booting up it loads my buttons correctly and upon pressing the correct button the popup window appears over the full screen window. However, when I try to run my code through the desktop shell, upon pressing the button, the popup window DOES appear, but is hidden behind the root window. I am not able to click anywhere else, and pressing "tab" and "enter" allows me to navigate between the two choices and pick one, but without being able to see it. I have buttons printing words in the shell, so I know the popup window is actually there.
The full screen makes use of the overrideredirect function, hiding the task bar and other options. When this is set to FALSE, the popup works as intended, but I am trying to make the GUI be the only thing on the screen.
Here is a condensed version of my code:
from Tkinter import*
import tkMessageBox

class Application(Frame):
    def run(self):
        tkMessageBox.askokcancel("Run Confirmation!", "Are you sure?")
        print "RUN Code Intitates"

    def createWidgets(self):
        self.button1 = Button(self,height=15,width=20)
        self.button1["command"] = self.run
        self.button1.pack({"side": "left"})

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

root = Tk()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.overrideredirect(1)
root.geometry("%dx%d+0+0" % (800, 480))

app = Application(master=root)
app.mainloop()
root.destroy()

I am by no means a computer science major and have only been working with raspberry pi, tkinter, and python for a couple weeks, so if I am missing something basic I apologize. I am using an 8" touchscreen display made for raspberry pi as my screen.

A: According to the tcl/tk documentation:

Setting the override-redirect flag for a window causes it to be
  ignored by the window manager; among other things, this means that the
  window will not be reparented from the root window into a decorative
  frame and the user will not be able to manipulate the window using the
  normal window manager mechanisms

So the window does not always behave has expected (it is less the case in Windows). For instance, in Linux, the window does not get keyboard focus (python tkinter overrideredirect; cannot receive keystrokes (Linux)).

*

*If what you really care about is to have a fullscreen GUI, just replace
root.overrideredirect(1)
by
root.attributes('-fullscreen', True)
and the window will behave normally so the message box will appear on top of the main window.

*Another possibility in Linux is to replace
root.overrideredirect(1)
by
root.attributes('-type', 'dock')
This tells the window manager to treat the window as a dock, and at least in XFCE, it results in a window with no decorations, always on top of the other windows, but the message box does appear on top of it.


text:
Q: Convert cmd ffmpeg script to shell its very simple code for cmd but i cant get how its should work on my nas with shell
Please help to convert script:
@echo off
setlocal enableextensions enabledelayedexpansion

Settings
set sWorkFolder=d:\workfolder
set sSourceFolder=%sWorkFolder%\waiting-to-convert
set sDestFolder=%sWorkFolder%\done
set sBackupFolder=%sWorkFolder%\trash
set sPath2ffmpeg=%sWorkFolder%\ffmpeg\bin\ffmpeg.exe

Start cycle
for /r "%sSourceFolder%" %%i in (*.mp4) do call :action "%%i"

endlocal
exit /b

:action
setlocal enableextensions enabledelayedexpansion

set "sSourcePath=%~dp1"
set "sDestPath=%sDestFolder%!sSourcePath:%sSourceFolder%=!"
if not exist "%sDestPath%." md "%sDestPath%"
set "sDestFile=%sDestPath%%~n1.720p%~x1"

"%sPath2ffmpeg%" -i "%~f1" -vcodec h264 -vf "scale=trunc(oh*a/2)*2:min(720p\,ih)" -b:v 2000k -preset faster -acodec copy -y "%sDestFile%"

set "sBackupPath=%sBackupFolder%!sSourcePath:%sSourceFolder%=!"
if not exist "%sBackupPath%." md "%sBackupPath%"

move /y "%~1" "%sBackupPath%"

endlocal
exit /b

A: Shell scripts are normally echo off. You can get debugging output with set -vx and turn that off with set +vx. These two can be placed anywhere in the file (preferably on a line separate from others). (And as you will notice below set is very different in shell that cmd).
The first line of your script should be
#!/bin/bash

After you save your file, you need to execute the unix/linux command
chmod 755 myScript.sh

To mark it executable.
If you created file on windows, or use windows ftp, or windows anything, once you have file to *nix, do
dos2unix myScript.sh

set var=value is accomplished with DestPath=/path/to/dir. use
if [ ! -d "$DestPath" ] ; then mkdir "$DestPath'; fi

All vars are referenced like "$var".
move is shortened to mv. Consult man mv for find equivalent  opt of /y.
for file in *.mp4 ; do cmd "$file" ; done

I don't understand your do :action in the for loop, so I have substituted cmd to indicate 'do some work'. You can call external commands (multiple), have an defined function that you call OR have a multi-cmd pipeline, like
cmd1 file | filter_cmd | filter2_cmd > outfile

Because you have labels in your code (i.e. :action), you should be aware that only csh allows for goto like branching (you don't want to start coding in csh!). You'll have to refactor your code to work only inside for and while loops, relying on break and continue to change processing inside the loops.
Convert this much, then use http://shellcheck.net for errors. Post a new question with your corrected code, and show exact error messages.
IHTH


text:
Q: How can i use fluid template on command line in typo3 flow I am trying to use fluid templates on command line controller on typo3 flow. The documentation is not full. How can i tweak it and solve this.

A: Currently this is not meant to work, but if you really need this you can instanciate a Fluid StandaloneView, render it and give the result to the CommandController::output() method.


text:
Q: What is registry and how do we use to register our assets / chaincode in hyper-ledger fabric? I am trying to understand about registry, like what is registry, why do we need to store Assets and Chaincodes in registry, where does registry gets stored.

A: Firt of all, the chaincode (or smart contracts) and the assets are two different things.

*

*Chaincode: the code that you will execute/invoke. This code is the same in all the nodes, i.e. each node of the network has installed the same chaincode.

*Assets: you digitize the assets using transactions that are governed by smart contracts.

On the other hand, how it works:

*

*Ledger: the Ledger stores all the transactions. The ledger is comprised of a blockchain ('chain') to store the immutable, sequenced record in blocks. Each peer maintains a copy of the ledger.

*State Database: maintains the current state. It represents the latest values for all keys ever included in the chain transaction log. Chaincode invocations execute transactions against the current state data.


text:
Q: EntityFrameWork - I need to get a value from another table So, i need to get a value ( cNIF ) inside  table ( projetos ) and i dont really know how to get there
So far i have this:
SC3
SC2
screenshot1
im using this code for add new client and i have a dropdownlist select the client with name and nif but in projectos.aspx nothing happens and i dont know what to do :(
protected void btadd_Click(object sender, EventArgs e)
    {
        try
        {
            using (MyMoneyEntities context = new MyMoneyEntities())
            {

                project p = new project();
                p.pName = txtNome.Text;
                p.createdOn = DateTime.Now.Date;

                context.projects.Add(p);
                context.SaveChanges();

                Response.Redirect("projetos.aspx");

            }
        }
        catch (Exception ex)
        {
            utils.pnlResultadoStyle(ref divResultado, 2);
            lblResultado.Text = ex.Message + " | " + ex.InnerException;
        }
    }

This is my projectos.aspx

<asp:GridView ID="grdLista" runat="server" EmptyDataText="Não existem registos a apresentar."
            Width="100%" AutoGenerateColumns="False" CellPadding="4"
            ForeColor="#333333" GridLines="None" PagerSettings-Mode="NextPreviousFirstLast"
            PagerSettings-NextPageText="Seguinte" PagerSettings-PreviousPageText="Anterior"
            PagerSettings-Position="TopAndBottom" AllowPaging="True" PageSize="80" >
            <RowStyle BackColor="#f1f1f1" Height="30px" />
            <Columns>
                <asp:BoundField DataField="pId" HeaderText="#" />
                <asp:TemplateField HeaderText="Nome">
                    <ItemTemplate>
                        <asp:LinkButton ID="lbActualizar" PostBackUrl='<%# string.Concat("projetos-update.aspx?id=", Eval("pid").ToString()) %>'
                            runat="server" ToolTip="Editar"><%# Eval("pname").ToString() %>
                        </asp:LinkButton>
                  </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="cNIF" HeaderText="NIF Cliente" />
                <asp:BoundField DataField="createdOn" HeaderText="Criado Em" />
                <asp:TemplateField ShowHeader="False" ItemStyle-Width="20px">
                    <ItemTemplate>
                        <asp:LinkButton ID="lbDelete" Text="Apagar" runat="server"
                            OnClientClick="return confirm('Tem a certeza que deseja apagar?');" ToolTip="Apagar">
                            <i class="fas fa-trash"></i>
                        </asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

in here im loading both grids clients and projetos...

 public partial class projetos : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            loadData();
        }
    }

    private void loadData()
    {
        try
        {
            using (MyMoneyEntities context = new MyMoneyEntities())
            {
                grdLista.DataSource = context.clients.ToList();
                grdLista.DataSource = context.projects.ToList();
                grdLista.DataBind();
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);

        }
    }
}


text:
Q: Is it possible to implement custom file system adapter for state backend? Is it possible to implement custom file system adapter for state backend?
Seems like I can implement own file system adapter base on FileSystem but how to start using it in my flow for state backend?

A: In most cases you don't need to implement a custom file system implementation because Flink supports all file systems supported by Hadoop's FileSystem interface.


text:
Q: Is the following space finite-dimensional? Is the following space finite-dimensional?
$$V=\left\{f(t):[0,1]\to\mathbb{R}\mid f(0)=f'(0)=0, \int_0^1 \left(f''(u)\right)^2 \,du < \infty \right\}$$
This question is largely related to my previous question. After much thought, I tried to show the space $V$ is finite-dimensional with basis $1,t,t^2,t^3$  (even though it just does not look like one).
I considered that
$$f(t) = f(0) + f'(0)t + \int_0^t (t-u) f''(u) \,du$$
and failed to recognize the coefficients for $t^2$ and $t^3$. Any help is appreciated.

A: No. The functions $t^2, t^3, t^4, \dots$ all belong to $V$ and are linearly independent.

A: No.
For $\lambda \in \mathbb{R}$ define $f_\lambda : [0,1]\to\mathbb{R}$ as $f_\lambda(x) = e^{\lambda x} - \lambda x  - 1$, $x \in [0,1]$.
You can check that $\Big\{f_\lambda : \lambda \in \mathbb{R}\setminus\{0\}\Big\} \subseteq V$ and that it is linearly independent.


text:
Q: Automatic indentation of HTML output? I would like to automatically indent the HTML outputted by the PHP script.
I do use HTML Purifier for internal textbox input form validation, and have considered HTMLTidy. However, as the HTML purifier depends on HTML Tidy, which is not developed actively and there are a lot of bugs reported, I was looking for something else.
I have found:
https://github.com/gajus/dindent
Is this a good choice? - Is there another script or way to process the output?
As is, I am doing indentation in a quite a laborious way, for example (part of the function that takes indentation argument):
echo str_repeat("\t", $indentation) . "
\n";
foreach($result as $value)
    {
    echo str_repeat("\t", $indentation) . "\t
" . datetime_converter($value["Date"]) . " - " . $value["Article"] . "
\n";
    }
echo str_repeat("\t", $indentation) . "
";

Thanks!

A: This is my indentation function, hope it helps.
class Html {
    private static $_indent = "  ";

    private static function indentStr($indentlevel = 0){
        $replaceindent = null;

        //Sets the indentation from current indentlevel
        for($o = 0; $o < $indentlevel; $o++) {
            $replaceindent .= self::$_indent;
        }

        return $replaceindent;
    }

    public static function indent($uncleanhtml) {
        // Seperate tags
        $uncleanhtml_array = explode("<", $uncleanhtml);
        $uncleanhtml_array = array_filter($uncleanhtml_array);
        foreach($uncleanhtml_array as $unfixedtextkey => $unfixedtextvalue) {
            if(!trim($unfixedtextvalue)){
                continue;
            }

            $unfixedtextvalue = '<' . trim($unfixedtextvalue);

            //Makes sure empty lines are ignores
            if(!preg_match("/^(\s)*$/", $unfixedtextvalue)) {
                $fixedtextvalue = preg_replace("/>(\s|\t)*\n<", $unfixedtextvalue);
                $uncleanhtml_array[$unfixedtextkey] = $fixedtextvalue;
            }

        }

        //Sets no indentation
        $indentlevel = 0;
        foreach($uncleanhtml_array as $uncleanhtml_key => $currentuncleanhtml) {
            //Removes all indentation
            $currentuncleanhtml = preg_replace("/\t+/", "", $currentuncleanhtml);
            $currentuncleanhtml = preg_replace("/^\s+/", "", $currentuncleanhtml);

            $replaceindent = self::indentStr($indentlevel);

            //If self-closing tag, simply apply indent
            if(preg_match("/<(.+)\/>/", $currentuncleanhtml)) {
                $cleanhtml_array[$uncleanhtml_key] = $replaceindent.$currentuncleanhtml;
            } else if(preg_match("/<!(.*)>/", $currentuncleanhtml)) {
                //If doctype declaration, simply apply indent
                $cleanhtml_array[$uncleanhtml_key] = $replaceindent.$currentuncleanhtml;
            } else if(preg_match("/<[^\/](.*)>/", $currentuncleanhtml) && preg_match("/<\/(.*)>/", $currentuncleanhtml)) {
                //If opening AND closing tag on same line, simply apply indent
                $cleanhtml_array[$uncleanhtml_key] = $replaceindent.$currentuncleanhtml;
            } else if(preg_match("/<\/(.*)>/", $currentuncleanhtml) || preg_match("/^(\s|\t)*\}{1}(\s|\t)*$/", $currentuncleanhtml)) {
                //If closing HTML tag or closing JavaScript clams, decrease indentation and then apply the new level
                $indentlevel--;
                $replaceindent = self::indentStr($indentlevel);

                $cleanhtml_array[$uncleanhtml_key] = $replaceindent.$currentuncleanhtml;
            } else if((preg_match("/<[^\/](.*)>/", $currentuncleanhtml) && !preg_match("/<(link|meta|base|br|img|hr|\?)(.*)>/", $currentuncleanhtml)) || preg_match("/^(\s|\t)*\{{1}(\s|\t)*$/", $currentuncleanhtml)) {
                //If opening HTML tag AND not a stand-alone tag, or opening JavaScript clams, increase indentation and then apply new level
                $cleanhtml_array[$uncleanhtml_key] = $replaceindent.$currentuncleanhtml;

                $indentlevel++;
                $replaceindent = self::indentStr($indentlevel);
            } else{
                //Else, only apply indentation
                $cleanhtml_array[$uncleanhtml_key] = $replaceindent.$currentuncleanhtml;
            }
        }

        //Return single string seperated by newline
        return implode("\n", $cleanhtml_array);
    }
}

And you call this like:
Html::indent($uncleanhtml);


text:
Q: Custom backend authenticate success without returning User object I'm writing a backend to validate users based on tokens from AWS Cognito. Is it possible to write an authenticate() method for a backend that "succeeds" without returning a Django User object?
For example:
class CustomBackend(BaseBackend):
     def authenticate(self, request, username=None, password=None):
          if token_is_valid(request.COOKIES["auth_jwt"]):
              # Success, let the user through
          else:
              # Failure, redirect to login page to get token from Cognito

My understanding of "authenticate()" is that "success" is denoted by returning a User object, and failure by returning None. Can this work or do we need to make User objects based on the tokens so we have a User to return?
Edit: Found something called RemoteUserBackend, which sounds like it might be what I want, but I think has the same issue. Will leave link here in case it is relevant: https://docs.djangoproject.com/en/3.0/ref/contrib/auth/#django.contrib.auth.backends.RemoteUserBackend

A: I don't know if a "userless backend" is possible, but I solved the problem with middleware, which seems more appropriate.
class ValidateTokenMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        response = self.get_response(request)
        token = request.COOKIES.get("auth_jwt", None)

        # Here you can validate your token, redirect, set new access token, etc.


text:
Q: Can I use Cloud Functions for Firebase to run a web scraper twice a day? I'm currently trying to build a simple web scraper to get prices from Amazon (and other sites) products and save it to Firestore and use it in my Firebase app.
I was thinking about using Google App Engine to run the code (maybe update the prices twice a day).
Can I use Cloud Functions for Firebase to do that?

A: Seems to me like it might be a better fit for one or more Cloud Functions, as one of their use cases is event- or cron-driven activation, while App Engine is really intended more for web apps, although either could probably work. I'm assuming you are looking at these for their serverless and scale-to-zero properties.
You can use Cloud Scheduler and Pub/Sub to kick off the Cloud Function. See cloud.google.com/scheduler/docs/tut-pub-sub


text:
Q: Result of InternalServerError in sending Remote Push Notification to iOS using GCM in PHP I tried to implement Google Cloud Messaging (GCM) for iOS in my App. I tried the codes provided on the pod GcmExample Xcode Project and wrote a PHP script the will send the request via PHP cURL.
My PHP code is as follows:
gcmPush(
    "kU6GAbdQEg0:APA91bGSF42WITzubJ9lwQ2qUqL4ETtZfQEOthazc4tP1CRhxx8tKSRChwgtFK37-kt7RjG2P_Ncj2bDOONpPVsYkjxCNi3NDhMNWSkJ7pnlR83jdbMJfOKlD1CPXCgAvZjbwpzdeiTa",
    "This is only a test from GCM for iOS.",
    "PHP test"
    );

function gcmPush($GCM_regID, $message, $title) {

    $GOOGLE_API_KEY = "AIzaSyAd8pw7_J8i-FPswnhUMkFCDHtufSCFFTc";
    $url = 'https://android.googleapis.com/gcm/send';

    $fields = array(
        'to' => $GCM_regID,
        'notification' => array(
            'sound' => 'default',
            'badge' => '1',
            'body' => $message,
            'title' => $title
        )
    );

    $headers = array(
        'Authorization: key=' . $GOOGLE_API_KEY,
        'Content-Type: application/json'
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

    $result = curl_exec($ch);
    echo "\r\n";
    if ($result === FALSE) {
        die('Failed: ' . curl_error($ch) . "\r\n");
    } else {

        echo "Success\r\n";
    }

    curl_close($ch);
}

The request is successful, however the result from the Google GCM server contains the following:

{"multicast_id":6164898138439370127,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InternalServerError"}]}

Is there anything wrong with the Google API Key?
I tried this script to send Remote Notification to the GcmExample.xcworkspace and it worked.
I would like to know how to resolve this.

A: If your encounter this error message in GCM for iOS {"error":"InternalServerError"}, Make sure you uploaded the correct P12 certificate in the Google Developer Console. And Make sure the Provisioning Profile is setup correctly for the Signing Certificate and set the following as follows:

*

*For Development:

@{kGGLInstanceIDRegisterAPNSOption:deviceToken, kGGLInstanceIDAPNSServerTypeSandboxOption:@YES};

*For Production / Distribution:

@{kGGLInstanceIDRegisterAPNSOption:deviceToken, kGGLInstanceIDAPNSServerTypeSandboxOption:@NO};

A: A similar issue was raised on the android-gcm groups. It looks like the issue came from the certificate being used. Other members on the group resolved the issue by uploading new certificates


text:
Q: manage frames in tkinter maybe it is trivial, but I cannot wrap my head around it. I want use frames to make a gui made of

*

*2 radio buttons on the top (with an output variable)

*n var fields in the middle (with each variable coming out from the gui)

*2 radio button at the bottom

I have tried this but I cannot figure it out
import tkinter as tk
from tkinter import ttk

# -----function definition--------------------------------

# define a variable entry
def create_input_field(container, label_set):
    r = 0
    out = []
    for label in label_set:
        ttk.Label(text=label, relief=tk.RIDGE, width=15).grid(row=r, column=0)  # sticky=tk.W)
        var = ttk.Entry(text=label, textvariable=label, width=10).grid(row=r, column=1)
        out.append(var)
        r = r + 1
    return out

# define radio button for output
def create_radio_button_analysis(container):
    selected_size = tk.StringVar()
    sizes = (('uniform', 'u'),
             ('non uniform', 'nu'))

    label = ttk.Label(text="type of analysis")
    # label.pack(fill='x', padx=5, pady=5)
    for size in sizes:
        r = ttk.Radiobutton(container, text=size[0], value=size[1], variable=selected_size)
        r.grid(row=1, column=0)

if __name__ == "__main__":
    # define main window
    root = tk.Tk()
    root.title('Name window')

    frame = ttk.Frame(root)
    frame.rowconfigure(0, weight=1)
    frame.rowconfigure(0, weight=1)
    frame.rowconfigure(0, weight=1)

    # input variables
    variables = ['var_1 (unit of measure)', 'var_2 (unit of measure)', 'var_3 (unit of measure)']
    create_input_field(root, variables)

    create_radio_button_analysis(root)

    root.mainloop()

A: Here is how you can do that simply using .pack() layout manager:
from tkinter import Tk, Frame, Radiobutton, Entry

root = Tk()

frame_top = Frame(root)
frame_middle = Frame(root)
frame_bottom = Frame(root)

frame_top.pack()
frame_middle.pack()
frame_bottom.pack()

Radiobutton(frame_top, text='Radio 1 top').pack()
Radiobutton(frame_top, text='Radio 2 top').pack()

entry_lst = []
for _ in range(5):
    e = Entry(frame_middle)
    e.pack()
    entry_lst.append(e)

Radiobutton(frame_bottom, text='Radio 1 bottom').pack()
Radiobutton(frame_bottom, text='Radio 2 bottom').pack()

root.mainloop()


text:
Q: C program works on VS Code but doesn't work on Dev-C++ So I need to sum the votes received per candidate but the sum becomes negative. I tried using the debugger in Dev-C++ but the program stops after I enter the votes so I used VS Code instead to debug the program. But when I run it, the output was correct even though I didn't change any code when I opened it in VS Code. I'm using Dev-C++ 5.11 and VS Code 1.65.0. I can't switch to VS Code because my teacher requires us to use either Dev-C++ or Turbo C++. I can't use Turbo C++ as well since it freezes every time I run any program using it.
THE CODE:
/****************************************************************************

MACHINE PROBLEM 1

The results from the mayor's race have been reported by each precinct as
follows:

            Candidate   Candidate   Candidate   Candidate
Precincts   A           B           C           D
1           192         48          206         37
2           147         90          312         21
3           186         12          121         38
4           114         21          408         39
5           267         13          382         29

Write a program to do the following:

a. Print out the table with the appropriate headings for the rows and
    columns.
b. Compute and print the total number of votes received by each
    candidate and the percent of the total votes cast.
c. If any one candidate received over 50 percent of the total votes, the
   program should print a message declaring that candidate the winner.
d. If no candidate received 50 percent of the votes, the program should
    print a message declaring a run-off between the two candidates who
    received the highest number of votes; two candidates should be identified
    by their letter names.
e. Run the program once with the preceding data and once with candidate C
    receiving only 108 votes in precinct 4. (note: test values are not
    limited to the preceding data)

Note: Use Array for this machine problem

*****************************************************************************/

#include <stdio.h>
#include <windows.h>

void headings();
void cHeadings();

char candidates[4] = {'A', 'B', 'C', 'D'};
int precincts[5] = {1, 2, 3, 4, 5};
int votes[5][4];

COORD coord = {0,0};
void gotoxy(int x, int y);

int main()
{
    char border = '|';
    int i, j;

    // Print headings

    printf("---------------------------------------------------------------------------------------\n");
    printf("\t\t%c\t", border);
    headings();
    printf("\nPrecincts");
    printf("\t%c\t", border);
    cHeadings();
    printf("---------------------------------------------------------------------------------------\n");

    //// Print precinct number

    for (i = 0; i < 5; i++) {
        printf("%d", precincts[i]);
        printf("\t\t%c\t", border);
        if (i != 4)
            printf("\n");
    }

    printf("\n---------------------------------------------------------------------------------------\n");

    // Table data

    int xcoord = 24, ycoord = 4;

    for (i = 0; i < 5; i++, ycoord++) {
        xcoord = 24;
        for (j = 0; j < 4; j++, xcoord += 16) {
            gotoxy(xcoord, ycoord);
            scanf("%d", &votes[i][j]);
        }
        printf("\n");
    }

    // Total number of votes per candidate

    float sum[1][4];

    printf("\n");
    printf("----------------------------------------------------------------------------------------------\n");
    printf("\t\t\t%c\t", border);
    headings();
    printf("\t\t\t\t\t%c\t", border);
    cHeadings();
    printf("----------------------------------------------------------------------------------------------\n");
    printf("Total no. of votes\t");
    printf("%c\t", border);
    for (i = 0; i < 5; i++) {
        //j = 0;
        for (j = 0; j < 4; j++) {
            sum[0][j] += votes[i][j];
        }
    }
    for (i = 0; i < 4; i++) {
        printf("%d\t\t", (int) sum[0][i]);
    }

    printf("\n----------------------------------------------------------------------------------------------");

    return 0;
}

// Print "Candidate" headings

void headings()
{
    int i;
    for (i = 0; i < 4; i++) {
        /*if (i == 0) {
            printf("\t");
        } else {*/
            printf("Candidate\t");
        //}
        if (i == 4) {
            printf("\n");
        }
    }
}

// Print candidate letter names

void cHeadings()
{
    int i;
    for (i = 0; i < 5; i++) {
        printf("%c\t\t", candidates[i]);
        if (i == 4) {
            printf("\n");
        }
    }
}

// gotoxy()

void gotoxy(int x, int y)
{
    coord.X = x;
    coord.Y = y;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

OUTPUT (DEV-C++):
---------------------------------------------------------------------------------------
                |       Candidate       Candidate       Candidate       Candidate
Precincts       |       A               B               C               D
---------------------------------------------------------------------------------------
1               |       192             48              206             37
2               |       147             90              312             21
3               |       186             12              121             38
4               |       114             21              408             39
5               |       267             13              382             29
---------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------
                        |       Candidate       Candidate       Candidate       Candidate
                        |       A               B               C               D
----------------------------------------------------------------------------------------------
Total no. of votes      |       -2147483648             -2147483648             1429            164
----------------------------------------------------------------------------------------------
--------------------------------
Process exited after 43.82 seconds with return value 0
Press any key to continue . . .

OUTPUT (VS CODE):
---------------------------------------------------------------------------------------
                |       Candidate       Candidate       Candidate       Candidate
Precincts       |       A               B               C               D
---------------------------------------------------------------------------------------
1               |       192             48              206             37
2               |       147             90              312             21
3               |       186             12              121             38
4               |       114             21              408             39
5               |       267             13              382             29
---------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------
                        |       Candidate       Candidate       Candidate       Candidate
                        |       A               B               C               D
----------------------------------------------------------------------------------------------
Total no. of votes      |       906             184             1429            164
----------------------------------------------------------------------------------------------

A: Seems that you forgot to clean local variables before to use. Just use float sum [4] = { 0 };
It is necessary due to memory which is allocated locally would be filled by any values. C standard aware just for cleaning of global variables.


text:
Q: Synonym for "turd" Is there a countable noun with the exact same meaning as "turd" - a single, formed piece of faecal matter?
Giving the reason for this enquiry might illustrate why 'stool' doesn't really work IMO.
(1) I have an infestation of small animals in my lawn, resulting in numerous small holes about 1" in diameter. I discovered that they could be discouraged from perforating the greensward by using a trowel to stuff a firm dog turd down each hole, then covering it with a handful of earth.
(2) I was imagining how to explain the process of rolling a cigarette. My preferred method is to roll a paper into a cylinder, using a 9/32" drill as the core to roll around. After inserting a filter into one end, I roll a small quantity of tobacco into an elongated ball the size and shape of a mouse turd. This is dropped into the open end of the cylinder ready to be gently compacted by a toothpick.
I suppose 'dropping' might be a suitably ambiguous term to use in the latter case, but I can't really accept 'a stool' as the product of canine bowel evacuation.

A: I'll add an 'answer' here because it is not that easy to ascertain whether stool is actually used in count usages.
Macmillan has:

stool [noun] [countable] ...
2a piece of solid waste from someone's body
Synonyms and related words:
[Human and animal waste]: cowpat, crap, dog dirt...

While 'cowpat' is count, the other 'synonyms/related words' are almost invariably not.
I'd say that the bare noun 'stools' is the most commonly used form (as opposed to a stool or umpteen stools), in a way closely synonymous with non-count plural-form 'faeces/feces'.
But indisputably count usages can be found, for example:

He has slept considerably since he was bled, and during the night; he
  has had only three stools last night, the last of which is scanty and
  serous; the pulse is 80 ...

[Practical treatises on tropical and scorbutic dysentery; on some ...
By RW Bampfield] (admittedly from 1826).

... with the diarrhea practically resolving by the third day of treatment
  with gelatin tannate (only three stools of almost normal consistency) ...

[Case Reports in Gastrointestinal Medicine_PMC US National Library of Medicine
National Institutes of Health 2012].
'Stools' for faeces is common, but the obviously-count plural usage (a plural-form  usage with a numeral or equivalent) and 'a stool' ('a' does not always confirm a count usage, but probably would here), I'd say, pretty rare. The situation is (usually) etically count, but who's counting?


text:
Q: Rope construction of spheres Given the following theorem:

where the first variational formula is given by:

I don't understand why the second term involving the integral of the variational formula vanishes in this case. Is it missing in the statement of the theorem that $\gamma_t$ is a geodesic for all t or why else does that term vanish?


text:
Q: Al actualizar una variable del scope, actualiza otra con el mismo valor Angular2 Buenas a todos.
Yo tengo un metodo que digamos que hace algo así:
getAll(){
         this.commonServices.getAllList()
                           .subscribe(
                               res => {
                                    this.resultList= res;
                                    this.copieResultList= res;
                               },
                                err => {
                                    console.log("Error: " + err);
                                });

    }

Hasta aquí todo bien. Llamo al servicio que me va a recuperar un array de objetos y almaceno su respuesta en dos variables del scope. resultListy copieResultList. El problema es que más abajo tengo un metodo que hace:
getOne(id: string){
        this.commonService.getOne(id)
                            .subscribe(
                                res => {
                                 console.log(this.resultList);
                                    this.resultList.length = 0;
                                    this.resultList= res;
                                 console.log(this.resultList);
                                },
                                err => {
                                    console.log("Prueba error: " + err);
                                });
    }

Aquí empieza el problema. Y es que el primer console.log me imprime la lista como es lógico. Pero el segundo no, el segundo me lo muestra vacio. Es decir al haber modificado el resultList me ha modificado tambien el copieResultList

El scope no se está modificando por error en ningún otro lado del código.

¿Alguna idea?

A: Mas que un error de Scopes, es un error de concepto de programacion. Cuando vuelcas el valor de un objeto, no vuelvas el objeto en la variable si no que creas una referencia a el, lo que explica lo que te esta pasando.

Una vez que pasas la primera captura, ambos apuntan al mismo espacio
  de memoria donde se encuentra dicho objeto.

Cuando llegas a la segunda imagen, modificas resultList pero tambien afecta a copieResultList porque realmente estas modificando el objeto al que ambos estan apuntando.


text:
Q: Jetpack Compose Navigation: PopUpTo Screen from Screens that have same route except argument navigation compose version 2.4.0-alpha06
I have a Navigation Drawer using Scaffold and part of the items are dynamically generated by ViewModel.
Example items are

*

*Home

*A

*B

*C
...

*Settings

where A, B, C, ... all share same Screen called Category, with just different arguments passed (e.g. Category/A, Category/B).
Inside my Scaffold
...

val items = viewModel.getDrawerItems()
// This gives something like
// ["Home", "Category/A", "Category/B", "Category/C", ..., "Settings"]
// where each String represents "route"

...

val backstackEntry = navController.currentBackStackEntryAsState()
val currentScreen = Screen.fromRoute(
    backstackEntry.value?.destination?.route
)
Log.d("Drawer", "currentScreen: $currentScreen")

items.forEach { item ->
    DrawerItem(
        item = item,
        isSelected = currentScreen.name == item.route,
        onItemClick = {
            Log.d("Drawer", "destinationRoute: ${item.route}")
            navController.navigate(item.route)
            scope.launch {
                scaffoldState.drawerState.close()
            }
        }
    )
}

This code works pretty well, except when I visit Home screen, I want to clear all backstack upto Home not inclusive.
I've tried adding NavOptionsBuilder
...

navController.navigate(item.route) {
    popUpTo(currentScreen.name) {
        inclusive = true
        saveState = true
    }
}
...

However, this doesn't work because currentScreen.name will give something like Category/{title} and popUpTo only tries to look up exact match from the backstack, so it doesn't pop anything.
Is there real compose-navigation way to solve this? or should I save the last "title" somewhere in ViewModel and use it?
This tutorial from Google has similar structure, but it just stacks screens so going back from screen A -> B -> A and clicking back will just go back to B -> A, which is not ideal behavior for me.
Thank you in advance.

A: You can make an extension function to serve the popUpTo functionality at all places.
fun NavHostController.navigateWithPopUp(
    toRoute: String,  // route name where you want to navigate
    fromRoute: String // route you want from popUpTo.
) {
    this.navigate(toRoute) {
        popUpTo(fromRoute) {
            inclusive = true // It can be changed to false if you
                             // want to keep your fromRoute exclusive
        }
    }
}

Usage
navController.navigateWithPopUp(Screen.Home.name, Screen.Login.name)

A: When you're specifying popUpTo you should pass same item you're navigating to in this case:
navController.navigate(item.route) {
    popUpTo(item.route) {
        inclusive = true
    }
}

Also not sure if you need to specify saveState in this case, it's up to you:

Whether the back stack and the state of all destinations between the current destination and the NavOptionsBuilder.popUpTo ID should be saved for later restoration via NavOptionsBuilder.restoreState or the restoreState attribute using the same NavOptionsBuilder.popUpTo ID (note: this matching ID is true whether inclusive is true or false).

A: Inspired by @Philip Dukhov's answer, I was able to achieve what I wanted.
...

navController.navigate(item.route) {
    // keep backstack until user goes to Home
    if (item.route == Screen.Home.name) {
        popUpTo(item.route) {
            inclusive = true
            saveState = true
        }
    } else {
        // only restoreState for non-home screens
        restoreState = true
    }
...

Unfortunately, if I add launchSingleTop = true, Screen with different argument is not recomposed for some reason, but that's probably another topic.


text:
Q: Gitlab with Bash on Windows Is it possible to have Gitlab execute projects with Bash shell on Windows? I have configured my runner with the following configuration, but it doesn't work (keep on pending status):
[[runners]]
  name = "IchsanWin8Bash"
  url = "https://gitlab.local/ci"
  token = "7fa094668bd46c27e7fcf0041d328e"
  executor = "shell"
  shell = "bash"
  [runners.ssh]
  [runners.docker]
    tls_verify = false
    image = ""
    privileged = false
    disable_cache = false
  [runners.parallels]
    base_name = ""
    disable_snapshots = false
  [runners.virtualbox]
    base_name = ""
    disable_snapshots = false
  [runners.cache]
    Insecure = false

The bash command is accessible as I put this on the env PATH: C:\Users\ichsan\AppData\Local\Programs\Git\bin

A: No, that is not supported. The available shells on Windows are CMD (default) and Powershell (highly recommended).
However, you may still be able to execute Bash commands where you really need to. Since the introduction of the Windows Subsystem for Linux, you can drop down into Bash from any Windows shell on a properly configured machine. You will not be able to use Bash commands in your .gitlab-ci.yml, but you ought to be able to use them in scripts called from .gitlab-ci.yml (which you're doing anyway, right?).


text:
Q: Solving system of nonlinear equations via iteration I will give an example to illustrate the question:
Assume I have the system:
$$
xy + x + y = 7\\
x^2 + y^3 = 9
$$
and I want to solve for $x$ and $y$. It is a fairly common approach to rearrange the first equation for $x$ and the second for $y$ as follows:
$$
x = \frac{7 - y}{1+y}\\
y = (9 - x^2)^{\frac{1}{3}}
$$
then to choose a pair of starting values $x_0,y_0$ and iterate between these until (hopefully) the results converge on a solution.
For this example the solution does converge to $x = 1.91$ and $y = 1.75$ after about 15 iterations (starting with $x_0 = y_0 = 1$) and these values are indeed solutions.
My questions are:
1) When will this approach be successfull? Can we know a priori if it will be likely to work or not work on a given equation set.
2) Why does it work at all, is there any underlying theory which has been developed to understand the convergence of these schemes which iterate through a given equation set?
3) Does this approach and area have a specific name? (More specific than just 'solving systems of nonlinear equations').


text:
Q: Cannot change MenuItem background Hello I have an issue.
I cannot change background of MenuItem in XAML. I set background using many ideas and it still doesn't work. Look at the picture please, I want the hole menu and all menu items to be blue. (only background of menu changed, but menuitem didn't change)

And here is the code:
<DockPanel Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="4">
            <Menu DockPanel.Dock="Top" VerticalAlignment="Center" Style="{StaticResource menuStyle}">
                <MenuItem Header="Wygląd" Style="{StaticResource menuItemStyle}" >
                    <MenuItem Header="Motywy" Style="{StaticResource menuItemStyle}">
                        <MenuItem Header="Jasny" Style="{StaticResource menuItemStyle}"></MenuItem>
                        <MenuItem Header="Ciemny" Style="{StaticResource menuItemStyle}"></MenuItem>
                        <MenuItem Header="Domyślny" Style="{StaticResource menuItemStyle}"></MenuItem>
                    </MenuItem>
                    <MenuItem Header="PLik" Style="{StaticResource menuItemStyle}"></MenuItem>
                    <MenuItem Header="PLik" Style="{StaticResource menuItemStyle}"></MenuItem>
                    <Separator></Separator>
                    <MenuItem Header="PLik" Style="{StaticResource menuItemStyle}"></MenuItem>
                </MenuItem>
                <MenuItem Header="File" Style="{StaticResource menuItemStyle}"></MenuItem>
                <MenuItem Header="File" Style="{StaticResource menuItemStyle}"></MenuItem>
                <MenuItem Header="File" Style="{StaticResource menuItemStyle}"></MenuItem>
            </Menu>
        </DockPanel>

<Application.Resources>

        <SolidColorBrush x:Key="appBackgroundColour" Color="#FFD0E281"/>

        <Style TargetType="Menu" x:Key="menuStyle">
            <Setter Property="Background" Value="Aqua"></Setter>
        </Style>

        <Style TargetType="MenuItem" x:Key="menuItemStyle">
            <Setter Property="Background" Value="Aqua"></Setter>
        </Style>
</Application.Resources>

How to change the colour of the MenuItem background?


text:
Q: Couchdb docker container exit with code 137 but docker state shows OOMKilled false I am trying to run a hyperledger fabric network which uses couchdb as peer database.
I have prepared the network and run in my local machine, it works.
But now I want to test my network in AWS ec2 instance.
When I try to run the peer with couchdb, couchdb container get exited with error code 137.
Docker version Docker version 19.03.8, build afacb8b7f0
Docker compose version docker-compose version 1.17.1, build unknown
My docker compose file for couchdb is
version: '2'
networks:
  test-net:
services:
  peer1org_couchdb:
    container_name: peer1org_couchdb
    image: hyperledger/fabric-couchdb:latest     <----- also tried with 0.4.18
    environment:
      - COUCHDB_USER=admin
      - COUCHDB_PASSWORD=1234
    ports:
      - 1502:5984
    networks:
      - test-net

Output log during running the yaml file with the command docker-compose -f docker-compose.yaml up peer1org_couchdb
Creating peer1org_couchdb ...
Creating peer1org_couchdb ... done
Attaching to peer1org_couchdb
peer1org_couchdb      | [info] 2020-04-17T10:22:59.190969Z nonode@nohost <0.9.0> -------- Application couch_log started on node nonode@nohost
peer1org_couchdb      | [info] 2020-04-17T10:22:59.227891Z nonode@nohost <0.9.0> -------- Application folsom started on node nonode@nohost
peer1org_couchdb      | [info] 2020-04-17T10:23:00.036441Z nonode@nohost <0.9.0> -------- Application couch_stats started on node nonode@nohost
peer1org_couchdb      | [info] 2020-04-17T10:23:00.036577Z nonode@nohost <0.9.0> -------- Application khash started on node nonode@nohost
peer1org_couchdb      | [info] 2020-04-17T10:23:00.636872Z nonode@nohost <0.9.0> -------- Application couch_event started on node nonode@nohost
peer1org_couchdb      | [info] 2020-04-17T10:23:00.637081Z nonode@nohost <0.9.0> -------- Application hyper started on node nonode@nohost
peer1org_couchdb      | [info] 2020-04-17T10:23:01.089753Z nonode@nohost <0.9.0> -------- Application ibrowse started on node nonode@nohost
peer1org_couchdb      | [info] 2020-04-17T10:23:01.439671Z nonode@nohost <0.9.0> -------- Application ioq started on node nonode@nohost
peer1org_couchdb      | [info] 2020-04-17T10:23:01.439942Z nonode@nohost <0.9.0> -------- Application mochiweb started on node nonode@nohost
peer1org_couchdb      | [info] 2020-04-17T10:23:01.856778Z nonode@nohost <0.202.0> -------- Apache CouchDB 2.3.1 is starting.
peer1org_couchdb      |
peer1org_couchdb      | [info] 2020-04-17T10:23:01.856901Z nonode@nohost <0.203.0> -------- Starting couch_sup
peer1org_couchdb      | [notice] 2020-04-17T10:23:02.055980Z nonode@nohost <0.86.0> -------- config: [features] pluggable-storage-engines set to true for reason nil
peer1org_couchdb      | [notice] 2020-04-17T10:23:02.239826Z nonode@nohost <0.86.0> -------- config: [admins] admin set to -pbkdf2-427945f79512e34d95218cc52e78566b9f4d8e48,aed422e86df0741649f31a8ea008c8c5,1000 for reason nil
peer1org_couchdb      | [notice] 2020-04-17T10:23:02.913517Z nonode@nohost <0.86.0> -------- config: [couchdb] uuid set to 6ced2fbea41a5cee13aa97dca6230b80 for reason nil
peer1org_couchdb      | [info] 2020-04-17T10:23:03.923379Z nonode@nohost <0.208.0> -------- open_result error {not_found,no_db_file} for _users
peer1org_couchdb      | [info] 2020-04-17T10:23:05.113342Z nonode@nohost <0.202.0> -------- Apache CouchDB has started. Time to relax.
peer1org_couchdb      |
peer1org_couchdb      | [info] 2020-04-17T10:23:05.113411Z nonode@nohost <0.202.0> -------- Apache CouchDB has started on http://any:5986/
peer1org_couchdb      | [info] 2020-04-17T10:23:05.167998Z nonode@nohost <0.9.0> -------- Application couch started on node nonode@nohost
peer1org_couchdb      | [info] 2020-04-17T10:23:05.168038Z nonode@nohost <0.9.0> -------- Application ets_lru started on node nonode@nohost
peer1org_couchdb      | [notice] 2020-04-17T10:23:06.093559Z nonode@nohost <0.290.0> -------- rexi_server : started servers
peer1org_couchdb      | [notice] 2020-04-17T10:23:06.166401Z nonode@nohost <0.295.0> -------- rexi_buffer : started servers
peer1org_couchdb      | [info] 2020-04-17T10:23:06.166662Z nonode@nohost <0.9.0> -------- Application rexi started on node nonode@nohost
peer1org_couchdb      | [info] 2020-04-17T10:23:06.458809Z nonode@nohost <0.208.0> -------- open_result error {not_found,no_db_file} for _nodes
peer1org_couchdb      | [warning] 2020-04-17T10:23:06.458855Z nonode@nohost <0.303.0> -------- creating missing database: _nodes
peer1org_couchdb      | [info] 2020-04-17T10:23:06.860150Z nonode@nohost <0.208.0> -------- open_result error {not_found,no_db_file} for _dbs
peer1org_couchdb      | [warning] 2020-04-17T10:23:06.860194Z nonode@nohost <0.318.0> -------- creating missing database: _dbs
peer1org_couchdb      | [warning] 2020-04-17T10:23:06.860238Z nonode@nohost <0.317.0> -------- creating missing database: _dbs
peer1org_couchdb      | [info] 2020-04-17T10:23:06.969823Z nonode@nohost <0.9.0> -------- Application mem3 started on node nonode@nohost
peer1org_couchdb      | [info] 2020-04-17T10:23:06.969978Z nonode@nohost <0.9.0> -------- Application fabric started on node nonode@nohost
peer1org_couchdb      | [info] 2020-04-17T10:23:07.477864Z nonode@nohost <0.9.0> -------- Application chttpd started on node nonode@nohost
peer1org_couchdb      | [notice] 2020-04-17T10:23:08.761738Z nonode@nohost <0.372.0> -------- chttpd_auth_cache changes listener died database_does_not_exist at mem3_shards:load_shards_from_db/6(line:395) <= mem3_shards:load_shards_from_disk/1(line:370) <= mem3_shards:load_shards_from_disk/2(line:399) <= mem3_shards:for_docid/3(line:86) <= fabric_doc_open:go/3(line:39) <= chttpd_auth_cache:ensure_auth_ddoc_exists/2(line:195) <= chttpd_auth_cache:listen_for_changes/1(line:142)
peer1org_couchdb      | [error] 2020-04-17T10:23:08.767611Z nonode@nohost emulator -------- Error in process <0.373.0> with exit value:
peer1org_couchdb      | {database_does_not_exist,[{mem3_shards,load_shards_from_db,"_users",[{file,"src/mem3_shards.erl"},{line,395}]},{mem3_shards,load_shards_from_disk,1,[{file,"src/mem3_shards.erl"},{line,370}]},{mem3_shards,load_shards_from_disk,2,[{file,"src/mem3_shards.erl"},{line,399}]},{mem3_shards,for_docid,3,[{file,"src/mem3_shards.erl"},{line,86}]},{fabric_doc_open,go,3,[{file,"src/fabric_doc_open.erl"},{line,39}]},{chttpd_auth_cache,ensure_auth_ddoc_exists,2,[{file,"src/chttpd_auth_cache.erl"},{line,195}]},{chttpd_auth_cache,listen_for_changes,1,[{file,"src/chttpd_auth_cache.erl"},{line,142}]}]}
peer1org_couchdb      |
peer1org_couchdb      | [info] 2020-04-17T10:23:09.149961Z nonode@nohost <0.9.0> -------- Application couch_index started on node nonode@nohost
peer1org_couchdb      | [info] 2020-04-17T10:23:09.149989Z nonode@nohost <0.9.0> -------- Application couch_mrview started on node nonode@nohost
peer1org_couchdb      | [info] 2020-04-17T10:23:09.150041Z nonode@nohost <0.9.0> -------- Application couch_plugins started on node nonode@nohost
peer1org_couchdb      | [notice] 2020-04-17T10:23:09.824221Z nonode@nohost <0.86.0> -------- config: [features] scheduler set to true for reason nil
peer1org_couchdb      | [info] 2020-04-17T10:23:10.153499Z nonode@nohost <0.208.0> -------- open_result error {not_found,no_db_file} for _replicator
peer1org_couchdb      | [notice] 2020-04-17T10:23:10.204544Z nonode@nohost <0.406.0> -------- creating replicator ddoc <<"_replicator">>
peer1org_couchdb      | [info] 2020-04-17T10:23:10.568612Z nonode@nohost <0.9.0> -------- Application couch_replicator started on node nonode@nohost
peer1org_couchdb      | [info] 2020-04-17T10:23:10.713222Z nonode@nohost <0.9.0> -------- Application couch_peruser started on node nonode@nohost
peer1org_couchdb      | [info] 2020-04-17T10:23:11.018006Z nonode@nohost <0.9.0> -------- Application ddoc_cache started on node nonode@nohost
peer1org_couchdb      | [info] 2020-04-17T10:23:12.965526Z nonode@nohost <0.9.0> -------- Application global_changes started on node nonode@nohost
peer1org_couchdb      | [info] 2020-04-17T10:23:12.965695Z nonode@nohost <0.9.0> -------- Application jiffy started on node nonode@nohost
peer1org_couchdb      | [info] 2020-04-17T10:23:13.695403Z nonode@nohost <0.9.0> -------- Application mango started on node nonode@nohost
peer1org_couchdb      | [notice] 2020-04-17T10:23:13.763130Z nonode@nohost <0.372.0> -------- chttpd_auth_cache changes listener died database_does_not_exist at mem3_shards:load_shards_from_db/6(line:395) <= mem3_shards:load_shards_from_disk/1(line:370) <= mem3_shards:load_shards_from_disk/2(line:399) <= mem3_shards:for_docid/3(line:86) <= fabric_doc_open:go/3(line:39) <= chttpd_auth_cache:ensure_auth_ddoc_exists/2(line:195) <= chttpd_auth_cache:listen_for_changes/1(line:142)
peer1org_couchdb      | [error] 2020-04-17T10:23:13.787365Z nonode@nohost emulator -------- Error in process <0.539.0> with exit value:
peer1org_couchdb      | {database_does_not_exist,[{mem3_shards,load_shards_from_db,"_users",[{file,"src/mem3_shards.erl"},{line,395}]},{mem3_shards,load_shards_from_disk,1,[{file,"src/mem3_shards.erl"},{line,370}]},{mem3_shards,load_shards_from_disk,2,[{file,"src/mem3_shards.erl"},{line,399}]},{mem3_shards,for_docid,3,[{file,"src/mem3_shards.erl"},{line,86}]},{fabric_doc_open,go,3,[{file,"src/fabric_doc_open.erl"},{line,39}]},{chttpd_auth_cache,ensure_auth_ddoc_exists,2,[{file,"src/chttpd_auth_cache.erl"},{line,195}]},{chttpd_auth_cache,listen_for_changes,1,[{file,"src/chttpd_auth_cache.erl"},{line,142}]}]}
peer1org_couchdb      |
peer1org_couchdb      | [info] 2020-04-17T10:23:14.080708Z nonode@nohost <0.9.0> -------- Application setup started on node nonode@nohost
peer1org_couchdb      | [info] 2020-04-17T10:23:14.080874Z nonode@nohost <0.9.0> -------- Application snappy started on node nonode@nohost
peer1org_couchdb      | [notice] 2020-04-17T10:23:14.407911Z nonode@nohost <0.426.0> -------- couch_replicator_clustering : cluster stable
peer1org_couchdb      | [notice] 2020-04-17T10:23:14.535225Z nonode@nohost <0.443.0> -------- Started replicator db changes listener <0.545.0>
peer1org_couchdb exited with code 137

Docker inspect shows the following result
"State": {
            "Status": "exited",
            "Running": false,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 0,
            "ExitCode": 137,
            "Error": "",
            "StartedAt": "2020-04-17T10:22:51.714367761Z",
            "FinishedAt": "2020-04-17T10:23:16.225929262Z"
        },


text:
Q: How to get around pipe symbol (bitwise OR operator) in PHP eval'ed code Is there an equivalent in PHP for the bitwise OR operator (pipe symbol | )?  I am using wordpress insert php plugin to allow php code in my content entries on posts and pages, and the way the plugin works is to take the code and run an eval statement on it, but eval function hiccups on certain symbols like bitwise OR or double-pipe OR or dollar sign $.  I came across the problem while trying to call json_encode with some flags connected by bitwise OR and of course the eval'ed code barfed when run.  My solution is to put the code into a function (like json_encode_eval() ) and define the function in functions.php with the call to json_encode ie return json_encode($str, FLAG | ANOTHER_FLAG); , but is there a better solution?  Thanks in advance.

A: Check if wordpress is encoding the | to an html escaped code. (Look for any of
| | | | |

)
If so, you'll have to unescape it before evalling.
[I'm pretty sure there's always a better way than evalling user submitted text - you may have a huge security hole there.]
I tried this and it gives the expected answer:
<?php
eval("\$a = 2|1;");
$b = 2|1;

var_dump($a);
var_dump($b);

Outputs:
int(3)
int(3)


text:
Q: Second degree parabola Find a second degree parabola to the following data with 1999 as origin
Years 1997 1998 1999 2000 2001
Value 10   17   28   43   62
(b) What would be the equation of the second degree parabola when origin is shifted to 2001?
I HAVE PROBLEM WITH (b) part. How to shift?

A: I'm not sure what's a second degree parabola, but the parabola is $y=a+bx+cx^2$
For your question they want an origin in 1999, so it's $y=a+b(x-1999)+c(x-1999)^2$


text:
Q: Using Google Maps API to determine Longitude/Latitude for an address I have a script which uses Google Maps to determine Longitude/Latitude for a list of 3000+ addresses. It was written several years ago, and appears to no longer work. It sends requests to a URL similar to this one (using a Key I had registered):
http://maps.google.com/maps/geo?output=xml&key=123456
When I load the URL in my browser, I get a message "We're sorry but your computer or network may be sending automated queries. To protect our users, we can't process your request right now."
I think maybe that API is outdated. Digging around, I found this API which I believe is more current:
https://maps.googleapis.com/maps/api/geocode/xml?sensor=true&key=123456&address=address+goes+here
When I plug in my Key I get a message "Request Denied. The provided API key is invalid."
So maybe I just need a new Key? I am not entirely sure that what I am trying to do requires a Key at all, but if it does, I don't know which API to register.
I logged into Google, then created a new API Project. I need to add Services to my Project. There are a list of Services related to maps, here are a couple I was looking at:
Google Maps Coordinate API
Courtesy limit: 1,000 requests/day
Google Maps Geolocation API
Courtesy limit: 0 requests/day • Pricing
Google Maps JavaScript API v3
Courtesy limit: 25,000 requests/day • Pricing
If all I want to do is retrieve Longitude/Latitude, what is my best option?
Would appreciate any assistance navigating the Google maze of APIs. Thank you!

A: Some time ago i used the google maps web API to get longitude/latitude via url request.
I don't know how they feel about that number of requests, but it worked without any registration.
You want to use the google maps geocoding API to get longitude/latitude. There you find everything about the request syntax etc.

A: Adding to @HeidiSalami answer: Parsing the results using the the Deserialize method allows you to better manipulate the data:
    System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    GeoLocation GoogleGeoLocation = (GeoLocation)serializer.Deserialize(ResponseforGoogleMaps, typeof(GeoLocation));

GeoLocation class
Take note that the different names should match those in the results provided (currently that are all lower case)
    public class GeoLocation
    {
        public List<result> results { get; set; }
        public string status { get; set; }
    }

    public class result
    {
        public List<address_component> address_components { get; set; }
        public string formatted_address { get; set; }
        public geometry geometry { get; set; }
        public string place_id { get; set; }
        public string[] types { get; set; }

    }
    public class address_component
    {
        public string long_name { get; set; }
        public string short_name { get; set; }
        public string[] types { get; set; }
    }
    public class geometry
    {
        public gviewport bounds { get; set; }
        public glocation location { get; set; }
        public string location_type { get; set; }
        public gviewport viewport { get; set; }
    }

    public class gviewport
    {
        public glocation northeast { get; set; }
        public glocation southwest { get; set; }
    }

    public class glocation
    {
        public double lat { get; set; }
        public double lng { get; set; }
    }


text:
Q: Как обновить таблицу? Есть БД rk в ней таблица dbo.RDRBP. Есть ещё БД rk_new и в ней точно такая же таблица. Как обновить таблицу в rk_new из таблицы в rk.
Я написал вот это:
USE rk_new
INSERT INTO dbo.RDRBP SELECT * FROM rk.dbo.RDRBP
Но вылетает ошибка: Сообщение 8101, уровень 16, состояние 1, строка 2
Значение столбца идентификаторов в таблице "dbo.RDRBP" может указываться явно только при использовании списка столбцов и когда IDENTITY_INSERT установлен в ON.
Что делать подскажите.
A: INSERT rk_new.dbo.RDRBP
()
SELECT ..
FROM rk.dbo.RDRBP

В список столбцов напишите все важные столбцы, кроме ID. Если нужно перенести с ID, то на время переноса отключит идентити у столбца таблицы в базе rk_new


text:
Q: Installing 32-bit Wine 1.7.19 on 64-bit Ubuntu 14.04 I'm having a bad time trying to install 32-bit version of Wine 1.7.19 on a 64-bit version of Ubuntu 14.04. I've got through all the questions related to that on AskUbuntu but I haven't found a working solution probably because I did a big mess with Wine (tried to compile/install it in many ways, winetricks won't work until I use ent WINE="path" winetricks, etc).
I would like to make a cleanup of everything that's related to Wine (and its components like winetricks) and perform a clean install. I tried to install Wine through the Software Center but there's only an old version of Wine, then I uninstalled it with Software Center as well. Then I used this tutorial to compile Wine: http://www.noobslab.com/2014/05/winehq-updated-to-version-1719-install.html - I compiled it in "/home/kamil/Pobrane/wine-1.7.19" but it made a 64-bit version of Wine. So basically I have two questions:

*

*How do I clean all traces of Wine to perform a clean install?

*How do I install/compile a 32-bit version of Wine 1.7.19?

A: First, if you've made a mess, you could start cleaning your wine config:
rm -rf $HOME/.wine

Then add the oficial wine PPA to your sources:
sudo add-apt-repository ppa:ubuntu-wine/ppa -y && sudo apt-get update

Finally, install the 32 bits version.
sudo apt-get install wine1.8:i386


text:
Q: Can not install Apantan Eclipse PlugIn I am trying to install Apantana Eclipse Plugin however i am getting this error message:
Cannot complete the install because one or more required items could not be found.
Software currently installed: GWT Designer Editor 2.6.0.r36x201206111227 (com.google.gdt.eclipse.designer.editor.feature.feature.group 2.6.0.r36x201206111227)
Missing requirement: Apache Xerces-J 2.9.0.v201101211617 (org.apache.xerces 2.9.0.v201101211617) requires 'bundle javax.xml [1.3.4,2.0.0)' but it could not be found
Cannot satisfy dependency:
From: GWT Designer UiBinder Support 2.6.0.r36x201206111227 (com.google.gdt.eclipse.designer.UiBinder 2.6.0.r36x201206111227)
To: bundle org.eclipse.wb.core.xml 0.0.0
Cannot satisfy dependency:
From: GWT Designer Editor 2.6.0.r36x201206111227 (com.google.gdt.eclipse.designer.editor.feature.feature.group 2.6.0.r36x201206111227)
To: com.google.gdt.eclipse.designer.UiBinder [2.6.0.r36x201206111227]
Cannot satisfy dependency:
From: WindowBuilder Core for XML GUI's 1.5.0.r36x201206111216 (org.eclipse.wb.core.xml 1.5.0.r36x201206111216)
To: bundle org.eclipse.wst.xml.ui 0.0.0
Cannot satisfy dependency:
From: Structured Source XML Model 1.1.503.v201102102045 (org.eclipse.wst.xml.core 1.1.503.v201102102045)
To: bundle org.apache.xerces [2.9.0,3.0.0)
Cannot satisfy dependency:
From: Eclipse XML Editors and Tools 1.1.103.v201101122108 (org.eclipse.wst.xml.ui 1.1.103.v201101122108)
To: bundle org.eclipse.wst.xml.core [1.1.500,1.2.0)

I tried to add xerces (i hope i did that correctly) to classpath but i still get this error message.
System Config:
Win7 64bit
Eclipse HELIOS ver 3.6.2
Java 1.6.0_21.

I would appreciate any help/clue.
Thanks.


text:
Q: Time Complexity for Java ArrayList I found other entries for this question that dealt with specific methods, but nothing comprehensive. I'd like to verify my own understanding of the most often used methods of this data structure:
O(1) - Constant Time:
isEmpty()
add(x)
add(x, i)
set(x, i)
size()
get(i)
remove(i)

O(N) - Linear Time:
indexof(x)
clear()
remove(x)
remove(i)

Is this correct? Thanks for your help.

A: The best resource is straight from the official API:

The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.


text:
Q: Neos CMS: Extending page properties for the backend Is it possible to have a checkbox in the Neos backend for every page to show/hide some HTML and JavaScript code in the page (and even better also for all sub pages)?

A: You can add anew property for Neos.Neos:Document or create a new type and then attach it as superType to every page type you want.
Sample settings for Neos.Neos:Document:
'Neos.Neos:Document':
  ui:
    inspector:
      groups:
        globalsettings:
          label: 'My special settings'
          tab: 'default'
  properties:
    yourVariableName:
      type: boolean
      defaultValue: false
      ui:
        label: 'Hide content'
        reloadPageIfChanged: FALSE
        inspector:
          position: 10
          group: 'globalsettings'

A: If you want to check if the current or parent page has a selected value you can do this with Fusion:
nodeOrParentNodeIsChecked = ${q(node).closest('[instanceof Neos.Neos:Document][yourVariableName]').property('yourVariableName')}

Fell free to ask on https://discuss.neos.io, because this is our official forum. You'll find more information here: https://www.neos.io/docs-and-support/support.html


text:
Q: outlook web addin - cookies are cleared when task pane closed win 10 I am developing an outlook web addin, in the taskpane I have a cookie sent from the server with httpOnly. For the same session cookie is handled correctly, when I close the task pane and re-open the cookie seems to be cleared.
This does not happen on Mac, does not happen on Windows when the browser used by outlook is IE11.
Seems to be happening only when the outlook uses edge as it's engine.
Is there something I can add in the manifest perhaps to avoid this cookie clearing?

A: Adding to @BrianClink's response, the session cookie probably works on most versions that use Internet Explorer to load the add-ins. Whenever an add-in is closed, Internet Explorer stays alive for a while, which probably preserves the session cookies. Since we switched to Microsoft Edge, this is no longer the case. So please don't rely on this behavior for preserving cookies.


text:
Q: How a Host application can query a javacard applet on a simulated smartcard in Netbeans? I am a newbie in the javacard world. I have a wallet applet successfully running in netbeans (I can credit, debit,check-balance, verify pin etc using APDUs in the device console).
I am tasked to write a host application to communicate with this card in netbeans without using the smartcard console. From a little research, I figure that I have to import javax.smartcardio class into my host application, however, as you might know, there is very little documentation on this. Any assistance will be appreciated and of help to many of us who are finding it hard to delve into this world of smartcard programming. Below is my applet code. Pin was passed via parameters as 1122334455667788 via project properties.
package classicapplet1;

//package com.sun.javacard.samples.wallet;

import javacard.framework.*;

    public class Wallet extends Applet {

    // codes of CLA byte in the command APDUs

    final static byte Wallet_CLA = (byte) 0xB0;

    // codes of INS byte in the command APDUs

    final static byte VERIFY = (byte) 0x20;

    final static byte CREDIT = (byte) 0x30;

    final static byte DEBIT = (byte) 0x40;

    final static byte GET_BALANCE = (byte) 0x50;

    // maximum wallet balance

    final static short MAX_BALANCE = 10000;

    // maximum transaction amount

    final static byte MAX_TRANSACTION_AMOUNT = 100;

    // maximum number of incorrect tries before the

    // PIN is blocked

    final static byte PIN_TRY_LIMIT = (byte) 0x03;

    // maximum size PIN

    final static byte MAX_PIN_SIZE = (byte) 0x08;

    // Applet-specific status words:

    final static short SW_VERIFICATION_FAILED = 0x6300;

    final static short SW_PIN_VERIFICATION_REQUIRED = 0x6301;

    final static short SW_INVALID_TRANSACTION_AMOUNT = 0x6A83;

    final static short SW_EXCEED_MAXIMUM_BALANCE = 0x6A84;

    final static short SW_NEGATIVE_BALANCE = 0x6A85;

    // instance variables declaration

    OwnerPIN pin;

    short balance;

    /**
     *
     * called by the JCRE to create an applet instance
     */

    public static void install(byte[] bArray, short bOffset, byte bLength) {

        // create a Wallet applet instance

        new Wallet(bArray, bOffset, bLength);

    } // end of install method

    /**
     *
     * private constructor — called by the install method to
     *
     * instantiate a Wallet instance
     */

    private Wallet(byte[] bArray, short bOffset, byte bLength) {

        pin = new OwnerPIN(PIN_TRY_LIMIT, MAX_PIN_SIZE);

        // bArray contains the PIN initialization value

        pin.update(bArray, bOffset, bLength);

        // register the applet instance with the JCRE

        register();

    } // end of the constructor

    /**
     *
     * initialize the applet when it is selected
     */

    public boolean select() {

        // the applet declines to be selected

        // if the pin is blocked

        if (pin.getTriesRemaining() == 0)

            return false;

        return true;

    } // end of select method

    /**
     *
     * perform any cleanup and bookkeeping tasks before
     *
     * the applet is deselected
     */

    public void deselect() {

        // reset the pin

        pin.reset();

    }

    /**
     *
     * process APDUs
     */

    public void process(APDU apdu) {

        // APDU object carries a byte array (buffer) to

        // transfer incoming and outgoing APDU header

        // and data bytes between the card and the host

        // at this point, only the first five bytes

        // [CLA, INS, P1, P2, P3] are available in

        // the APDU buffer

        byte[] buffer = apdu.getBuffer();

        // return if the APDU is the applet SELECT command

        if (selectingApplet())

            return;

        // verify the CLA byte

        if (buffer[ISO7816.OFFSET_CLA] != Wallet_CLA)

            ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED);

        // check the INS byte to decide which service method to call

        switch (buffer[ISO7816.OFFSET_INS]) {

        case GET_BALANCE:
            getBalance(apdu);
            return;

        case DEBIT:
            debit(apdu);
            return;

        case CREDIT:
            credit(apdu);
            return;

        case VERIFY:
            verify(apdu);
            return;

        default:
            ISOException.throwIt

            (ISO7816.SW_INS_NOT_SUPPORTED);

        }

    } // end of process method

    /**
     *
     * add money to the wallet
     */

    private void credit(APDU apdu) {

        // verify authentication

        if (!pin.isValidated())

            ISOException.throwIt(SW_PIN_VERIFICATION_REQUIRED);

        byte[] buffer = apdu.getBuffer();

        // get the number of bytes in the

        // data field of the command APDU

        byte numBytes = buffer[ISO7816.OFFSET_LC];

        // recieve data

        // data are read into the apdu buffer

        // at the offset ISO7816.OFFSET_CDATA

        byte byteRead = (byte) (apdu.setIncomingAndReceive());

        // error if the number of data bytes

        // read does not match the number in the Lc byte

        if ((numBytes != 1) || (byteRead != 1))

            ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);

        // get the credit amount

        byte creditAmount = buffer[ISO7816.OFFSET_CDATA];

        // check the credit amount

        if ((creditAmount > MAX_TRANSACTION_AMOUNT)

        || (creditAmount < 0))

            ISOException.throwIt(SW_INVALID_TRANSACTION_AMOUNT);

        // check the new balance

        if ((short) (balance + creditAmount) > MAX_BALANCE)

            ISOException.throwIt(SW_EXCEED_MAXIMUM_BALANCE);

        // credit the amount

        balance = (short) (balance + creditAmount);

        return;

    } // end of deposit method

    /**
     *
     * withdraw money from the wallet
     */

    private void debit(APDU apdu) {

        // verify authentication

        if (!pin.isValidated())

            ISOException.throwIt(SW_PIN_VERIFICATION_REQUIRED);

        byte[] buffer = apdu.getBuffer();

        byte numBytes = (byte) (buffer[ISO7816.OFFSET_LC]);

        byte byteRead = (byte) (apdu.setIncomingAndReceive());

        if ((numBytes != 1) || (byteRead != 1))

            ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);

        // get debit amount

        byte debitAmount = buffer[ISO7816.OFFSET_CDATA];

        // check debit amount

        if ((debitAmount > MAX_TRANSACTION_AMOUNT)

        || (debitAmount < 0))

            ISOException.throwIt(SW_INVALID_TRANSACTION_AMOUNT);

        // check the new balance

        if ((short) (balance - debitAmount) < (short) 0)

            ISOException.throwIt(SW_NEGATIVE_BALANCE);

        balance = (short) (balance - debitAmount);

    } // end of debit method

    /**
     *
     * the method returns the wallet's balance
     */

    private void getBalance(APDU apdu) {

        byte[] buffer = apdu.getBuffer();

        // for(short i=0;i<buffer.length;i++)

        // {

        // System.out.println((byte)buffer[i]);

        // }

        // System.out.println((short)0);

        // inform the JCRE that the applet has data to return

        short le = apdu.setOutgoing();

        // set the actual number of the outgoing data bytes

        apdu.setOutgoingLength((byte) 2);

        // write the balance into the APDU buffer at the offset 0

        Util.setShort(buffer, (short) 0, balance);

        // send the 2-byte balance at the offset

        // 0 in the apdu buffer

        apdu.sendBytes((short) 0, (short) 2);

    } // end of getBalance method

    /**
     *
     * verify the PIN
     */

    private void verify(APDU apdu) {

        byte[] buffer = apdu.getBuffer();

        // receive the PIN data for validation.

        byte byteRead = (byte) (apdu.setIncomingAndReceive());

        // check pin

        // the PIN data is read into the APDU buffer

        // starting at the offset ISO7816.OFFSET_CDATA

        // the PIN data length = byteRead

        if (pin.check(buffer, ISO7816.OFFSET_CDATA, byteRead) == false)

            ISOException.throwIt(SW_VERIFICATION_FAILED);

    } // end of verify method

}

A: How the simulator works?
Netbeans uses Java Card Development kit tools to simulate Java Card. Communication with the simulator requires a little socket programming, but the JCDK provided a library for that already. It is named APDUIO. You can find it and its documentations in the JCDK.
Those ports that Netbeans assign to the simulator is 9025 (for contact) and 9026 (for contactless) by default. But you can change them simply.
How to change Java Card simulator configurations in Netbeans?
1-Go to Services tab, do a right click on Java card Runtime and then select Java Platforms:

2- Select Bundled Java Card and then click on Manage Devices:

3- There, you can change the configured ports:

How to communicate with the simulator via code?
First turn on the simulator in the Netbeans, and then run this program:
package testapduio;

import com.sun.javacard.apduio.*;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Arrays;

public class TestAPDUIO {

    public static void main(String[] args) {

        CadClientInterface cad;
        Socket sock;
        Apdu apdu = new Apdu();
        apdu.command = new byte[]{(byte) 0x00, (byte) 0xa4, (byte) 0x04, (byte) 0x00, (byte) 0x00};

        try {
            sock = new Socket("localhost", 9025);
            InputStream is = sock.getInputStream();
            OutputStream os = sock.getOutputStream();
            cad = CadDevice.getCadClientInstance(CadDevice.PROTOCOL_T1, is, os);

            byte[] ATR = cad.powerUp();
            System.out.println("Answer To Reset:\n");
            System.out.println(Arrays.toString(ATR));

            byte[] input = apdu.getDataIn();
            byte[] output = apdu.getDataOut();
            System.out.println("-----------------");
            System.out.println(input);
            System.out.println("\n");
            System.out.println(output);

            cad.exchangeApdu(apdu);
            System.out.println("-----------------");
            System.out.println(input);
            System.out.println("\n");
            System.out.println(output);

            cad.powerDown();
        } catch (Exception e) {
            System.out.println("Exception Occurred");
        }

    }

}

Note that, as you see in the imports above, you need to add the apduio library from Java Card Development Kit package, to your project'c library in Netbeans.


text:
Q: Does entire and v>0 implies f is constant? Let $f$ : $C$ to $C$ be a function. Assume that $f$ is entire and Im(f(z)) > 0 for all $z$ belongs to $C$. Does that imply $f$ is constant?
I think f will be constant,but can't deduce it
 Its easy when the imaginary part(v) is constant but does v>0 also implies that f is constant?
what if v is non-negative that is it can attain $0$ also, will the result remain same?

A:

If $f$ is a non-constant entire function then $f(\Bbb C)$ is dense in the plane.

Proof: Suppose that $f(\Bbb C)\cap D(p,r)=\emptyset$. Then  $g=\dots$ is bounded, hence $g$ is constant, so $f$ is constant.


text:
Q: Proving that the coordinate basis is a basis of a tangent space Given a differentiable manifold $M$ and some chart $(U, \psi)$ near $p$, we can consider the curve $\tilde{\beta}_i: t \mapsto \psi(p)+t e_i$, where $e_i$ denoted the standard basis in $\mathbb{R}^n$, $i \in \{1, \dots, n\}$. Now we can set $\beta_i := \psi^{-1} \circ \tilde{\beta}_i$ to get the corresponding curve on $M$ and we can define the corresponding tangent vector by
$$\left(\frac{\partial}{\partial x^i}\right)_{p,\psi} u := \left.\frac{d}{dt}\right|_{t=0} u(\beta_i(t))$$
for all $u \in C^{\infty}(M)$. We can quickly verify that this is indeed well-defined. A quick computation also shows that any linear combination of these vectors still lies in $T_pM$ and that they span $T_pM$. To show that they form a basis, it is left to show that they are linearly independent.
We have done a proof in class where at some point I must have made a typo or I simply fail to understand what is happening.

There exists a cutoff function $\rho: \mathbb{R}\to\mathbb{R}$ that is smooth and satisfies
  $$\rho(x) = \begin{cases}1 & x \in (-\frac{1}{2},\frac{1}{2})\\ 0 & x \in (-\infty, -\frac{3}{4}] \cup [\frac{3}{4},\infty)\end{cases}.$$
  For $j \in \{1,\dots,n\}$ define $\varphi_j: M \to \mathbb{R}$ by
  $$\varphi_j(q) := \begin{cases} 0 & q \notin U\\ \left(\prod_{i=1}^n \rho \left(\frac{\psi^i(q)-\psi^i(p)}{\varepsilon}\right)\right)\psi^j(q) & q \in U \end{cases}.$$
  Then, $\varphi_j \in C^{\infty}(M)$ and $$\left(\frac{\partial}{\partial x^i}\right)_{p,\psi} \varphi_j = \delta_{ij},$$
  which implies that they are linearly independent.

Question 1: What is $\varepsilon$? In an earlier class we defined tangent vectors as linear maps arising as a directional derivative along some smooth curve $\gamma: (-\varepsilon,\varepsilon)\to M$ with $\gamma(0)=p$. This doesn't make any sense in the proof because we can choose $\varepsilon$ rather freely. I am pretty sure this must be a typo, so the real question is: What should the definition of $\varphi_j$ actually be?
Question 2: What does the function $\varphi_j$ do?
Question 3: Why does $$\left(\frac{\partial}{\partial x^i}\right)_{p,\psi} \varphi_j = \delta_{ij}$$ imply that the coordinate basis vectors are linearly independent?

A: $\varepsilon$ is a parameter that ensures that $\varphi_j$ is smooth. The smoothness of $\varphi_j$ follows if the factor
$$\prod_{i = 1}^n \rho\biggl(\frac{\psi^i(q) - \psi^i(p)}{\varepsilon}\biggr)\tag{1}$$
is non-zero only on a relatively compact subset of the coordinate patch $U$. By the specification of $\rho$, that factor vanishes outside the subset $V$ of the coordinate patch $U$ corresponding to the cube with sidelength $\frac{3}{2}\varepsilon$ and centre $\psi(p)$, provided that cube is contained in $\psi(U)$. One chooses an arbitrary $\varepsilon > 0$ such that the cube $\prod \bigl[\psi^i(p)-\frac{3}{4}\varepsilon, \psi^i(p) + \frac{3}{4}\varepsilon\bigr]$ is contained in $\psi(U)$, then the function in $(1)$ has compact support in $U$, and $\varphi_j$ is smooth on the whole manifold.
The function $\varphi_j$ is a smooth extension of the coordinate function $\psi^j$ from a small neighbourhood - corresponding to $\prod \bigl( \psi^i(p) - \frac{\varepsilon}{2},\psi^i(p) + \frac{\varepsilon}{2}\bigr)$ - of $p$ to all of $M$. Since apparently the operation of tangent vectors is defined in terms of global smooth functions and not locally, we cannot directly use the coordinate functions $\psi^j$, since those are not necessarily extensible to global smooth functions. Therefore we multiply with a cutoff function to obtain a smooth extension of a restriction of $\psi^j$ to a smaller neighbourhood of $p$.
The relation
$$\biggl(\frac{\partial}{\partial x^i}\biggr)_{p,\psi} \varphi_j = \delta_{ij}\tag{2}$$
implies linear independence by the linearity of differentiation in the $\frac{\partial}{\partial x^i}$. If we have a linear relation
$$\sum_{i = 1}^n c_i \biggl(\frac{\partial}{\partial x^i}\biggr)_{p,\psi} = 0,$$
then applying that tangent vector to $\varphi_j$ yields
$$0 = \Biggl(\sum_{i = 1}^n c_i \biggl(\frac{\partial}{\partial x^i}\biggr)_{p,\psi}\Biggr)\varphi_j = \sum_{i = 1}^n c_i \Biggl(\biggl(\frac{\partial}{\partial x^i}\biggr)_{p,\psi}\varphi_j\Biggl) = \sum_{i = 1}^n c_i \delta_{ij} = c_j.$$
Doing that for all $1\leqslant j\leqslant n$ shows all coefficients $c_i$ are $0$, i.e. the linear independence.


text:
Q: Import model from inside ember-engine I have an Ember.js application with an ember-engine added as an external addon, and both the parent application and the engine share the store.
This creates an issue because when fetching a model in a route from the engine, the fact of having the store shared makes the parent application to crash saying that it does not know the model.
Copying the model from inside the engine into the parent's models fixes it, but it goes against the principle of isolation.
I wonder if there is any way of importing an engine's model into the parent application, because even if that also makes the parent aware of the engine's model, at least it won't be replicating code.
Since it is an addon, I supposed this would work:
`import DockerComposeModel from 'ember-stack-builder-engine/models/docker-compose'`

But throws an error
Error: Could not find module `ember-stack-builder-engine/models/docker-compose` imported from `bde-integrator-user-interface/application/controller`

A: Can you please show us some code How you are configuring the engine.
normally engine and app shares the model and you do not have to use import.
You can directly use this.findRecord(ModelName) but if it does not work then please share your code.


text:
Q: How to dynamically order many-to-many relationship with JPA or HQL? I have a mapping like this:
@ManyToMany(cascade = CascadeType.PERSIST)
    @JoinTable(
            name="product_product_catalog",
            joinColumns={@JoinColumn(name="product_catalog", referencedColumnName="product_catalog")},
            inverseJoinColumns={@JoinColumn(name="product", referencedColumnName="product")})
    public List<Product> products = new ArrayList<Product>();

I can fetch the products for the catalog nicely, but I can't (dynamically) order the products.
How could I order them?
I probably have to write a many-to-many HQL query with the order-by clause? I though of passing the orderBy field name string to the query, or is there a better solution?
Tables are:
products,
product_catalog,
product_product_catalog (associative table)
P.S. Using Play! Framework JPASupport for my entities.

A:
I can fetch the products for the catalog nicely, but I can't (dynamically) order the products. How could I order them?

Not possible if you let JPA retrieve the association. Mappings are static, the best thing you can do with mappings is to specify the order at "retrieve time":

9.1.28 OrderBy Annotation
The OrderBy annotation specifies the ordering of the elements of a collection valued association at the point when the association is retrieved.
@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface OrderBy {
   String value() default "";
}

The syntax of the value ordering
  element is an orderby_list, as
  follows:
orderby_list::= orderby_item [,orderby_item]*
orderby_item::= property_or_field_name [ASC | DESC]

If ASC or DESC is not specified, ASC (ascending order) is assumed.
If the ordering element is not specified, ordering by the primary key of the associated entity is assumed.
The property or field name must correspond to that of a persistent property or field of the associated class. The properties or fields used in the ordering must correspond to columns for which comparison operators are supported.
Example:
@Entity public class Course {
  ...
  @ManyToMany
  @OrderBy("lastname ASC")
  public List<Student> getStudents() {...};
  ...
}

So either use a custom finder or sort your list from Java using a Comparator.


text:
Q: How to split list of arrays into individual arrays? I got one list of arrays with two different dimensions arrays inside.
 c = [array([  3.00493560e+05,   3.04300000e+01,   3.21649837e-01,
         6.50984546e+05,   3.00493379e+05,   3.03073203e+01]), array([ 14.])]

I want to split them based on there dimensions to have two separate arrays.
   a =  array[([  3.00493560e+05,   3.04300000e+01,   3.21649837e-01,
                 6.50984546e+05,   3.00493379e+05,   3.03073203e+01]]

   b = array[([ 14.])]

I tried to use np.split(c, 6) - but it splits array based and given length and creates one big array so it's not what i am expecting.
I also tried to use
a = c[c[:, 0] < 1.5]
b = c[c[:, 1] > 5]

It works but sometimes my value from second array have same values as values from first array...

A: From my understanding, you wish to split a list of numpy arrays into individual python lists. You can do the following:
a,b = [ [individualArray] for individualArray in c]

This will give you the desired output:
a= [array([  3.00493560e+05,   3.04300000e+01,   3.21649837e-01,
             6.50984546e+05,   3.00493379e+05,   3.03073203e+01]
b= [array([ 14.])]

EDIT
In case c contains more than 2 arrays, you can generalize this approach by generating a list of split arrays:
splitArraysList = [ [individualArray] for individualArray in c ]

If the arrays are very big, you can use a generator instead of a list, to iterate on the individual arrays in the split list:
splitArraysList = ( [individualArray] for individualArray in c )

A: Maybe what you want is something like this:
a = sum([i for i in c if len(i) == 6], [])
b = sum([i for i in c if len(i) == 1], [])

If what you want is for a to be all lists with a length of 6, and b to be all list with a length of 1


text:
Q: Determine if an array of objects contains any object of another array in JavaScript Given the following two array objects:
let origArr = [ { value: 2, label: 'Dog' },
                { value: 4, label: 'Cat' },
                { value: 16, label: 'Horse' }
              ]

let newArr = [
  { value: 2, label: 'Dog' },
  { value: 3, label: 'Bird' },
  { value: 0, label: 'Fish' }
]

what would be the best way to return a new array of just the value of the difference between the origArr and the newArr, that is, where origArr element(s) are not in newArr ?
In the above example, I am after a new array called diffArr = [4,16]
Please note: that all value values within both origArr and the newArr are unique
Not sure if there is an ES2016 means?

A: You can use filter and some to do the job.

let origArr = [ { value: 2, label: 'Dog' },
                { value: 4, label: 'Cat' },
                { value: 16, label: 'Horse' }
              ]

let newArr = [
  { value: 2, label: 'Dog' },
  { value: 3, label: 'Bird' },
  { value: 0, label: 'Fish' }
]

const res = origArr.filter(x => !newArr.some(y => y.value === x.value));

console.log(res); // assuming you want the entire filtered objects

const justValues = res.map(x => x.value); // if you want just the filtered values

console.log(justValues)

some - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
filter - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

A: You can get all unique value from newArr using Set and array#map and then filter value which doesn't exist in the set and get all values.

const origArr = [ { value: 2, label: 'Dog' }, { value: 4, label: 'Cat' }, { value: 16, label: 'Horse' } ],
      newArr = [ { value: 2, label: 'Dog' }, { value: 3, label: 'Bird' }, { value: 0, label: 'Fish' } ],
      unique = new Set(newArr.map(o => o.value)),
      difference = origArr
            .filter(({value}) => !unique.has(value))
            .map(o => o.value);
console.log(difference);


text:
Q: Error using Travis CI with Sonarcloud: Not authorized. Please check the properties sonar.login and sonar.password I'm following Get started instructions on sonarcloud.io to execute the SonarQube Scanner for Maven from my computer:
mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent package sonar:sonar \
    -Dsonar.host.url=https://sonarcloud.io \
    -Dsonar.organization=ron190-github \
    -Dsonar.login=9...e

Manual execution is working:
[INFO] ANALYSIS SUCCESSFUL, you can browse https://sonarcloud.io/dashboard/index
/jsql-injection:jsql-injection

But when I'm ready to automate with Travis CI it's failing with Not authorized. Please check the properties sonar.login and sonar.password.:
[ERROR] Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.4.0.905:sonar (default-cli) on project jsql-injection: Not authorized. Please check the properties sonar.login and sonar.password. -> [Help 1]

And if I add sonar.login to the mvn command then it's working:
language: java
sudo: false
install: true

addons:
  sonarcloud:
    organization: "ron190-github"
    token:
      secure: "v...s="

jdk:
  - oraclejdk8

script:
  # JaCoCo is used to have code coverage, the agent has to be activated
  # Not working
  # - mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent package sonar:sonar
  - mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent package sonar:sonar -Dsonar.login=9...e

cache:
  directories:
    - '$HOME/.m2/repository'
    - '$HOME/.sonar/cache'

I have also used the example script.
Do you know why secure token is ignored and why it's failing with default config?

A: It seems that the tag secure is not working, use a repo variable instead:
language: java
sudo: false
install: true

addons:
  sonarcloud:
    organization: "ron190-github"

jdk:
  - oraclejdk8

script:
  # JaCoCo is used to have code coverage, the agent has to be activated
  - mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent package sonar:sonar -Dsonar.login=${SONAR_TOKEN}

cache:
  directories:
    - '$HOME/.m2/repository'
    - '$HOME/.sonar/cache'

A: I agree with Santhosh Tpixler that your problem is likely with the Travis encryption of the token. In my case I need travis-ci.com (opposed to travis-ci.org, see https://devops.stackexchange.com/q/1201), therefore had to use the --pro flag.
From inside the project directory I used these commands:
travis login --pro
travis encrypt --pro <your-hexadecimal-token>

A: The problem is with the travis encryption.
Correct encryption syntax:
travis encrypt 309473973909Z09R830 -r my-org/my-repo
No variable name, no quote.
If you are running travis encrypt inside your repo directory you can just use
travis encrypt 309473973909Z09R830
Kindly replace you token for 309473973909Z09R830
The above trick worked for me. Thought of making it more visible to the public.
Credits: @ron190