text:
Q: Change button background color as if pressed, but without the user pressing it On Android, a Button changes its background color when pressed.
How can we tell a button that it is pressed (without firing the onClick-action), so that it changes color, without the user pressing it? (for example triggered by a swipe action)
It should change color briefly, and then change back.
There a quite a few questions concerning keeping the pressed state. This question asks, how to set the button_pressed state briefly, as if clicked, but without a real click.
Button.setPressed(true) has not given a color change, neither has Button.performClick().

A: First, create the effect when button is hovered, clicked etc in XML. Put this style in your drawable.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Pressed button -->
    <item android:drawable="@color/dark_green"
        android:state_focused="true"
        android:state_pressed="false"
        />
    <item android:drawable="@color/dark_green"
        android:state_focused="true"
        android:state_pressed="true"
        />
    <item android:drawable="@color/dark_green"
        android:state_focused="false"
        android:state_pressed="true"/>

    <!-- Normal button -->
    <item android:drawable="@color/green"
        android:state_focused="false"
        android:state_pressed="false"/>
</selector>

Then in your XML, initiates the style by using:
<Button
 android:layout_width="wrap_content"
 android:layout_height="match_parent"
 android:background="@drawable/the_style_in_drawable"
 android:text="click"/>

By putting the style in your XML, you don't have to initiate the style when button on click. Android will detect the button state and do the work for you. Just remember to put the state in selector.

A: To change a button state without anything else is done via
btn1.getBackground().setState(new int[]{android.R.attr.state_pressed});

To reset to ordinary, you use
btn1.getBackground().setState(new int[]{android.R.attr.state_enabled});

A Button's states can be found out via
btn1.getBackground().getState();

which resturns an int[]. You can compare its values to android.R.attr to find out which states are set.
Example Code

private void simulateClick(final ImageButton button,
                           final long clickDuration) {
    button.getBackground().setState(new int[]{android.R.attr.state_pressed});
    new Thread(new Runnable() {
        public void run() {
            try {
                Thread.sleep(clickDuration);
            } catch ( InterruptedException e ) {
                // not bad if interrupted: sleeps a bit faster (can happen?)
            }
            Count.this.runOnUiThread(new Runnable() {
                    public void run() {
                        button.getBackground().setState(new int[]{android.R.attr.state_enabled});
                    }
                });
        }}).start();
}

Explanation
Each View has a Drawable as background image. A Drawable can be of different subtypes, here it is a StateListDrawable, as defined per XML. (See @Lynx's answer as an example of a XML defined drawable).
This Drawable can be told which state it is to assume (via setState) and does the layout itself.

A: AsyncTask for button color change illusion:
private class ChangeButtonColorMomentarily extends AsyncTask<String, Void, String> {

    @Override
    protected void onPreExecute() {
        btn1.setBackgroundDrawable(new ColorDrawable(Color.rgb(50, 50, 50)));//pressed state
    }

    @Override
    protected String doInBackground(String... params) {
        try {
            Thread.sleep(1000);
        } catch (Exception e) {

        }
        return "";
    }

    @Override
    protected void onPostExecute(String result) {
        btn1.setBackgroundDrawable(new ColorDrawable(Color.rgb(200, 200, 200)));//normal state
    }

}

Also take note that if your API 16 above use setBackground() instead.

A: For changing the color of button at that time, you can use setOnTouchListener as:
button.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if(event.getAction() == MotionEvent.ACTION_DOWN){
                //Button Pressed
            }
            if(event.getAction() == MotionEvent.ACTION_UP){
                 //finger was lifted
            }
            return false;
        }
    });


text:
Q: Python 2.7 error: Indentation error I am working with an example file of a Tkinter layout. I keep getting an error that is boggling my mind.
the code worked until I inserted the statements:
area.pack()
area.insert(end, "hello")

then I got the error:
Indentation error: unexpected indentation.

ok, so I commented the two statements out (as shown below), to get what is essentially the exact same code I started with, which worked fine- only to keep getting the same error again. I have played around with it for a few hours now and I simply can't grasp the - im sure- really simple thing that is really triggering this. Any thoughts?
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode Tkinter tutorial

In this script, we use the grid
manager to create a more complicated
layout.

author: Jan Bodnar
last modified: December 2010
website: www.zetcode.com
"""

from Tkinter import Tk, Text, BOTH, W, N, E, S
from ttk import Frame, Button, Label, Style

class Example(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent

        self.initUI()

    def initUI(self):

        self.parent.title("Windows")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

        self.columnconfigure(1, weight=1)
        self.columnconfigure(3, pad=7)
        self.rowconfigure(3, weight=1)
        self.rowconfigure(5, pad=7)

        lbl = Label(self, text="Windows")
        lbl.grid(sticky=W, pady=4, padx=5)

        area = Text(self)
        area.grid(row=1, column=0, columnspan=2, rowspan=4,
            padx=5, sticky=E+W+S+N)

        #area.pack()
        #area.insert(end, "hello")

        abtn = Button(self, text="Activate")
        abtn.grid(row=1, column=3)

        cbtn = Button(self, text="Close")
        cbtn.grid(row=2, column=3, pady=4)

        hbtn = Button(self, text="Help")
        hbtn.grid(row=5, column=0, padx=5)

        obtn = Button(self, text="OK")
        obtn.grid(row=5, column=3)

def main():

    root = Tk()
    root.geometry("350x300+300+300")
    app = Example(root)
    root.mainloop()

if __name__ == '__main__':
    main()

A: You're mixing tabs and spaces.  Don't do that :-) 1
For future reference, run the code with python -tt instead of just python2.  If you mix tabs and spaces python -tt will yell at you and tell you to fix it rather than giving strange indentation errors.

1Don't do that in any language.  It only leads to pain and suffering.
2I believe that this is the default behavior for python3.x.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to dynamically create elements in VTK? I've been trying to create primitives from a text input file in VTK. It means, That my input file could be for example:
cube s x y z
sphere r x y z
cube s x y z
cone r h x y z

Where I have the name of the element and some attributes such as Position, radius, etc, depending on the primitive. All I have done so far is to put 1 actor for each primitive in the same rendered scene. So my program would draw a cube, a sphere and a cone based on the example above. However what I want to accomplish is to dynamically draw whatever the input says.
I supposse I have to create an actor for every object in the scene. However I don't know how many objects the input indicates before running it. I was thinking about a list of actors (because I can push as many actors to the list as the input says), but I'm not sure if it's neccessary.
Need big help over here. ty

A: What you need a vtkActorCollection. Think of it as a list of actors. You will supply the number of actors (the number of your premitives), and iterate through the collection and connect a suitable source to it.


text:
Q: Deploy multiple dacpac files to a single database I want to automate my database deployment on our CI server. I wrote a powershell script to deploy a dacpac file to the the database on the sql server. But now I am in a strange position where I have two separate dacpac files and want to deploy them to a single database (I cant use a single dacpac due to our software design). If I deploy them one by one, it removes the objects created from the first dacpac. So any help here is highly appreciated.
If there are other ways to combine two dacpac files and deploy them using any commands or scripts, please reply your suggestions.
I am using the below powershell script to deploy single dacpac to the database.
$sqlPackagePath = "C:\Program Files (x86)\Microsoft SQL Server\110\DAC\bin\Microsoft.SqlServer.Dac.dll";
$sqlServer = "localhost";
$dacpacPath = "mydatabase.dacpac"
$database = "TestDatabase"

add-type -path $sqlPackagePath
$dacService = new-object Microsoft.SqlServer.Dac.DacServices "server=$sqlServer"
$dp = [Microsoft.SqlServer.Dac.DacPackage]::Load($dacpacPath)
$dacService.deploy($dp, $database, "True")

A: By default, publishing a dacpac does not drop extra objects.  There's a setting that you must explicitly choose to enable that behavior (it's called "drop objects not in source" and it's false by default).
You are, though, using an old (SQL Server 2012) version of Microsoft.SqlServer.Dac to perform this operation so perhaps the behavior of that version differs from the newer versions.
The latest version of the Data-Tier Application Framework (Microsoft.SqlServer.Dac) is available here: https://www.microsoft.com/en-us/download/details.aspx?id=55088
After installation the new version of Microsoft.SqlServer.Dac will be in Microsoft SQL Server\140\DAC\bin


text:
Q: Impossible to place lstinputlisting correctly I have this code in a document :
\begin{figure}
    \center
    \includegraphics[scale=0.5]{images/image.jpg}
    \caption{image}
\end{figure}

The content of file.sh :
\begin{figure}
    \lstinputlisting[language=Bash,caption={mycaption}]{file.sh}
\end{figure}
Blablabla

The source code is placed after the text Blablabla and on a single page. This text containt a classic text, a section. It should be placed just after the image. Morever, the source code is cut at end of page and it's missing the half of code... This are the logs :
<images/image.jpg, id=122, 442.65375pt x 492.84125pt>
File: images/image.jpg Graphic file (type jpg)
<use images/image.jpg>
Package pdftex.def Info: images/image.jpg used on input line 292.
(pdftex.def) Requested size: 221.32632pt x 246.42001pt.
(/usr/share/texlive/texmf-dist/tex/latex/listings/lstlang1.sty
File: lstlang1.sty 2015/06/04 1.6 listings language file
)
(/usr/share/texlive/texmf-dist/tex/latex/listings/lstlang1.sty
File: lstlang1.sty 2015/06/04 1.6 listings language file
)
Package hyperref Info: bookmark level for unknown lstlisting defaults to 0 on i
nput line 298.
LaTeX Font Info: Try loading font information for T1+cmtt on input line 298.
(/usr/share/texlive/texmf-dist/tex/latex/base/t1cmtt.fd
File: t1cmtt.fd 2014/09/29 v2.5h Standard LaTeX font definitions
)
(./file.sh)
LaTeX Warning: Float too large for page by 705.87885pt on input line 299.
[9]

I am going crazy. Hope you can help me.

A: If LaTeX is supposed to keep the strict order image-listing-Blablabla, don't use any figure environments. Everything that you wrap into a figure environment will have a certain inclination to move around to where TeX thinks it fits best; moreover, the contents of a figure environement does not  break across pages.

\documentclass{article}
\usepackage{caption}% For the \captionof command, to be used outside of figures
\usepackage{graphicx}
\usepackage{listings}
\begin{document}
\begin{center}
    \includegraphics[scale=0.5]{example-image}
    \captionof{figure}{image}
\end{center}

The content of file.sh :
    \lstinputlisting[language=Bash,caption={mycaption}]{file.sh}
Blablabla
\end{document}


text:
Q: How to get specific files in SFTP using regex I am trying to get files from specific range date (11-OCT to 15-OCT) using SFTP via SecureCRT:
File name: PEM_CUST_REC_G0X_20181016XXXXXX.gz

*

**20181016 represents the file date (YYYYMMDD).

*X represents varied values.

I am doing:
#> get PEM_CUST_REC_G0?_201810(1[1-5])*.gz
#> //System could not find specific file

A: The get command in sftp does not understand regular expressions, but can take ordinary filename globbing patterns.
In your case:
get PEM_CUST_REC_G0?_2018101[1-5]??????.gz

The ? pattern matches exactly one character and 2018101[1-5] would match the dates from the 11th to the 15th (inclusively) of October in 2018.
See also the sftp manual on your system (man sftp).


text:
Q: Cannot find module 'react-dev-utils/crossSpawn' exception React App I downloaded the installer node-v10.6.0-x64 and create-react-app-master package for working on React Application. After creating React App project on PhpStorm, I had the exception like this:
internal/modules/cjs/loader.js:582
    throw err;
    ^

Error: Cannot find module 'react-dev-utils/crossSpawn'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:580:15)
    at Function.Module._load (internal/modules/cjs/loader.js:506:25)
    at Module.require (internal/modules/cjs/loader.js:636:17)
    at require (internal/modules/cjs/helpers.js:20:18)
    at Object.<anonymous> (D:\Projects\ReactProjects\create-react-app-master\packages\react-scripts\bin\react-scripts.js:18:15)
    at Module._compile (internal/modules/cjs/loader.js:688:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
    at Module.load (internal/modules/cjs/loader.js:598:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
    at Function.Module._load (internal/modules/cjs/loader.js:529:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ start: `cd packages/react-scripts && node bin/react-scripts.js start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm WARN Local package.json exists, but node_modules missing, did you mean to install?

I tried writing to the terminal of PhpStorm:
npm install --save-dev react-dev-utils

but it doesn't help.
How to solve this?

A: Delete node_modules folder and run "npm install" .  Hope this will work


text:
Q: Which threading mode is Sqlite for iOS compiled in Swift? The page http://www.sqlite.org/threadsafe.html mentions:
Single-thread
Multi-thread
Serialized
How can we implement that threads in Swift. Or how to use sqlite3_config(SQLITE_CONFIG_MULTITHREAD in Swift

A: Instead of sqlite3_config you can add the required options when opening the database. This is only available for sqlite3_open_v2, not for sqlite3_open or sqlite3_open16.
Here is an example:
let rc = sqlite3_open_v2(databasePath, &db, SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE|SQLITE_OPEN_FULLMUTEX, nil)

A: For anyone who ended up here looking for a way to call sqlite3_config (regardless of the threading question) using the built-in SQLite3 module...
The reason it's not available is that it uses ellipsis-style variadic arguments, which according to this are not supported in Swift.  One way to get around this is to make your own C header with wrapper functions for calling sqlite3_config with whatever (non-variadic) argument arrangement you need.
For example, a "bridging header" with something like this covers all the valid call signatures you might need (as far as what the SQLite config options require):
#ifndef SqliteConfig_h
#define SqliteConfig_h

#import "sqlite3.h"

static inline int sqlite3_config_no_args(int op) {
    return sqlite3_config(op);
}

static inline int sqlite3_config_ptr(int op, void* arg1) {
    return sqlite3_config(op, arg1);
}

static inline int sqlite3_config_int(int op, int arg1) {
    return sqlite3_config(op, arg1);
}

static inline int sqlite3_config_ptr_int_int(int op, void* arg1, int arg2, int arg3) {
    return sqlite3_config(op, arg1, arg2, arg3);
}

static inline int sqlite3_config_int_int(int op, int arg1, int arg2) {
    return sqlite3_config(op, arg1, arg2);
}

static inline int sqlite3_config_ptr_ptr(int op, void* arg1, void* arg2) {
    return sqlite3_config(op, arg1, arg2);
}

#endif /* SqliteConfig_h */

Maybe there are cleaner or more idiomatic ways to create these kinds of wrappers (rather than static-inline functions in a bridging header).  I'm not an expert in this area.  But considering they're just wrapping calls, it seems like a good lightweight workaround.
You can search around for more info on bridging headers if you don't know how to create one.  But in short:  You can create a bridging header "manually" (after creating your .h file) by going to Build Settings/Swift Compiler - General/Objective-C Bridging Header and setting the value to the header filename you created.  If you don't do that, your .h file is ignored.  Or you could create one automatically (without going into the compiler settings) by dragging a dummy .c file into the project, deleting that file, and then editing the header it created.  Or do that with a "real" C file if you prefer your code there rather than inline.
With that in place, here's an example of using sqlite3_config to install your own logging callback:
import SQLite3

func errorLogCallback(_: OpaquePointer?, iErrCode: Int, zMsg: UnsafePointer<CChar>)
{
    let s = String(cString: zMsg)
    print("LOG:", iErrCode, s)
}

let cCallbackPtr: @convention(c) (OpaquePointer?, Int, UnsafePointer<CChar>) -> () = errorLogCallback
let rawPtr = unsafeBitCast(cCallbackPtr, to: UnsafeMutableRawPointer.self)
sqlite3_config_ptr_ptr(SQLITE_CONFIG_LOG, rawPtr, nil)


text:
Q: Make a folder access case insensitive on Linux ext4 I'm trying to run a mod for a game on Linux and this mod reads files from a texture folder in a case insensitive manner (the mod runs on Windows as well).
I was wondering if there was a way to expose this folder to the game in a case insensitive way. Perhaps as some kind of symlink or a script that to_lower()s the file name access.
Would such a thing be possible?
The problem was also reported on steam, which you can look for more details: https://steamcommunity.com/workshop/filedetails/discussion/1800248038/1640917196996115981/

A: Starting with Linux 5.3, ext4 has support for case-insensitive directories.  This work was contributed by Gabriel Bertazi of Collabora, and the work was funded by a company that ports Windows games to Linux.  You'll want to use at e2fsprogs 1.45.4.
Linux 5.4 will likely be the next long-term stable kernel, so this feature should start showing up in distributions next year.

A: Your best bet is probably to mount an exfat or vfat filesystem which is case insensitive.  You can either use a partition or maybe use a file as a block device, and format as exfat or vfat
You can probably (I've not tried it, but it makes sense) use http://www.brain-dump.org/projects/ciopfs/ to use FUSE to make a lowercase version of the filesystem - although this working will depend, I expect, on the program asking for lowercase files. It has the advantage of being an overlay, so not creating disk requirements.


text:
Q: Bootbox modal is not scrollable after a second modal is opened JS fiddle: http://jsfiddle.net/9y7nrx9m/2/
I am creating a bootbox dialog initially:
// First dialog
bootbox.dialog({
    message: '<input type="button" value="Open second modal" class="second" />' + '<br/>bar'.repeat(100),
    allowCancel: true
});

Scrolling now affects the dialog box and the web page stays in position.
// Second dialog
bootbox.dialog({message: "Second dialog!", allowCancel: true});

After creating another bootbox dialog/alert/prompt and closing it, scrolling no longer affects the first dialog box. The web page contents move and the first dialog just stays frozen (unexpected behavior). How do I fix this?
Any buttons that are visible on the first dialog can be clicked on and buttons on the main page aren't clickable (expected behavior).

A: Bootstrap modal are made of single modal viewing, but if we want to show modal over modal then when the current modal gets close the dom gets reset and from body tag modal-open will be removed which caused scrolling issues.
Solution 1
While closing of the second modal at modal-open to body.
 $('.bootbox.modal').on('hidden.bs.modal', function () {
  if($(".modal").hasClass('in')){
             $('body').addClass('modal-open');
         }
})

Solution 1
Solution 2
You can achieve the same with css as well.
.bootbox.modal{
  overflow: auto !important;
}

This will make modal scrollable but there will be 2 scroll bars.
Solution 2
-Help :)

A: Based on Help answer , in bootstrap 4 you have to use
$(document).on('hidden.bs.modal', '.bootbox.modal', function (e) {
        if($(".modal").hasClass('show')) {
            $('body').addClass('modal-open');
        }
})

A: In bootstrap 3 you have to use this code:
$(document).on('hidden.bs.modal', '.bootbox.modal', function (e) {
        if($(".modal").hasClass('in')) {
            '$('body').addClass('modal-open');
        }
});


text:
Q: Bootstrap confirmation won´t work Inside my main-page (bootstrap-confirmation script included below) there are some Tabs where the content is loaded by ajax GET method.

Script for loading Tabs content:
$("#tab_open").load("noticelist.php?status=0", function (result) {
  App.blockUI({target: "#tab_content",animate: true});
  $("#tab_open").tab("show");
  App.unblockUI("#tab_content");
});
$(\'[data-toggle="tabajax"]\').click(function(e) {
    App.blockUI({target: "#tab_content",animate: true});
    var $this = $(this),
        loadurl = $this.attr("href"),
        targ = $this.attr("data-target");
    $.get(loadurl, function(data) {
        $(targ).html(data);
    });
    $this.tab("show");
    App.unblockUI("#tab_content");
    return false;
});

Inside each Tab there is this link with a bootstrap-confirmation:
<a class="btn btn-icon-only red-mint deleteit" id="delete_'.$val['DS'].'"
                      data-toggle="confirmation"
                      data-popout="true"
                      data-btn-ok-label="'.T::ACTIONS_3.'"
                      data-btn-cancel-label="'.T::ACTIONS_4.'"
                      data-original-title=""
                      data-on-confirm="shortwork"
                      data-job-id="del"
                      data-id="'.$val['DS'].'"
                      title="'.T::SYSMSG_0.'"
                      href="#"
                      >

When I click at the button nothing happens and the error-console is empty. I'm unsure what is wrong?
If I add the button directly into the main page, the confirmation will show correctly, why doesn't it work inside the ajax loading content method?

A: Adding this code to the php-file wich given the content solved that problem.
$('[data-toggle=confirmation]').confirmation({ btnOkClass: 'btn btn-sm btn-success', btnCancelClass: 'btn btn-sm btn-danger'});


text:
Q: Java Process IO Im using java to start a GNOME terminal process in linux and redirecting its input and output to my code. Below is a code.
        public static void main(String[] args) throws InterruptedException
    {
        // TODO Auto-generated method stub  /usr/bin/telnet
        try
        {
            String line, commandInput;
            Scanner scan =  new Scanner(new File("/home/Ashutosh/Documents/testfile"));
            ProcessBuilder telnetProcessBuilder = new ProcessBuilder("/bin/bash");///home/Ashutosh/Documents/tempScript");
            telnetProcessBuilder.redirectErrorStream(true);
            Process telnetProcess = telnetProcessBuilder.start();
            //Process telnetProcess = Runtime.getRuntime().exec("xterm");///home/Ashutosh/Documents/tempScript");
            BufferedReader input = new BufferedReader(new InputStreamReader(telnetProcess.getInputStream()));
            BufferedWriter output = new BufferedWriter(new OutputStreamWriter(telnetProcess.getOutputStream()));
            while(scan.hasNext())
            {
                commandInput = scan.nextLine();
                output.write(commandInput);
/*              if(commandInput.trim().equals("exit"))
                {
                    output.write("exit\r");
                }
                else
                {
                    output.write("((" + commandInput + ") && echo --EOF--) || echo --EOF--\r");
                }
*/              output.flush();
                line = input.readLine();
                while(line != null && !line.trim().equals("--EOF--"))
                {
                    System.out.println(line);
                    line = input.readLine();
                }
                if(line == null)
                    break;
            }
/*          Thread.sleep(500);
            output.write("/home/Ashutosh/Documents/testfile\r");
            Thread.sleep(500);
            output.flush();

            while((line = input.readLine())!= null)
                System.out.println(line);
            telnetProcess.destroy();
*/          //String s = input.readLine();
            //System.out.print(s + "\r\n");
            //s = input.readLine();
            //System.out.print(s + "\r\n");
        }

the contents of testfile which is bash script is
#!/bin/bash

ls -l
pwd
date
exit

and i also tried the following interactive script which takes input from user which i want to redirect from java code is given
#! /bin/bash
echo "Input any number form 0-3:"
read num
case $num in
  0) echo "You are useless";;
  1) echo "You are number 1";;
  2) echo "Too suspecious";;
  3) echo "Thats all man, got to go...!";;
  *) echo "Cant't u read english, this is wrong choice";;
esac
read
exit

my code stops at input.readLine(); im not sure but i think i am not able to redirect the output stream
output.write(commandInput);

command is executing well but did not write i intended to on the process redirected input, that is why it hangs at readLine();.
If somebody have already solved please let me know the solution.
From following link i tried to solve the issue but still no luck:
Java Process with Input/Output Stream
Thanks
Ashutosh

A: readLine() read the contents of a line, without the newline at the end.
write() writes just the text, it doesn't add a new line.
Perhaps you want to add write("\n"); or use PrintStream or PrintWriter.
I imagine, your script is being sent as
#!/bin/bashls -lpwddateexit

which is a comment without a newline.

A: EDIT: Huge error, not adding the command to the ProcessBuilder!!
Why are you not just running your script as a Linux script? That is,
ProcessBuilder builder = new ProcessBuilder();
LinkedList<String> command = new LinkedList<String>();
command.add("/bin/bash");
command.add("/home/Ashutosh/Documents/testfile");
builder.command(command);

Process myProc = builder.start();

Also, I notice the variable is named 'telnetProcess' yet there is no invocation of telnet anywhere that I can see. Perhaps this is the problem?
EDIT: Added my suggestion below for the interactive script.
ProcessBuilder builder = new ProcessBuilder();
LinkedList<String> command = new LinkedList<String>();
command.add("/bin/bash");
command.add("/path/to/interactiveScript");
builder.command(command);

final Process myProc = builder.start();

// Java input goes to process input.
Thread inputParser = new Thread() {
  public void run() {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(myProc.getOutputStream()));
    String line = "";
    while(line != null) {
      line = br.readLine();
      bw.write(line);
      bw.newLine();
    }
  }
}.start();

// Process output must go to Java output so user can see it!
Thread outputParser = new Thread() {
  public void run() {
    BufferedReader br = new BufferedReader(new InputStreamReader(myProc.getInputStream()));
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
    String line = "";
    while(line != null) {
      line = br.readLine();
      bw.write(line);
      bw.newLine();
    }
  }
}.start();

A: hi guys sorry for late response, after some trials i got it working. I am simply letting the process completing its process and exit normally rather than forcefully and then the BufferedReader and BufferedWriter keeps the string buffers in RAM which i can read now after process exit with code 0.
public static void main(String[] args) throws InterruptedException
{
    // TODO Auto-generated method stub
    try
    {
        String line, commandInput;
        ProcessBuilder telnetProcessBuilder = new ProcessBuilder("/bin/bash");
        telnetProcessBuilder.redirectErrorStream(true);
        Process telnetProcess = telnetProcessBuilder.start();
        BufferedReader input = new BufferedReader(new InputStreamReader(telnetProcess.getInputStream()));
        BufferedWriter output = new BufferedWriter(new OutputStreamWriter(telnetProcess.getOutputStream()));
        commandInput = "ls -l\n";
        output.write(commandInput);
        output.flush();
        commandInput = "pwd\n";
        output.write(commandInput);
        output.flush();
        commandInput = "whoami\n";
        output.write(commandInput);
        output.flush();
        commandInput = "exit\n";
        output.write(commandInput);
        output.flush();
        while((line = input.readLine())!= null)
            System.out.println(line);
    }
}


text:
Q: Deserialize dynamic object from request to strong type I'm trying to implement API endpoint that should allow dynamic object in request body.
Example of body 1:
{
  "type": "CallStart",
  "attributes": {
      "Name": "Test",
      "Time": "09:15"
  }
}

Example of body 2:
{
  "type": "CallEnd",
  "attributes": {
      "Name": "Test",
      "SendFeedback": true
  }
}

So, I created model for this:
public class CommandRequest
{
    public CommandType Type { get; set; }
    public dynamic Attributes { get; set; }
}

Then I have tried to write something like this
[HttpPost("id")]
public async Task<IActionResult> Commands([FromRoute] string id, [FromBody] CommandRequest requestBody)
{
    object command = null;
    switch (requestBody.Type)
    {
        case CommandType.CallStart:
            command = new Command<CallStartAttributes>
            {
                Type = requestBody.Type,
                Id = id,
                Attributes = JsonConvert.DeserializeObject<CallStartAttributes>(requestBody.Attributes)
            };
            break;
        case CommandType.CallEnd:
            command = new Command<CallEndAttributes>
            {
                Type = requestBody.Type,
                Id = id,
                Attributes = JsonConvert.DeserializeObject<CallEndAttributes>(requestBody.Attributes)
            };
            break;
        default: throw new NotImplementedException();
    }

    await _mediator.Send(command);
    return Ok();
}

All models
public class Command<TAttributes> : IRequest
{
    public string Id { get; set; }
    public CommandType Type { get; set; }
    public TAttributes Attributes { get; set; }
}
public class CallStartAttributes
{
    public string Name { get; set; }
    public string Time { get; set; }
}
public class CallEndAttributes
{
    public string Name { get; set; }
    public bool SendFeedback { get; set; }
}

It doesn't work in this way. Error:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: The best overloaded method match for 'Newtonsoft.Json.JsonConvert.DeserializeObject<Core.Features.CallStartAttributes>(string)' has some invalid arguments

How can I deserialise dynamic object to strong type?
I would prefer to not change this
public dynamic Attributes { get; set; }

to this
public string Attributes { get; set; }

A: Since DeserializeObject always expects a string, why not serialize dynamic to string. Perhaps bit hacky but this would work:
JsonConvert.DeserializeObject<CallEndAttributes>(JsonConvert.SerializeObject(
requestBody.Attributes))

JsonConvert.DeserializeObject<CallStartAttributes>(JsonConvert.SerializeObject(
requestBody.Attributes))

Minimal reproducible code of your problem that I tried:
using Newtonsoft.Json;
using System;

namespace SO
{
    public enum CommandType
    {
        CallStart, CallEnd
    }
    public class CommandRequest
    {
        public CommandType Type { get; set; }
        public dynamic Attributes { get; set; }
    }
    public class Command<TAttributes>
    {
        public string Id { get; set; }
        public CommandType Type { get; set; }
        public TAttributes Attributes { get; set; }
    }
    public class CallStartAttributes
    {
        public string Name { get; set; }
        public string Time { get; set; }
    }
    public class CallEndAttributes
    {
        public string Name { get; set; }
        public bool SendFeedback { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            BuildCommand();
            Console.ReadLine();
        }

        public static void BuildCommand()
        {
            CommandRequest requestBody1 = new CommandRequest() { Type = CommandType.CallStart, Attributes = new { Name = "TestStart", Time = "some time" } };
            CommandRequest requestBody2 = new CommandRequest() { Type = CommandType.CallEnd, Attributes = new { Name = "TestEnd", SendFeedback = true } };

            var command1 = new Command<CallStartAttributes>
            {
                Id = "1",
                Type = requestBody1.Type,
                Attributes = JsonConvert.DeserializeObject<CallStartAttributes>(JsonConvert.SerializeObject(requestBody1.Attributes))
            };
            var command2 = new Command<CallEndAttributes>
            {
                Id = "2",
                Type = requestBody2.Type,
                Attributes = JsonConvert.DeserializeObject<CallEndAttributes>(JsonConvert.SerializeObject(requestBody2.Attributes))
            };

        }
    }
}

A: you could use the Json.Net JObject attribute. check https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JObject.htm. Then get the particular values you're looking for.


text:
Q: why is this key step valid in the derivation of Ito's lemma? I am confused about the validity of a certain step (perhaps the most crucial one) in the derivation of Itô's lemma.
Here's my understanding so far: Itô's lemma deals with transforming a differential equation of a stochastic variable $X(t)$ into a differential equation for a function $F(X, t)$ of that variable. In particular, suppose the variable $X(t)$ satisfies the differential equation
$$
\frac{dX}{dt}=\mu(t)+\sigma(t)\frac{dW}{dt},
$$
where the function $W(t)$ has the property that, given that $W(\tau) = w$, then for any $\Delta > 0$, the value of $W(\tau + \Delta)$ is a random variable that follows the probability distribution
$$
p(x)=\frac{1}{\sqrt{2\pi\Delta}}\exp\left[-\frac{(x-w)^{2}}{2\Delta}\right].
$$
The derivation begins by expanding $F$ to second order in $X$ and first order in $t$:
$$
dF=\frac{\partial F}{\partial X}dX+\frac{1}{2}\frac{\partial^{2}F}{\partial X^{2}}dX^{2}+\frac{\partial F}{\partial t}dt.
$$
Now in order to obtain Itô's lemma, we evaluate $dX^2 = \sigma^2 dW^2 + \mathcal{O}(dtdW) + \mathcal{O}(dt^2)$. Now here is where I am confused: the next step is to take $dW^2 = dt$. The reason I am confused is that $dW^2$ is a random variable; so we cannot say for certain that it is $dt$. In particular, we have
$$
dW=W(t+dt)-W(t).
$$
Hence, the random variable $dW$, evaluated at time $t$ is normally-distributed with mean 0 and variance $dt$:
$$
p_{dW}(x)=\frac{1}{\sqrt{2\pi dt}}\exp\left[-\frac{x^{2}}{2dt}\right].
$$
Now we want the probability distribution of $dW^2$. We have
$$
p_{dW^{2}}(y)=2\left|\frac{d(x^{2})}{dx}\right|^{-1}p_{dW}(x)
$$
where the 2 comes from the fact that there is a positive and negative root. We then have
$$
p_{dW^{2}}(y)=\frac{1}{\sqrt{2\pi ydt}}\exp\left(-\frac{y}{2dt}\right).
$$
This distribution is indeed normalized when integrating from 0 to $\infty$. Now if we compute the first two moments of this distribution, we note that $y = dW^2$ has mean $dt$ and standard deviation $\sqrt{2}dt$. Hence, for infinitesimal $dt$, we are not at all certain that $dW^2 = dt$! I would like to understand why this substitution is legitimate.

A: I just realized one possible way to resolve it is to map $W(t)$ back to a discrete random walk, where for each time step $dt$, the walker has equal probability of going left or right by $dx$. The mean displacement in a single step is 0, but the squared displacement is $dx^2$ for certain, because there are only two outcomes: $-dx$ and $dx$.
Now extend to the continuum limit, the probability distribution is a Gaussian:
$$
p(x) \propto \exp\left(-\frac{x^2}{4Dt} \right),
$$
where $D$ is the continuum limit of the quantity $\frac{dx^2}{2dt}$, as seen in any derivation of the diffusion equation from a discrete random walk. For $W(t)$, we clearly have $D = 1/2$, so we must have $dx^2 = dt$. We concluded earlier in the discrete walk that the squared displacement in a single step is $dx^2$ for certain, so we have $dW^2 = dt$.

A: Heuristically maybe you can think $(dW_t)^2$ as a random variable with mean $dt$ and variance $2(dt)^2$, since $dt$ is infinitesimal, $(dt)^2$ vanishes, so $(dW_t)^2$ degenerates to $dt$.
That said, the reason that we say $(dW_t)^2=dt$ actually goes quite deep: consider a sequence $\{t_i\}_{i=0}^m$ such that $0=t_0<\dotsb<t_m=t$, and let $\Delta t_k=t_{k}-t_{k-1}$. Suppose $X_t$ is a continuous semi-martingale with local martingale part $M_t$, then for $f\in C^2$ we have the following change-of-variable formula (this is a more general version of Ito's formula): $$df(X_t)=f'(X_t)dX_t+\frac{1}{2}f''(X_t)d\langle M\rangle_t.$$ Here $\langle M\rangle_t$ is the quadratic variation of $M_t$, and it appears basically because for some approriately chosen $\eta$s, we have Taylor expansion $$f(X_t)-f(X_0)=\sum_{k=1}^mf'(X_{t_{k-1}})(X_{t_k}-X_{t_{k-1}})+\frac{1}{2}\sum_{k=1}^mf''(\eta_k)(X_{t_k}-X_{t_{k-1}})^2,$$ additionally, one can show that $$\sum_{k=1}^mf''(\eta_k)(X_{t_k}-X_{t_{k-1}})^2\to\int_0^t f''(X_{s})\,d\langle M\rangle_s\approx\sum_{k=1}^mf''(X_{t_{k-1}})(\langle M\rangle_{t_k}-\langle M\rangle_{t_{k-1}})$$ as $\Delta t_k\to 0$. In Ito's formula we replace $M_t$ by a Brownian motion $W_t$; thus $(dW_t)^2$ really is just a shorthand for $d\langle W\rangle_t$, and one can show that almost surely $\langle W\rangle_t=t$, hence the notation $(dW_t)^2=dt$.
In addition, it seems that questions similar to this have been asked several times elsewhere, e.g. you may take a look at this post. Also for reference I think Øksendal's Stochastic Differential Equations and Karatzas & Shreve's Brownian Motion and Stochastic Calculus can be quite helpful.


text:
Q: I have eclipse with pydev and i set the background to black and text white. now when i click on any word, is highlighted in a yellow color I have eclipse with pydev and i set the background to black and text white. now when i click on any word, is highlighted in a yellow color and i don't know how to change this yellow color to another. please help

A: Solved: Windows -> Preferences -> General -> Editors -> Text Editors -> Annotations -> Occurrences (Pydev) and change the color :D

A: Window -> Preferences -> Text Editors -> Appearance color options in the bottom and change the current highlight color


text:
Q: Docker container purely for frontend files My web-application consists of a vue frontend (purely client-side), a .NET backend and a postgres db. For hosting I'm using docker and docker-compose (my first time).
The setup consists of 4 containers.

*

*postgres db

*.net backend

*vue frontend (not running, just the built files)

*nginx instance

The nginx container serves as a reverse proxy for my backend and serves the static files for the frontend. I'm using only one container for both since I'm planning on hosting on a raspberry pi with limited resources and I also wanted to avoid coupling vue and nginx.
In order to achieve this, I'm mounting a named volume frontend-volume to read the frontend files from which previously is mounted to the static files built by the frontend image. I have copied (hopefully all) the relevant parts of the docker-compose file and the frontend dockerfile below. The full files are on GitHub:

*

*docker-compose.yml

*frontend/Dockerfile
Now my setup works fine initially but when I want to update some frontend-code, it just won't apply these changes in the container since the volume that contains the frontend files already exists and contains data (my assumption). I've tried docker-compose up --build and docker-compose up --build --force-recreate. Building manually with docker-compose build --no-cache frontend and then docker-compose up --force-recreate doesn't work either.
I had hoped these old files would just be overridden but apparently that's not the case. The only way I found to get the frontend to update correctly is to delete the volumes with docker-compose down -v and then running the up command again. Since I also have a volume for my database, this isn't a feasible solution unfortunately.
My goal was to have a setup that enables me to do a git pull on the raspi followed by a docker-compose up --build to update all the containers to the newest state while retaining the volumes containing the database-data. But that in itself might be wrong, I just want something comparable.
So my question: How can I create a file-only container for the frontend without having my files "frozen"?
Alternatively: what's the correct way of doing this (is it just wrong on every level)?
Dockerfile:
FROM node:14 as build-stage
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY ./ .

RUN npm run build

FROM alpine:latest as production-stage
COPY --from=build-stage /app/dist /app
VOLUME [ "/app" ]

docker-compose.yml:
version: '3'

services:
  nginx:
    container_name: nginx
    image: nginx:latest
    restart: always
    ports:
      - 5001:80
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
      - ./nginx/conf.d:/etc/nginx/conf.d:ro
      - frontend-volume:/app:ro
  frontend:
    container_name: frontend
    build:
      context: ./frontend
      dockerfile: Dockerfile
    volumes:
      - frontend-volume:/app
volumes:
  frontend-volume:

I also tried this dockerfile:
FROM node:14 as build-stage
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY ./ .

RUN npm run build

FROM alpine:latest as production-stage
VOLUME /app
# RUN rm -R /app/* uncommenting this doesn't work either, it fails with 'rm: can't remove '/app/*': No such file or directory'
COPY --from=build-stage /app/dist /app

A: A container, first and foremost, wraps a process; a "file-only container" doesn't really make sense as a concept.
Once you compile your Vue application, as far as the Nginx process is concerned, it's just a bunch of files to be served.  You can compile these into the Nginx image.  A multi-stage build would be a very common approach to this.  I wouldn't really consider this "coupling" different parts of the application together; you have one step that uses one set of tools to build the application, and a second step that serves it as static files.
# frontend/Dockerfile

# First stage: build the Vue app.  (Probably exactly what you have now.)
FROM node:14 as build-stage
WORKDIR /app
...
RUN npm run build

# Final stage: build an image that can serve the application.
# (Not just a bunch of files, an actual server.)
FROM nginx
COPY --from=build-stage /app/dist /usr/share/nginx/html
# (The base image provides a correct CMD already)

Then in your docker-compose.yml file, there isn't a separate container for the built files; they are already included in the image.
version: '3.8'
services:
  nginx:
    build: ./frontend
    restart: always
    ports:
      - 5001:80
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
      - ./nginx/conf.d:/etc/nginx/conf.d:ro
      # no volumes: for the code; it's built into the image
  # no separate frontend container

As a general rule, you shouldn't put your code or other outputs from your build process in volumes.  As you already note in the question, Docker will only copy content into a named volume the very first time a container runs, so using a volume here causes any updates to the application to be ignored (or to static files, or your node_modules directory, or ...).  This approach also doesn't work in other container environments like Kubernetes, where getting a volume that can be shared between containers is actually a little tricky, and where the container system won't automatically copy anything into a volume for you.

A: First and foremost you should know that containers should run a single master process, and if saving resources is on your mind, think about the fact that if you need to run two types of applications on the same container you'd have to create a special base image that would be hard to maintain feature and security wise, not to speak of using a more general container image that in the end might consume even more resources than two tailor made, small and concise images.
Regards not being tied to nginx with your frontend, the buety of using container means you don't have to install different pieces of software or versions of them directly on your machine and switching to node 16 from 14 for example is easy as changing your build stage base image, so I wouldn't worry about it especially cause you have many guides if you want to switch back from nginx and find a production dockerfile in a pinch.
My advice (cause I got a bit confused from your setup) is to build your frontend image with, first, your build stage as you've done and then in the 'production stage' copy the static files built in the 'build stage' to the appropriate nginx html folder (which is I think /usr/share/nginx/html ) copy the nginx.conf also to it's location and specify in the nginx configuration file to proxy requests with /api to the backend url.
On the other hand, if you currently want to debug fast with local mounted volumes, you could skip the 'build stage' and run the commands in it on your local machine then binding the created build files to nginx html folder (again /usr/share/nginx/html) as well as the nginx configuration file, both at run-time.
Running like this enables you to debug fast without messing around with stages and configuration and when your finished, using the better option with the full pipeline that will "freeze" the files.


text:
Q: Plaid: 'client_id must be a properly formatted, non-empty string' I am creating an application.
PLAID_CLIENT_ID = os.getenv('PLAID_CLIENT_ID')
PLAID_SECRET = os.getenv('PLAID_SECRET')

client = plaid.Client(client_id=PLAID_CLIENT_ID,
                      secret=PLAID_SECRET,
                      environment='development')

access_token = #Access Token

response = client.Accounts.balance.get(access_token)
accounts = response['accounts']

accountsTwo = accounts[0]['balances']['available']
#accountsThree = accountsTwo['balances']
#accountsFour = accountsThree['current']

jsonobj = json.dumps(accounts, indent = 4)

print(jsonobj)
print('-------------------------------------------------')
print(accountsTwo)

But I am getting an error saying
  File "c:\Users\callm\git\quickstart\python\find.py", line 26, in <module>
    response = client.Accounts.balance.get(access_token)
  File "C:\Python\Python39\lib\site-packages\plaid\api\accounts.py", line 22, in get
 line 68, in _http_request
    raise PlaidError.from_response(response_body)
plaid.errors.InvalidRequestError: client_id must be a properly formatted, non-empty string

It works fine in the debugger, but when I run it from my terminal it doesn't work. Let me know if you can figure it out please!


text:
Q: how to get binding value from ng-included file I'm new to angularjs and still teaching myself how it all works, so I'm assuming I'm missing something fundamental here.
Basically, I have a slider.html file that has:
{{priceSlider}}

<rzslider
    rz-slider-model="priceSlider"
    rz-slider-always-show-bar="true"
    rz-slider-translate="translate"
    rz-slider-on-change=""
    rz-slider-hide-limit-labels="true"
    rz-slider-floor="25"
    rz-slider-ceil="10000">
</rzslider>

Now the {{priceSlider}} returns the value just fine when the slider is moved on that page.
So on my main.html page I have:
{{priceSlider}}

I know the slider.html file is being pulled in just fine because I can see the content for that partial but my problem is that {{priceSlider}} is not updated on main.html like it is on slider.html. I am not sure what I am missing here.


text:
Q: Roku remote in javascript I am get errors in the web console for my roku remote control script. The javascript is as shown here:
  <script>
    function rokuSend(RokuAccess) {
      xhr = new XMLHttpRequest();
      xhr.onload=function() { alert(xhr.responseText); }
      xhr.open("POST", RokuAccess);
      xhr.send();
    }
    function rokuKeySend(keyVal) {
      rokuSend("http://" + document.getElementById('RokuIP').value + ":8060/keypress/" + keyVal);
    }

I supply the IP address for the Roku using:
<form id="Roku"><input type="text" id="RokuIP"></form>

When ever I press a key on my web based remote it send a command, to simplify things I will be using the SAME function to send key presses as well as other commands. So one of the functions called "rokuKeySend()" simply constructs the proper string that is needed to send a command issued by a key press. The second function "rokuSend()"sends the command to the Roku. Later additional commands will be sent to collect data from the Roku so I will create more functions that use "rokuSend()". For now I use the following buttons (these will later be replaced with images), for now they work fine as proof of concept:
<button type="button" onclick="rokuKeySend('Back')">Back</button>

<button type="button" onclick="rokuKeySend('Home')">Home</button>

<button type="button" onclick="rokuKeySend('Up')">Up</button>

<button type="button" onclick="rokuKeySend('Left')">Left</button>

<button type="button" onclick="rokuKeySend('Select')">Select</button></td>

<button type="button" onclick="rokuKeySend('Right')">Right</button>

<button type="button" onclick="rokuKeySend('Down')">Down</button>

<button type="button" onclick="rokuKeySend('InstantReplay')">InstantReplay</button>

<button type="button" onclick="rokuKeySend('Info')">Info</button>

<button type="button" onclick="rokuKeySend('Rev')">Rev</button>

<button type="button" onclick="rokuKeySend('Play')">Play</button>

<button type="button" onclick="rokuKeySend('Fwd')">Fwd</button>

<button type="button" onclick="rokuKeySend('Backspace')">Backspace</button>

<button type="button" onclick="rokuKeySend('Search')">Search</button>

<button type="button" onclick="rokuKeySend('Enter')">Enter</button>

After placing the IP into the input of the form, I can press ANY of the buttons and they do work. However they 'visually' depress when clicked by a mouse, but do not return from the depressed state. Upon checking the web console of the browser I found an error. This error is likely the reason I do not get return from the depressed state. How do I fix this? The error is listed below:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://xxx.xxx.xxx.xxx/keypress/KEY. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

In the above error 'xxx' represents the IP and 'key' represents the key that was pressed.

A: Its mentioned in the error, CORS Header is missing. Cross Object Resource Sharing(CORS) requires to add header "Access-Control-Allow-Origin" in the request. You can try to add this header in the request-
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');

If its not working, you have to create something proxy kind of solution. You can find more details here and here regarding CORS and fixing the error.


text:
Q: How can I move my camera sideways in ThreeJS I want to move my camera sideways using the arrow keys. For this I can use something like this to move forward:
const facingDir = this.camera.getWorldDirection(new THREE.Vector3())

this.camera.position.addScaledVector(facingDir, 1)

How do I calculate the vector to go sideways?

A: I got it working like this:
import * as THREE from 'three'

export default function calcOrthogonalVector(object: THREE.Object3D): THREE.Vector3 {
  // create default plane using normal vector
  const normalVector = new THREE.Vector3(0, 1, 0)
  const normalPlane = new THREE.Plane(normalVector, 0)

  // copy rotation of camera to plane
  normalPlane.normal.set(0, 1, 0).applyQuaternion(object.quaternion.clone())

  // get new normal vector
  const newNormalVector = normalPlane.normal

  // create new vector from cross product
  const crossVector = new THREE.Vector3()
  crossVector.crossVectors(newNormalVector, object.getWorldDirection(new THREE.Vector3()))

  return crossVector
}


text:
Q: Rails: How do I write a spec for a route that does a redirect? I am using Omniauth in my Rails project, and I'd like to hide "/auth/facebook" behind a "/login" route.
In fact, I wrote a route:
match "/login", :to => redirect("/auth/facebook"), :as => :login

and this actually works, i.e. a link to login_path will redirect to /auth/facebook.
However, how can I write a (RSpec) spec to test this route (specifically, the redirect)?
Do note that /login is not an actual action nor method defined in the application.
Thanks in advance!

A: Because you didn't provide any detail about your environment, the following example assumes you are using rspec 2.x and rspec-rails, with Rails 3.
# rspec/requests/redirects_spec.rb
describe "Redirects" do
  describe "GET login" do
    before(:each) do
      get "/login"
    end

    it "redirects to /auth/facebook" do
      response.code.should == "302"
      response.location.should == "/auth/facebook"
    end
  end
end

Read the Request Specs section of rspec-rails for more details.

A: You can also use:
get "/login"
response.should redirect_to(path)

A: You should use Rack::Test and check the url and the http status code
get "/login"
last_response.status.should == 302
last_response.headers["Location"].should == "/auth/facebook"


text:
Q: N-Tier questions In a typical N-Tier app, my understanding of the tiers is as follows:
DAL - code which interacts with db
BLL - business rules (how is this different to the DAL? Does it call the DAL? What's a sample BLL class?)
Presentation Layer
Also, where does a "service layer" come into all of this?

A: Well, let's start with DAL.
It lets you forget all the problems with DB when you write you BLL. That is: DAL takes care of insert, select, update, delete operations, takes care of transactions, executes stored procedures ets.
How do you use it in real life? Let's say tou have a table TBL1 in your DB. In DAL you create a class, named Tbl1Adapter. With dummy methods CreateRecord, GetRecord(id), UpdateRecord(id, newData), DeleteRecord(Id). Your BLL will call this methods. But Tbl1Adapter class will do DB job inside. It will call stored procedures or will send SQL commands to DB or will use some tricky DB drivers to fullfill your wishes from BLL :) Besides DAL does not mean only databases, it may be used to work with ASCII files, with input devices, with something else.
This layer provides data.
Next thing is BLL:
BLL is all about working your data. It gets data from DAL, and gives data to DAL to save it. But all the operations with data appear in BLL: numbers get multiplied, conditions (IF...THEN...) fullfiled, some other rocket science logic is executed... So BLL is core of your application.
This layer is a brain of your application.
Presentation layer:
This one is the easiest one to understand and very interesting to develop. It is all about how your application presents results of it's work. It may be a windows form with data grid and buttons, it may be a web page, it may be some cool audio interface.
This layer is a face of your application: eyes and ears to get data from user (or another system), and mouth to give data to user (or another system).
Well, service layer is a little bit tricky one.
Often it is an API of some other application. Let's say I have a web-service which can multiply to numbers. It's called MegaBrain :)
You have an application, which takes two numbers from user. But instead of implementing BLL in your application you decide TO USE SERVICE of my MegaBrain - give him those numbers and get back the result.
So service layer is... well, I don't know how to describe it in two words. Service layer let's your application use BLL of another application. It is similar to DAL, but data access layer only stores and gives data, while service layer performs some operations on input data and produces some result (gives you back result of multiplication or turns on a TV ;)


text:
Q: Не могу вызвать метод в класе php Есть такой кусок кода:
class tapinambur {
    protected $mysqli = false;
    protected $db_name = '';

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

    public function connectDB () {
        $this->mysqli = new mysqli('localhost', '***', '***', $this->db_name);
        $this->mysqli->query("SET NAMES 'utf8'");
    }

    public function closeDB () {
        $this->mysqli->close();
    }

    function getNews() {
        connectDB();

        $result = $this->mysqli->query("SELECT * FROM `news` ORDER BY `id` DESC");

        closeDB();

        return resultToArray($result);
    }

При обращении к getNews() пишет:

Call to undefined function connectDB()

Помогите пожалуйста, только начал изучать ООП на PHP.
Версия PHP: 7

A: В классе вызов вашей функции надо делать через $this  т.е $this->connectDB();
Тоже самое касается  метода closeDB().
Более подробно читайте ТУТ


text:
Q: Canot take password UItextfield in Iphone but it does in simulator I am developing an app on xcode swift4. it is a logon application to shibboleth. when i run application on simulator it work fine. however when i try on iphone6plus, the function that i am calling UI password field it dont take it.
it just skip it( meaning it dont take what i write inside password field) and pass it then step out the function. anyidea why ?
thanks
import UIKit
import SwiftECP
import XCGLogger
class ViewController: UIViewController {

@IBOutlet var UsernameField: UITextField!

@IBOutlet var passwordField: UITextField!

  var file = "file"

override func viewDidLoad() {
    super.viewDidLoad()
    if #available(iOS 10, *) {
        // Disables the password autoFill accessory view.
        UsernameField.textContentType = UITextContentType("")
        passwordField.textContentType = UITextContentType("")
    }
}

@IBAction func _Login(_ sender: Any) {
    gotourl()

    let DocumentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)

    let fileURL = DocumentDirURL.appendingPathComponent("file").appendingPathExtension("txt")
    var readString = ""
    do {
        // Read the file contents
        readString = try String(contentsOf: fileURL)
//            print ( "Reading from file \(readString)")
    } catch let error as NSError {
        print("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription)
    }

    let attributes = try! FileManager.default.attributesOfItem(atPath:fileURL.path)
    let fileSize = attributes[.size] as! NSNumber
 //        print ("Here is file \(fileSize)")

    if fileSize != 0{
        performSegue(withIdentifier: "gotowelcome", sender: self)

    }
    else
    {
        let alert = UIAlertController(title: "Login error", message: "Wrong Username or password.", preferredStyle: UIAlertControllerStyle.alert)

        // add an action (button)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.destructive, handler: { action in

            self.UsernameField.text=""
            self.passwordField.text=""

            }))

        // show the alert
        self.present(alert, animated: true, completion: nil)
        // Do any additional setup after loading the view.
        let text = ""
        do {
            try text.write(to: fileURL, atomically: false, encoding: .utf8)
            let fileSize2 = attributes[.size] as! NSNumber

        } catch {
            print(error)
        }
    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
func gotourl(){
    let username: String = UsernameField.text!
    let password: String = passwordField.text!
    let protectedURL = URL(
        string: "https://itsapps.odu.edu/auth/getInfo.php"
        )!
    let logger = XCGLogger()
    logger.setup(level: .debug)

    ECPLogin(
        protectedURL: protectedURL,
        username: username,
        password: password,
        logger: logger
        ).start { event in
            switch event {

            case let .value( body) :
                // If the request was successful, the protected resource will
                // be available in 'body'. Make sure to implement a mechanism to
                // detect authorization timeouts.

                print("Response body: \(body)")

                //this is the file. we will write to and read from it

                let text = "\(body)" //just a text

                let DocumentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)

                let fileURL = DocumentDirURL.appendingPathComponent("file").appendingPathExtension("txt")
                print("FilePath: \(fileURL.path)")

                do {
                    // Write to the file
                    try text.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
                } catch let error as NSError {
                    print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)
                }
                // The Shibboleth auth cookie is now stored in the sharedHTTPCookieStorage.
                // Attach this cookie to subsequent requests to protected resources.
                // You can access the cookie with the following code:
                if let cookies = HTTPCookieStorage.shared.cookies {
                    let shibCookie = cookies.filter { (cookie: HTTPCookie) in
                        cookie.name.range(of: "shibsession") != nil
                        }[0]
                    print(shibCookie)
                }

            case let .failed(error):
                // This is an AnyError that wraps the error thrown.
                // This can help diagnose problems with your SP, your IdP, or even this library :)

                switch error.cause {
                case let ecpError as ECPError:
                    // Error with ECP
                    // User-friendly error message
                    print(ecpError.userMessage)

                    // Technical/debug error message
                    print(ecpError.description)
                case let alamofireRACError as AlamofireRACError:
                    // Error with the networking layer
                    print(alamofireRACError.description)
                default:
                    print("Unknown error!")
                    print(error)

                }

            default:
                break

            }
    }

}

}
in this part where is error cause because of skiping the rest of the function
    @IBAction func _Login(_ sender: Any) {
    gotourl()

then it goes to
  func gotourl(){
    let username: String = UsernameField.text!
    let password: String = passwordField.text!
    let protectedURL = URL(
        string: "https://itsapps.odu.edu/auth/getInfo.php"
        )!

and skip password: String = passwordField.text!

A: Try to do it programmatically.
set txtfld.isSecureTextEntry = true
in viewDidLoad Method.


text:
Q: How can I configure a private (friends only) IRC Server? I am trying to setup an IRC server on my machine for a bunch of friends and me to use. This is an ubuntu box and I have installed dancer-ircd and dancer-services and gotten everything up and running according to the Ubuntu Docs. I would like to now lock down the server so that users need a "global" password to connect. Alternatively, every user can have their own username/password as long as I have the ability to pre-approve who is registering a nick on the server.

A: I had some IRC servers way back when. If I remember correctly, you set the connection password in the third field of the I: lines in ircd.conf.
The clients connect with something like /server yourserver.com:port password, and I believe most clients will ask for the password if you fail to provide one in the connect string.
There are a number of other options if you want to further restrict the connections.
I:address mask:password:domain mask::connection class

The connection class is defined with an Y: line. There's probably one in the default configuration that you can reference. Looking through the example ircd.conf is probably a good idea, most configuration options are explained there.

A: Have you considered running an IRC bot such as Eggdrop on a +i channel on a public network? This has the following benefits:

*

*Bot can be scripted to hand out invites to preconfigured people with preconfigured passwords.

*There is a myriad of Eggdrop TCL scripts out there, including logging.

*Running a single Eggdrop instance is a lot cheaper (in terms of computing resources) than a whole IRCd.

Obviously, there are disadvantages:

*

*Eggdrop scripts are written in TCL. This can be viewed as a benefit, depending on how good your TCL-fu is and what your opinion is of the language in general.

*You depend on the larger public network's infrastructure. While this is beneficial because all the good stuff has been done for you, events such as net splits or server revolts/expulsions can affect your private channel. This doesn't happen as often on larger, stable, and established networks such as Undernet or Freenode.

One more point to consider is that IRC is not a secure protocol. Some server software supports SSL connections, though I've never encountered such servers in practice. YMMV.
SILC is another alternative, although the PK cryptography minutia can be too much for some users.

A: There might be a way to limit connections only to certain IP addresses, but it seems like you're seriously overcomplicating yourself, as I've never seen a server that requires a password to connect.
You should just get a channel on a public network and password protect it, or better yet use some chat tool like Yahoo Messenger, which features conference mode, where you can invite more people into the same discussion.

A: I found this several years after the fact, but I'd like to add that the way I do this is to set up a IRCd to listen on localhost only, and set up ZNC.
ZNC has user accounts and uses either the server password or a USER that contains both.
I'm using this approach for TRC, example: https://irc.teamrelaychat.nl/ (use demo2/demo2)


text:
Q: POST запрос более 5 минут после переноса сайта НА тестовом домене и хостинге все работало отлично. Запрос проходил за пол секунды.
После переноса на домен и хостинг клиента запрос стал уходить очень долго. Максимальное время, которое я видел 7.5 минут.
Сделал скрин консоли и замер времени выполнения скрипта:

Код отправки формы скину если нужно, но он не менялся, поэтому думаю дело не в этом
Писать хостеру или все таки проблема на моей стороне? Заранее спасибо!


text:
Q: LinkedList Part I think I might have done something right, headByRating and headByName both refer to the same address.
I have been drawing diagras working all day trying new things etc, and i havent really made any progress.
I have two list pointers, headByRating and headByName.
and two node pointers nextByName and nextByRating.
Somehow I need to be able to sort this stuff by its name and rating.
I've been thinking that I do that by each of the ptrs' address'.
2 statements as an example that I have been trying to sort:

//main.cpp

list *wineries = new list();
wineries->insert(winery("Lopez Island Vinyard", "San Juan Islands", 7, 95));
wineries->insert(winery("Gallo", "Napa Valley", 200, 25));

the winery ctor is fine everything is allocated and into the object at this point:

//list.cpp
void list::insert( const winery& winery )
{
         list *listPtr  = new list(); // havent really used the list obj. yet.

    node *current = new node( winery ); // winery is now a node.
    node *temp    = current;     // temp knows about the nodes address.

    while ( temp->nextByName != NULL )
    {
                 // check for null and reassign
        temp = temp->nextByName;
    }
    node *new_node = new node( winery ); // creating a new node.
    new_node->item = winery;
    new_node->nextByName   = new_node;
    new_node->nextByRating = new_node;
}

// list.h
struct node
{
    winery  item;
    node *  nextByName;
    node *  nextByRating;
};

class list
{
    ...
private:
    node * headByName;
    node * headByRating;
};

What is a good approach to this? I dont think im doing this right.

A: Why are you rolling your own linked list? Why not use std::list?
If it's for the double-sorting thing, two separate lists of pointers would work, and be a hell of a lot easier if you can then use the provided container classes.
Or alternatively, if you need to sort it, is a linked list the best option? std::vector is often easier for sorting, or std::set maintains the order itself.

A: It looks like you have several problems here:

*

*It will always skip the while
statement since temp->nextByName
will always be NULL since temp
points to current which is a new
object.

*You're creating a node
object from winery twice

*You're
assigning the item member to winery
after you sent it in the constructor

*You're making the nextByName and
nextByRating members point to itself

I'd recommend removing everything from this method and writing high-level pseudo code in its place. Then create a smaller method for each line of pseudo code. Smaller logical methods called inside insert will help it make sense.

A: If you want to make your List type for experimentation, do it, otherwise use std::list.

If you want to keep your list sorted while you insert new elements then you have to implement an ordered list.

It's better to remove "winery field" dependencies from your List. A node should have only one next node, not many. You are making a List, not a Tree.
// list.h
struct node
{
    winery  item;
    node *  next;
};

class list
{
    ...
private:
    node * head;
};

You can't have one List ordered by different winery fields.
Make a new type, like CWinery, which will act as a container for your winery records.
In there, you can have a list to store your elements and methods to sort it or whatever you need.

A: If you are need to use list with several indexes you should consider using boost::multi_index instead of inventing the wheel.


text:
Q: JavaScript: Store first string in for loop in a value? var tds = document.getElementsByClassName('ms-cellstyle ms-vb2');
for (var i = 0; i < tds.length; i++) {
    if (tds[i].innerHTML.indexOf('Routed') >= 0 && i < tds.length - 1) {
        console.log(tds[i + 1].innerHTML);
    }
}

How would I store the first value?
this loop pulls a list of next siblings W1234567,A5364274,G8367483.
Need to store the first found in a value in this case is would be from the list "W1234567"

A: Retrieve the first occurrence? Is this what you mean?
If so, create a function and pass your parameters in. Return immediately when your condition is true.

function getFirst(className, criteria) {
  var tds = document.getElementsByClassName(className);
  for (var i = 0; i < tds.length; i++) {
    if (tds[i].innerHTML.indexOf(criteria) >= 0 && i < tds.length - 1) {
      return tds[i];
    }
  }
  return null;
}

// The target call to highlight.
var targetCell = null;

// The cell with "Routed" in it's text.
var matched = getFirst('ms-cellstyle ms-vb2', 'Routed');

if (matched != null) {
  // Fist sibling is the text of the matched cell, we need the one after that.
  targetCell = matched.nextSibling.nextSibling;
}

if (targetCell != null) {
  targetCell.className += ' found'; // Highlight cell
}
table, tr, td {
  border: thin solid #000;
  border-collapse: collapse;
}

.found {
  background: #FF0;
}

    Not in OMS
    A5364274

    Routed: Less Than 24 Hours
    W1234567

    Undefined
    G8367483

Side Note: You can adjust your for loop's condition to coincide with your inner if-condition.
for (var i = 0; i < tds.length - 1; i++) {


text:
Q: Android - API visible using charls proxy in release app - How to secure api details in release app? In my release app I am able to get the api details using charls. However in other apps charls shows unknown in case of api details.
How can I achieve the same? I need to secure the api.
AndroidManifest
<application
        android:allowBackup="true"
        android:icon="@drawable/app_icon"
        android:label="@string/app_name"
        android:networkSecurityConfig="@xml/network_config"
        android:roundIcon="@drawable/app_icon"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="false">

A: I just had to use https instead of http in the base url


text:
Q: What are the rules for expected values to the dotnet ef commands? In an ASP.NET Core application with migrations, running update database gives the following output. It works, and the verbose output displays the default values for a variety of options.
dotnet ef --verbose database update

Setting the data directory to 'C:\temp\bin\Debug\netcoreapp1.0\'.
Invoking dependency command 'Microsoft.EntityFrameworkCore.Design' in project '2016-101DP-TreeGame-Auth'
Running C:\Program Files\dotnet\dotnet.exe exec
  --runtimeconfig C:\temp\bin\Debug\netcoreapp1.0\temp.runtimeconfig.json
  --depsfile C:\temp\bin\Debug\netcoreapp1.0\temp.deps.json
  --additionalprobingpath C:\Users\me\.nuget\packages C:\Users\me\.nuget\packages\Microsoft.EntityFrameworkCore.Design\1.0.0-preview2-final\lib\netcoreapp1.0\Microsoft.EntityFrameworkCore.Design.dll
  --assembly C:\temp\bin\Debug\netcoreapp1.0\temp.dll
  --startup-assembly C:\temp\bin\Debug\netcoreapp1.0\temp.dll
  --dispatcher-version 1.0.0-preview2-21431
  --data-dir C:\temp\bin\Debug\netcoreapp1.0\
  --project-dir C:\temp
  --content-root-path C:\temp
  --root-namespace temp
  --verbose update database
Process ID: 12544
Finding DbContext classes...
Using context 'ApplicationDbContext'.
Done.

When I try to run the same command with options, the CLI complains that my options have "unexpected values." Here are two examples.
dotnet ef --data-dir C:\temp\bin\Debug\netcoreapp1.0\ --verbose database update

dotnet ef --data-dir "C:\temp\bin\Debug\netcoreapp1.0\" --verbose database update

Both tell me this:

Microsoft.Extensions.CommandLineUtils.CommandParsingException: Unexpected value 'C:\temp\bin\Debug\netcoreapp1.0\' for option 'data-dir'
at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
at Microsoft.EntityFrameworkCore.Tools.Cli.Program.Main(String[] args)

What are the rules for expected values to the dotnet ef commands?

A: There are two layers. dotnet-ef reads metadata from the project (and builds it) then calls ef using that metadata (including the output assembly paths). You cannot specify the following options from dotnet ef since they are determined for you.

*

*--assembly

*--startup-assembly

*--data-dir

*--project-dir

*--content-root-path

*--root-namespace
The rest of the options that show up in dotnet ef --help can be specified on dotnet ef.
This should get better as part of issue #6592.
Here is some documentation about dotnet ef.


text:
Q: Vertx: handling POST body is so slow I'm trying to implement an Http service for uploading files. Uploaded files are transferred via raw body of requests. Here's what I've implemented with vertx 3
public class MainVerticle extends AbstractVerticle {
    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();
        vertx.deployVerticle(new MainVerticle());
    }

    public static void log(String message) {
        System.out.printf("%s > %s\n", System.currentTimeMillis(), message);
    }

    @Override
    public void start(Future<Void> fut) {
        // Create a router object.
        Router router = Router.router(vertx);
        router.route().handler(BodyHandler.create());

        router.route("/api/v1.0/log/write")
                .handler(routingContext -> {
                    log("Processing... ");
                    JsonObject result = new JsonObject();
                    result.put("status", "ok");
                    routingContext.response()
                            .putHeader("content-type", "application/json")
                            .end(result.toString());
                });

        Handler<HttpServerRequest> handler = new Handler<HttpServerRequest>() {
            @Override
            public void handle(HttpServerRequest request) {
                request.handler(buffer -> log("Handling2...." + buffer.length()));
                request.endHandler(aVoid -> {
                    log("Done");
                    JsonObject result = new JsonObject();
                    result.put("status", "ok");
                    request.response()
                            .putHeader("content-type", "application/json")
                            .end(result.toString());
                });
            }
        };

        vertx
                .createHttpServer()
                .requestHandler(router::accept)
                .listen(9231, result -> {
                    if (result.succeeded()) {
                        fut.complete();
                    } else {
                        fut.fail(result.cause());
                    }
                });
    }
}

To validate the service, I ran the following script:
max=50
for i in `seq 2 $max`
do
    curl -H "Content-Type: application/json" \
        -X POST \
        --max-time 10 \
        --retry 5 \
        --retry-delay 0 \
        --retry-max-time 60 \
        --data-binary "@./512-kb.log" \
        http://localhost:9231/api/v1.0/log/write
    echo "\n"
done

To my surprise, the service performed so slow. Roughly about 1 request/s. Below is the runtime log:
text
Apr 08, 2018 7:41:06 PM io.vertx.core.Starter
INFO: Succeeded in deploying verticle
1523191273 > Processing...
1523191274 > Processing...
1523191275 > Processing...
1523191276 > Processing...
1523191277 > Processing...
1523191278 > Processing...

Would you please tell me how to implement it the right way? Thanks in advance.

A:
To my surprise, the service performed so slow. Roughly about 1 request/s. Below is the runtime log

Your runtime output doesn't seems to say that you have only one request per second but one per millis ;)
I've tried with the following code:
public class MainVerticle extends AbstractVerticle {
    public static void log(String message) {
        System.out.printf("%s > %s\n", Instant.ofEpochMilli(System.currentTimeMillis()), message);
    }

    @Override
    public void start(Future<Void> fut) {
        Router router = Router.router(vertx);
        router.route().handler(BodyHandler.create());

        router.route("/api/v1.0/log/write").handler(routingContext -> {
            log("Processing... ");
            JsonObject result = new JsonObject();
            result.put("status", "ok");
            routingContext.response().putHeader("content-type", "application/json").end(result.toString());
        });

        vertx.createHttpServer().requestHandler(router::accept).listen(9231, result -> {
            if (result.succeeded()) {
                fut.complete();
            } else {
                fut.fail(result.cause());
            }
        });
    }
}

And here's the result:
2018-04-09T06:39:49.154Z > Processing...
2018-04-09T06:39:49.192Z > Processing...
2018-04-09T06:39:49.203Z > Processing...
2018-04-09T06:39:49.213Z > Processing...
2018-04-09T06:39:49.224Z > Processing...
2018-04-09T06:39:49.235Z > Processing...
2018-04-09T06:39:49.246Z > Processing...
2018-04-09T06:39:49.257Z > Processing...
...

And I had the same result several times.
P.S :
1) Your Handler seems not to be used
2) I used the io.vertx.core.Launcher to run my verticle or the vertx executable command.


text:
Q: How to restore .wt backup file to local MongoDB? This is a question that was asked before, but I have tried all solutions, and simply cannot get it right. I have spent quite some time researching before posting this question. I have looked at the official MongoDB documents and many other blogs.
How to restore a .wt MongoDB backup file to a local MongoDB database?

A: Community wiki answer:
*.wt are binary data files used by the WiredTiger storage engine. Individual files are not usable as a standalone backup. If you want to take a file copy backup of a MongoDB dbPath you need to include all of the files using a Supported File Copy Backup Method.
If you have a valid file backup you can use it as the dbPath for another mongod instance. Aside from copying files, there is no restore special restore process for a file copy backup.
Can you clarify what files you have in your backup?

A: You can restore your .wt WiredTiger files downloaded from your Atlas Backup (which unzips or untar as a  restore folder) to your local MongoDB.
First, make a backup of your /data/db path. Call it /data_20200407/db. Second, copy paste all the .wt files from your Atlas Backup restore folder into your local /data/db path. Restart your Ubuntu or MongoDB server. Start your Mongo shell and you should have those restored files there.

A: There is a much simpler way,
But here are few things that need to consider, you can not create a backup from a single .wt file, you have to use the entire folder.
The easiest way is to start mongod with dbpath
mongod --dbpath <path-to-you-backup-folder-where-all-.wt-files-resides>

If your mongod service is already running, you will get some error or the above command will not work. So make sure to stop any existing mongod service if running, and then run the above command.
After that simply connect to your localhost mongo server, and this DB will be visible. Hopefully this will works!


text:
Q: Location icon is not showing on the google map

window.onload = function initmap() {
  var styles = [{
    "featureType": "water",
    "stylers": [{
      "color": "#2b2b2b"
    }]
  }, {
    "featureType": "landscape",
    "stylers": [{
      "visibility": "on"
    }, {
      "color": "#333333"
    }]
  }, {
    "featureType": "road.highway",
    "stylers": [{
      "visibility": "on"
    }, {
      "color": "#808080"
    }]
  }, {
    "featureType": "road.highway",
    "elementType": "labels.text.stroke",
    "stylers": [{
      "visibility": "off"
    }, {
      "color": "#808080"
    }]
  }, {
    "elementType": "labels.icon",
    "stylers": [{
      "color": "#5d5d5d"
    }, {
      "visibility": "off"
    }]
  }, {
    "elementType": "geometry.fill",
    "stylers": [{
      "color": "#5d5d5d"
    }, {
      "visibility": "off"
    }]
  }, {
    "featureType": "water",
    "elementType": "geometry.fill",
    "stylers": [{
      "color": "#808080"
    }, {
      "visibility": "on"
    }]
  }, {
    "featureType": "water",
    "elementType": "labels.text.fill",
    "stylers": [{
      "visibility": "off"
    }]
  }];
  var options = { // googel map with javascript
    mapTypeControlOptions: {
      mapTypeIds: ['Styled']
    },
    center: new google.maps.LatLng(41.786254, -85.428930),
    zoom: 16,
    disableDefaultUI: true,
    mapTypeId: 'Styled'
  };
  var div = document.getElementById('surabaya');
  var map = new google.maps.Map(div, options);
  var styledMapType = new google.maps.StyledMapType(styles, {
    name: 'Styled'
  });
  map.mapTypes.set('Styled', styledMapType);

  var map1 = new google.maps.Map(document.getElementById('map1'), {
    zoom: 4,
    center: {
      lat: 41,
      lng: -85
    }
  });
  var image = 'images/marker.png';
  var beachMarker = new google.maps.Marker({
    position: {
      lat: 41.786254,
      lng: -85.428930
    },
    map: map1,
    icon: image
  });
};
#surabaya {
  width: 100%;
  height: 400px;
}

I want to editing in the google map i have successfully changed the styling. Now i want to show the location marker of my choice . I am unable to set the icon of my choice and i am also not getting the default icon marker of the google map.i Have attached all my codes and i have also attached the google map api script and have entered my own API-KEY in the script.

A: Try This .. it should helps you sure ..
use your base_url() path for markerimage.
var image = new google.maps.MarkerImage("images/marker.png");
var beachMarker = new google.maps.Marker({
 position: {
   lat: 41.786254,
   lng: -85.428930
 },
 map: map1,
 icon: image
});


text:
Q: How can I restart model.fit after x epochs if loss remains high? I am having trouble sometimes getting a fit on my data, and when I restart fit (with shuffle=true) then I sometimes get a good fit.
See my previous question:
https://datascience.stackexchange.com/questions/62516/why-does-my-model-sometimes-not-learn-well-from-same-data
As a work around, I want to automatically restart the fitting process, if loss is high after x epochs. How can I achieve this?
I assume I would need to use a custom version of EarlyStopping callback? How could I differentiate between ES because of finding a low loss ( < 0.5) so training is finished, or because loss > 0.5 after x epochs so need to restart training?
Here is a simplified structure:
def train_till_good():
    while not_finished:
         train()

def train():
    load_data()
    model = VerySimpleNet2();

    checkpoint = keras.callbacks.ModelCheckpoint(filepath=images_root + dataset_name + '\\CheckPoint.hdf5')

    myOpt = keras.optimizers.Adam(lr=0.001,decay=0.01)

    model.compile(optimizer=myOpt, loss='categorical_crossentropy',  metrics=['accuracy'])

   LRS = CyclicLR(base_lr=0.000005, max_lr=0.0003, step_size=200.)

    tensorboard = keras.callbacks.TensorBoard(log_dir='C:\\Tensorflow', histogram_freq=0,write_graph=True, write_images=False)

    ES = keras.callbacks.EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=5)

    model.fit(train_images, train_labels, shuffle=True, epochs=num_epochs,
              callbacks=[checkpoint,
                         tensorboard,
                         ES,
                         LRS],
              validation_data = (test_images, test_labels)
              )

def VerySimpleNet2():
    model = keras.Sequential([
        keras.layers.Dense(112, activation=tf.nn.relu, input_shape=(224, 224, 3)),
        keras.layers.Dropout(0.4),
        keras.layers.Flatten(),
        keras.layers.Dense(3, activation=tf.nn.softmax)
    ])
    return model


text:
Q: Apply wildcard to a key of assoc. array I have read similar questions on this site, but still could not figure out how to apply it to my array. I have the following:
$var = array(
  [docs] = > array (
     [0] => array(
       [title_en] => some_title_en,
       [text_en] => some_text_en
      )
     [1] => array(
       [title_es] => some_title_es,
       [text_es] => some_text_es
      )
     [2] => array(
       [title_de] => some_title_de,
       [text_de] => some_text_de
      )
   )
 )

foreach ($var['docs'] as $array) {
   echo 'Title: '.$array['title_?'];
   echo 'Text: '.$array['text_?'];
}

Is there a way to output this array with wildcard for the keys: title and text, something like: $array['title_*'] and $array['text_*'] ?

A: Consider restructuring your array as mentioned by Mark Baker. It doesn't matter if you get the data from an external data source:
<?php

$array = array(
    'docs' => array(
        array(
            'title_en' => 'some_title_en',
            'text_en' => 'some_text_en',
        ),
        array(
            'title_es' => 'some_title_es',
            'text_es' => 'some_text_es',
        ),
        array(
            'title_de' => 'some_title_de',
            'text_de' => 'some_text_de',
        ),
    )
);

$newArray = array();

foreach ($array as $category => $texts) {
    $newArray[$category] = array();

    foreach ($texts as $textsLanguage) {
        foreach ($textsLanguage as $key => $value) {
            if (preg_match('/^(.*)_([a-z]{2})$/', $key, $match)) {
                if (!isset($newArray[$category][$match[2]])) {
                    $newArray[$category][$match[2]] = array();
                }

                $newArray[$category][$match[2]][$match[1]] = $value;
            }
        }
    }
}

print_r($newArray);

Outputs:
Array
(
    [docs] => Array
        (
            [en] => Array
                (
                    [title] => some_title_en
                    [text] => some_text_en
                )

            [es] => Array
                (
                    [title] => some_title_es
                    [text] => some_text_es
                )

            [de] => Array
                (
                    [title] => some_title_de
                    [text] => some_text_de
                )

        )

)

Now you can simply use
$lang = 'en';
var_dump( $newArray['docs'][$lang]['title'] ); //string(13) "some_title_en"

DEMO

A: Actually, I ended up using my own workaround:
foreach ($var['docs'] as $array) {
   foreach ($array as $key => $val) {
       if (substr($key,0,5) == 'title' || substr($key,0,4) == 'text') {
          $lang = explode('_', $key);
          $sufx = $lang[1];
       }
   }
   echo 'Title: '.$array['title_'.$sufx];
   echo 'Text: '.$array['text_'.$sufx];
}


text:
Q: Problem in reading text file with negative numbers Text File:
I have a text file containing more than 87,000 data points. The format of the text file is as follows:

*

*X Coordinate  ----- Y Coordinate ------- Parameter 1 ------ Parameter 2--------

*2.744596610E-02  1.247197202E+00  7.121462841E-03 2.467938066E-05

*2.732558411E-02  1.242196291E+00  1.365028508E-02 6.262368697E-05

*2.713870635E-02  1.227254209E+00  1.958976965E-03-3.179617352E-06
There is no space between the two numbers highlighted in bold because of the leading - (minus) sign, because of which the resulting csv/pandas dataframe results in something like below.
Output:
| X Coordinate    | Y Coordinate    | Parameter 1     | Parameter 2     |
| --------------  | --------------  | --------------- | ------------    |
| 2.744596610E-02 | 1.247197202E+00 | 7.121462841E-03 | 2.467938066E-05 |
| 2.732558411E-02 | 1.242196291E+00 | 1.365028508E-02 | 6.262368697E-05 |
| 2.713870635E-02 | 1.227254209E+00 | 1.958976965E-03-3.179617352E-06|  |

Required:
| X Coordinate    | Y Coordinate    | Parameter 1     | Parameter 2     |
| --------------  | --------------  | --------------- | ------------    |
| 2.744596610E-02 | 1.247197202E+00 | 7.121462841E-03 | 2.467938066E-05 |
| 2.732558411E-02 | 1.242196291E+00 | 1.365028508E-02 | 6.262368697E-05 |
| 2.713870635E-02 | 1.227254209E+00 | 1.958976965E-03 |-3.179617352E-06 |

I am comfortable with python/pandas, so any of the programming techniques would be of great help.

A: A regex can put spaces in there:
import re

with open("current.txt") as fh, open("new.txt", "w") as gh:
    # skip the first line
    fh.readline()

    # for other lines..
    for line in fh:
       gh.write(re.sub(r"(E[+-]\d+)(\S)(\d|\.)", r"\1 -\3", line))

Then
# you can include the header, I didn't paste
df = pd.read_csv("new.txt", sep=" ", header=None)

gives me
>>> df

          0         1         2         3
0  0.027446  1.247197  0.007121  0.000025
1  0.027326  1.242196 -0.013650  0.000063
2  0.027139 -1.227254  0.001959 -0.000003

A: import re

DATAPOINT = re.compile(r'-?\d{1}\.\d{9}E[+-]\d{2}')

data = []
with open("data.txt") as fp:
    next(fp) # Ignore header (1st line)
    for l in fp.readlines():
        data.append(DATAPOINT.findall(l))

df = pd.DataFrame(data, columns=['X Coordinate', 'Y Coordinate', 'Parameter 1', 'Parameter 2'])

>>> df
      X Coordinate     Y Coordinate      Parameter 1       Parameter 2
0  2.744596610E-02  1.247197202E+00  7.121462841E-03   2.467938066E-05
1  2.732558411E-02  1.242196291E+00  1.365028508E-02   6.262368697E-05
2  2.713870635E-02  1.227254209E+00  1.958976965E-03  -3.179617352E-06


text:
Q: why lines detected by opencv houghline are not parallel with real lines in image? higuys, at first please see below image:

why lines that detected and drawn by houghline are not really parallel with white lines of football pitch ??
i need that intersection point be on really places on image precisely
then it need to draw stright parallel line with white lines in image
who can helps me to solve this problem
thanks in advance
if you want to work with code ,this is original image d.jpg:

and this is my python code:
import numpy as np
import cv2
from collections import defaultdict
import sys
import math

img2 = cv2.imread("e:/d.jpg")
edges2 = cv2.Canny(img2, 40, 55)
def segment_by_angle_kmeans(lines, k=2, **kwargs):

 # Define criteria = (type, max_iter, epsilon)
 default_criteria_type = cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER
 criteria = kwargs.get('criteria', (default_criteria_type, 10, 1.0))
 flags = kwargs.get('flags', cv2.KMEANS_RANDOM_CENTERS)
 attempts = kwargs.get('attempts', 10)
 # Get angles in [0, pi] radians
 angles = np.array([line[0][1] for line in lines])
 # Multiply the angles by two and find coordinates of that angle on the Unit Circle
 pts = np.array([[np.cos(2*angle), np.sin(2*angle)] for angle in angles], dtype=np.float32)
 # Run k-means
 if sys.version_info[0] == 2:
    # python 2.x
    ret, labels, centers = cv2.kmeans(pts, k, criteria, attempts, flags)
 else:
    # python 3.x, syntax has changed.
    labels, centers = cv2.kmeans(pts, k, None, criteria, attempts, flags)[1:]

 labels = labels.reshape(-1) # Transpose to row vector

 # Segment lines based on their label of 0 or 1
 segmented = defaultdict(list)
 for i, line in zip(range(len(lines)), lines):
    segmented[labels[i]].append(line)

 segmented = list(segmented.values())
 print("Segmented lines into two groups: %d, %d" % (len(segmented[0]), len(segmented[1])))

 return segmented

def intersection(line1, line2):
 """
 Find the intersection of two lines
 specified in Hesse normal form.

 Returns closest integer pixel locations.

 """

 rho1, theta1 = line1[0]
 rho2, theta2 = line2[0]
 A = np.array([[np.cos(theta1), np.sin(theta1)],
              [np.cos(theta2), np.sin(theta2)]])
 b = np.array([[rho1], [rho2]])
 x0, y0 = np.linalg.solve(A, b)
 x0, y0 = int(np.round(x0)), int(np.round(y0))

 return [[x0, y0]]

def segmented_intersections(lines):
 """
 Find the intersection between groups of lines.
 """

 intersections = []
 for i, group in enumerate(lines[:-1]):
    for next_group in lines[i+1:]:
        for line1 in group:
            for line2 in next_group:
                intersections.append(intersection(line1, line2))

 return intersections

def drawLines(img, lines, color=(0,0,255)):
 """
 Draw lines on an image
 """
 for line in lines:
    for rho,theta in line:
        a = np.cos(theta)
        b = np.sin(theta)
        x0 = a*rho
        y0 = b*rho
        x1 = int(x0 + 1000*(-b))
        y1 = int(y0 + 1000*(a))
        x2 = int(x0 - 1000*(-b))
        y2 = int(y0 - 1000*(a))
        cv2.line(img, (x1,y1), (x2,y2), color, 2)

 # Detect lines
 rho = 2.7
 theta = np.pi/50
 thresh = 410
 lines = cv2.HoughLines(edges2, rho, theta, thresh)
 print("Found lines: %d" % (len(lines)))

 # Draw all Hough lines
 img_with_all_lines = np.copy(2)
 drawLines(img_with_all_lines, lines)

 # Cluster line angles into 2 groups (vertical and horizontal)
 segmented = segment_by_angle_kmeans(lines, 2)

 # Find the intersections of each vertical line with each horizontal line
 intersections = segmented_intersections(segmented)

 img_with_segmented_lines = np.copy(img2)

 # Draw vertical lines
 vertical_lines = segmented[1]
 img_with_vertical_lines = np.copy(img2)
 drawLines(img_with_segmented_lines, vertical_lines, (255,255,0))

 # Draw horizontal lines
 horizontal_lines = segmented[0]
 img_with_horizontal_lines = np.copy(img2)
 drawLines(img_with_segmented_lines, horizontal_lines, (0,255,255))

 # Draw intersection points

 intersections.pop(5)
 intersections.pop(4)

 mn = intersections[3]
 mk = intersections[2]
 intersections = intersections[:2]
 intersections.append(mn)
 intersections.append(mk)
 print(intersections)
 for point in intersections:
 pt = (point[0][0], point[0][1])
 length = 5

 cv2.circle(img_with_segmented_lines, pt, 5 , (255, 0, 255), -1)

 cv2.imshow("Segmented lines", img_with_segmented_lines)
 cv2.waitKey()

A: Hough uses accumulators with a finite resolution and this resolution determines the accuracy. You can reduce your theta (at the expense of running time, and possibly loss of reliability).
If I had to do it, I would probably add some post-processing to detect the lines  more precisely along the Hough lines, f.i. using a directional gradient filter and robust line fitting.


text:
Q: MySQL for update prevent lock joined tables I need to process a queue and MySQL for update is the goal for that.
Everything is working fine, except the fact for update is locking joined tables too.
I have 4 functions that are called simultaneously and 2 of them joins the same table.
The problem is that it seems it's locking all joined table and not specific joined rows.
My code is something like that (just example):
Query #1:
SELECT t1.id, t1.name, t2.balance FROM t1
LEFT JOIN t2 ON t2.user_id = t1.id

WHERE t2.balance < 0

LIMIT 10

FOR UPDATE
SKIP LOCKED

Query #2:
SELECT t3.id, t3.action, t2.balance FROM t3
LEFT JOIN t2 ON t2.user_id = t3.user_id

WHERE t2.balance < 0

LIMIT 10

FOR UPDATE
SKIP LOCKED

I didn't find anything related to this.
Is there a way to avoid that behavior?