text:
Q: Android M - SSLHandshakeException in SSLSocket connection I have a fairly simple client(Android)/server app to which I am trying to add SSL. Its working fine up to Android 4.4.4 but failing with SSLHandshakeException on Android M ( haven't tested on Lollipop), the server is telling me there are no cipher suites in common.
Here's the basic code (full source available here)..
Server.java
public class Server {
    public static final int PORT = 4646;
    TrustManagerFactory tmf;
    KeyManagerFactory kmf;
    KeyStore publicKeyStore;
    KeyStore privateKeyStore;
    SSLServerSocket serverSocket;

    public static void main(String args[]) {
        Server server = new Server();
        server.init();
    }

    private void init() {
        InputStream privateKeyStoreIns;
        InputStream publicKeyStoreIns;

        SecureRandom secureRandom = new SecureRandom();
        secureRandom.nextInt();

        privateKeyStoreIns = Server.class.getResourceAsStream("/server.private");
        publicKeyStoreIns = Server.class.getResourceAsStream("/client.public");

        Security.addProvider(new BouncyCastleProvider());

        try {
            privateKeyStore = setupKeystore(privateKeyStoreIns, "private");
            publicKeyStore = setupKeystore(publicKeyStoreIns, "public");

            tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(publicKeyStore);

            kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(privateKeyStore, "private".toCharArray());

            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(kmf.getKeyManagers(),
                    tmf.getTrustManagers(),
                    secureRandom);

            SSLServerSocketFactory sf = sslContext.getServerSocketFactory();
            serverSocket = (SSLServerSocket) sf.createServerSocket( PORT );
            serverSocket.setNeedClientAuth(true);

            Socket socket = serverSocket.accept();

            ObjectInputStream objInputStream = new ObjectInputStream(socket.getInputStream());
            while (objInputStream.readObject() != null) {
                // do nothing
            }

            objInputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private KeyStore setupKeystore(InputStream keyStoreInputStream, String passphrase)
            throws GeneralSecurityException, IOException {
        KeyStore keyStore = KeyStore.getInstance("BKS");
        keyStore.load(keyStoreInputStream, passphrase.toCharArray());

        return keyStore;
    }

}

MainActivity.java
public class MainActivity extends Activity {
    private static final String TAG = MainActivity.class.getName();
    public static final int PORT = 4646;
    public static final String HOST = "192.168.1.12"; //Change to IP address of server

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        connect();
    }

    private void connect() {
        new SocketConnector(this).execute();
    }

    static class SocketConnector extends AsyncTask<Void, Void, String> {
        Activity activity;
        TrustManagerFactory tmf;
        KeyManagerFactory kmf;
        KeyStore publicKeyStore;
        KeyStore privateKeyStore;
        SSLSocket socket;

        public SocketConnector(Activity activity) {
            this.activity = activity;
        }

        @Override
        protected String doInBackground(Void... params) {
            InputStream privateKeyStoreIns;
            InputStream publicKeyStoreIns;

            SecureRandom secureRandom = new SecureRandom();
            secureRandom.nextInt();

            privateKeyStoreIns = activity.getResources().openRawResource(R.raw.client_private);
            publicKeyStoreIns = activity.getResources().openRawResource(R.raw.server_public);

            try {
                privateKeyStore = setupKeystore(privateKeyStoreIns, "private");
                publicKeyStore = setupKeystore(publicKeyStoreIns, "public");

                tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                tmf.init(publicKeyStore);

                kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                kmf.init(privateKeyStore, "private".toCharArray());

                SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(kmf.getKeyManagers(),
                        tmf.getTrustManagers(),
                        secureRandom);

                SSLSocketFactory sf = sslContext.getSocketFactory();
                socket = (SSLSocket) sf.createSocket(HOST, PORT);
                socket.startHandshake();

            } catch (Exception e) {
                e.printStackTrace();
                return "Connection failure: " + e.getMessage();
            }

            return "Connection established!";
        }

        @Override
        protected void onPostExecute(String s) {
            TextView textView = (TextView) activity.findViewById(R.id.text_view);
            textView.setText(s);
        }

        private KeyStore setupKeystore(InputStream keyStoreInputStream, String passphrase)
                throws GeneralSecurityException, IOException {
            KeyStore keyStore = KeyStore.getInstance("BKS");
            keyStore.load(keyStoreInputStream, passphrase.toCharArray());

            return keyStore;
        }
    }
}

Exception stacktrace on Android
javax.net.ssl.SSLHandshakeException: Handshake failed
    at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:396)
    at com.sslsocketpoc.app.MainActivity$SocketConnector.doInBackground(MainActivity.java:71)
    at com.sslsocketpoc.app.MainActivity$SocketConnector.doInBackground(MainActivity.java:31)
    at android.os.AsyncTask$2.call(AsyncTask.java:295)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
    at java.lang.Thread.run(Thread.java:818)
Caused by: javax.net.ssl.SSLProtocolException: SSL handshake terminated: ssl=0x9e7a3140: Failure in SSL library, usually a protocol error
error:100c5410:SSL routines:ssl3_read_bytes:SSLV3_ALERT_HANDSHAKE_FAILURE (external/boringssl/src/ssl/s3_pkt.c:972 0xb4071d20:0x00000001)
error:100c009f:SSL routines:ssl3_get_server_hello:HANDSHAKE_FAILURE_ON_CLIENT_HELLO (external/boringssl/src/ssl/s3_clnt.c:750 0xab25d50f:0x0000
    at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
    at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:324)

Server side exception
javax.net.ssl.SSLHandshakeException: no cipher suites in common
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:292)
    at sun.security.ssl.ServerHandshaker.chooseCipherSuite(ServerHandshaker.java:1035)

A: Google has forked OpenSSL in API 23 (6.x) and now uses BoringSSL with no DSA support (but ECDSA), your public client key is a DSA 1024 KEY so you need check (and change) your keys to any supported algorithm.


text:
Q: How to attach multiple pdfs from directory (in server) to email attachments in PHP I made a form that can send form details to database then convert results to pdf (*pdfcrowd).
I have saved the filename(*of the pdf) inside the database and the pdf is saved inside a folder directory too.
Everything is working fine. EXCEPT that i'm stuck on how to get the pdf files.
The user is going to see the tables. I'll provide a checkbox and when the checkbox is clicked, the filename in the row should be included on what to attach in the email.
My database is Recipes, Table: Recipe_list, The field where filename is saved is.. "recipe_name" and the folder where the pdfs files are inside "/recipes/" folder.
I don't understand the "MIME" and other stuff about email attachment. I would appreciate if you can help me with this.

A: you can refer below link for this task,
http://www.emanueleferonato.com/2008/07/22/sending-email-with-multiple-attachments-with-php/
this would be very much helpful to you.
Thanks.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Uncaught TypeError: Cannot read property 'label' of null in laravel 5.4 Actually, I am using autocomplete in my input from where data comes from enrolCourse table if I see my route data return from database table my it does not show in my form show this error. I am uploading my form code and javascript code

{!! Form::open(array('url' => '/admin/enrollCourse/store')) !!}

                {!! Form::open(array('url' => '/admin/saveResult/create')) !!}

                        {{Form::label('Student Register','Search Student Register Number')}}
                        {!! Form::text('reg_id', null, array('id'=>'reg_id','placeholder' => 'Search Registration Number','class' => 'form-control')) !!}

                {!! Form::close()  !!}

                        {{Form::label('Student Registration','Student Registration Number')}}
                        {!! Form::text('reg_number', null, array('id'=>'reg_number','placeholder' => ' Registration Number','class' => 'form-control')) !!}

                        {{Form::label('Name','Student Name')}}
                        {!! Form::text('s_name', null, array('id'=>'s_name','placeholder' => 'Enter Student Name','class' => 'form-control')) !!}

                        {{Form::label('Email','Student Email')}}
                        {!! Form::email('email', null, array('id'=>'email','placeholder' => 'Enter Student Email','class' => 'form-control')) !!}

                        {{Form::label('Department','Department ')}}
                        {!! Form::text('department_id', null, array('id'=>'department_id','placeholder' => 'Enter Student Department','class' => 'form-control','onchange'=>"teacherQuery() ")) !!}

                        {{Form::label('Select Course','Select Course ')}}
                        {{csrf_field()}}
                        <select name="course_id" class="form-control" id="course_id">
                            <option value=" ">----Select Course-----</option>

                        </select>

                        {{Form::label('Select Grade','Select Grade ')}}
                        {{csrf_field()}}
                        <select name="grade_id" class="form-control" id="grade_id">
                            <option value=" ">----Select Course-----</option>
                            <option>A+</option>
                            <option>A</option>
                            <option>A-</option>
                            <option>B+</option>
                            <option>B</option>
                            <option>B-</option>
                            <option>C+</option>
                            <option>C</option>
                            <option>C-</option>
                            <option>D+</option>
                            <option>D</option>
                            <option>D-</option>
                        </select>

                        {{Form::submit('Enroll',['class'=>'btn btn-primary'])}}

    {!! Form::close() !!}

@endsection
@section('script')

@endsection

and Controller code here
public function  autocompleteResult(Request $request)
{
    $term = $request->term;
    $date = EnrollCourses::where('reg_num','LIKE','%' .$term. '%')->with('course')->take(10)->get();

    $result = array();
    foreach($date as $key=> $v)
    {
        $result = ['reg_num' =>$v->reg_num,'s_name'=>$v->s_name, 'email'=>$v->email,'department_id'=>$v->department_id, 'course_id'=>$v->course['name']];
    }
    return response()->json($result);
}

I need your help guys please suggest me, how can I solve this problem?


text:
Q: how to restrict on check multiple checkboxes in jquery.? I have tried Following code but not working so please suggest any other method using only jquery.

$("#Checkboxes4 :checkbox").change(function() {
   if($('#Checkboxes4').length > 1){
  $('#Checkboxes4').prop('checked',false);
  $(this).prop('checked',true);
 }
});
Spices

  <input type="checkbox" name="Checkboxes4[]" id="Checkboxes4" value="1+">1+ Kg
  <input type="checkbox" name="Checkboxes4[]" id="Checkboxes4" value="5+">5+ Kg
  <input type="checkbox" name="Checkboxes4[]" id="Checkboxes4" value="10+">10+ Kg

A: Perhaps radio buttons would serve you better?
Radio buttons are designed for the purpose of having only one radio button in a group checked at any one time, thus fulfilling "restrict on check multiple checkboxes".
This is a better solution than using checkboxes because you don't need to use any javascript nor Jquery to enforce this rule.
Example:
<form>
    <input type="radio" name="sex" value="male" checked>Male

    <input type="radio" name="sex" value="female">Female
</form>

Demo: http://www.w3schools.com/html/tryit.asp?filename=tryhtml_form_radio

A: Things to be noticed:

*

*In this case you should use radios with same name group instead.

*Never use same ids for multiple elements. Every element should have it's unique ID. When same ids happend to be on a page then only first element will get the event to be registered.

*When it comes to event binding then you can use class names instead because class names always returns a collection.

*In your case you can change the ID to class and you can use the snippet below.

$('.Checkboxes4').change(function() {
  $(this).closest('label').siblings('label').find(':checkbox').prop('disabled', this.checked);
});

Spices

    <input type="checkbox" name="Checkboxes4[]" class="Checkboxes4" value="1+">1+ Kg

    <input type="checkbox" name="Checkboxes4[]" class="Checkboxes4" value="5+">5+ Kg

    <input type="checkbox" name="Checkboxes4[]" class="Checkboxes4" value="10+">10+ Kg

I have changed the attribute id to class="Checkboxes4".

A: try this way:
$('#Checkboxes1').on('change', function() {
  if($(this).siblings(':checked').length > 1) {
   this.checked = false;
}
});

Also refer this: Disable checkboxes when 6 are checked -- multiple forms on page with checkbox groups

A: First one, you should not set all input with the same id. Replace id by class
And following code is the solution with checkboxes. Hope this help ^^

$(".a").change(function() {
    $('.a').prop("checked",false);
    $(this).prop("checked",true);
});

Spices

  <input type="checkbox" name="Checkboxes4[]" class ="a" value="1+">1+ Kg
  <input type="checkbox" name="Checkboxes4[]" class ="a" value="5+">5+ Kg
  <input type="checkbox" name="Checkboxes4[]" class ="a" value="10+">10+ Kg

A: In HTML multiple elements with same ID is not allowed..
You need to:

*

*Set the listener in the document/body ready event

*Change the ID to CLASS on the checkboxes

*Attach the event to checkbox with selected classes.

Here's the working code:
 $("body").ready(function(){
    $("input:checkbox.Checkboxes4").change(function() {
       if($('.Checkboxes4').length > 1){
            $('.Checkboxes4').prop('checked',false);
            $(this).prop('checked',true);
        }
    });

 });

Spices

  <input type="checkbox" name="Checkboxes4[]" class="Checkboxes4" value="1+">1+ Kg
  <input type="checkbox" name="Checkboxes4[]" class="Checkboxes4" value="5+">5+ Kg
  <input type="checkbox" name="Checkboxes4[]" class="Checkboxes4" value="10+">10+ Kg

JS Fiddle


text:
Q: Python sqlite3 library can't use URIs, even though sqlite3 version should be able to I have the most recent sqlite3 installed on my machine:
$ sqlite3 --version
3.26.0 2018-12-01 12:34:55 bf8c1b2b7a5960c282e543b9c293686dccff272512d08865f4600fb58238b4f9

And, in python, the sqlite3 module is using this version of sqlite3:
$ python
Python 3.4.9 (default, Jan  5 2019, 18:35:56)
[GCC 5.5.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite3 as sq
>>> sq.sqlite_version_info
(3, 26, 0)
>>> sq.version_info
(2, 6, 0)

However, I cannot open a database file using URIs, even though that feature has been present in sqlite since version 3.7:
>>> import sqlite3 as sq
>>> c = sq.connect('file://test', uri=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
sqlite3.NotSupportedError: URIs not supported

What is going on here?  What have I done wrong?

A: OK, I figured out what was going on by reading the source code.  When pyenv compiled my version of Python, the _sqlite module was compiled against the ridiculously old CentOS version of the "sqlite3.h" file.  Because of this, the Python module didn't have the SQLITE_OPEN_URI macro defined, which causes it give a hard-coded "URIs not supported" Python exception.
To get around this, I had to set the following environment variable:
# This is to direct pyenv to the linuxbrew include and library directories, when building versions of Python
export PYTHON_CONFIGURE_OPTS="LD_RUN_PATH=/home/linuxbrew/.linuxbrew/lib/ LDFLAGS=-L/home/linuxbrew/.linuxbrew/lib/ CPPFLAGS=-I/home/linuxbrew/.linuxbrew/include/"


text:
Q: $T(u)=2u$ for $u\in Im(T)$ implies $V=Im(T)\oplus Ker(T)$ Let $V$ be a finite dimensional space. Let $T:V\to V$ a linear operator. If  $T$ satisfies that
$$T(u)=2u \hspace{5mm} \text{for} \hspace{2mm} u\in Im(T)$$
does this implies that $V=Im(T)\oplus Ker(T)$?
In particular, I am having difficulties proving that if $v\in V$, then $v\in Im(T) +Ker(T)$.
I tried doing something similar than the case when $T$ is idempotent, that is, writing $v$ as $v=T(v)+(v-T(v))$ and seeing that the term $T(v)$ is in the image and the term $(v-T(v))$ is in the kernel, but I get an extra $-T(v)$ term. Any help will be appreciated.

A: If $T$ is the zero operator or if $T$ is invertible $\text{Im}(T)\oplus\text{Ker}(T) = V$ is immediate.
Otherwise let $r$ be the rank of $T$ and let $n$ be the dimension of $V$. Let $y_{r+1},\dots,y_n$ be a  basis of the kernel of $T$ and it can be extended to a basis of $V$ say $y_1,\dots,y_r,y_{r+1},\dots,y_n.$
It is sufficient to show $y_1,y_2,\dots,y_r$ span $\text{Im}(T).$
We show that $Ty_1,Ty_2,\dots,Ty_r$ forms a basis of $\text{Im}(T)$.
To see that note that any $x \in V$ is of the form $x = a_1 y_1 + \dots + a_n y_n.$
So, $T(x) = a_1 T(y_1) + a_r T(y_r)$, since $T(y_{r+1})=\dots=T(y_n)=0.$
So $T(y_1),\dots,T(y_r)$ span $\text{Im}(T)$.
Next note if $a_1T(y_1)+ \dots + a_rT(y_r) = T(a_1y_1+\dots+a_ry_r)=0$ then $a_1y_1+a_2y_2+\dots+a_ry_r \in \text{Ker}(T) \in \text{span}\{y_{r+1},\dots,y_n\}$, but by the construction of $y_1,\dots,y_r$ this is possible only if  $a_1y_1+a_2y_2+\dots+a_ry_r=0$ and independence leads us to: $a_1=\dots=a_r=0$.
So $T(y_1),T(y_2), \dots, T(y_r)$ froms a basis of $\text{Im}(T)$
or $2y_1,\dots,2y_n$, i.e., $y_1,y_2,\dots,y_r$ forms a basis of $\text{Im}(T).$


text:
Q: Use Windows security dialog in python project I'm working on a python program.
In this program, I need to get credentials from the user, and I store this credential in the Windows "Credential Manager".
Question is: Is it possible to use a native windows dialog to get credential from the user ? Like this dialog:
Image of Windows security login dialog
Maybe there is a Windows API that allow us to use that?
I know that I can create a custom dialog with, for example, tkinter but I want to use as much as possible the windows features.
Optional question:
I use the python lib nammed keyring to store credential in the credential manager.
All the credentials are stored in the Windows Crendentials -> Generic credentials section.
Do you know were a can found the file that store the generic credentials in my computer?
I found many topics with this question but no answer that suits me.
I have search on the Credential and the Vault folders located in local and roaming APPDATA.
Thanks,


text:
Q: How do I permanently remove all the sites in IE's Restricted Zone that SpyBot S&D added? On Windows XP I use a utility called "Spybot Search & Destroy" that helps protect my system from Spyware, while also providing great tools to inspect running processes, hidden startup applications, secure file shreding etc.
Its an awesome tool except for one major issue it has that brutally degrades performance in Internet Explorer 8.
In short, the 1,000's of sites that the tool adds to the IE "restricted zone" cause massive performance issues. Thus I need to remove them.
Steps taken thus far:

*

*I've turned off the "resident shield" & "Tea Timer" options

*Under Immunize I've unchecked every option

*Under settings I've turned off the "autorun" option to immunize on program start

*Full Windows reboot

Final cleanup (that won't work!):

*

*In IE > Tools > Internet Options > Security > Zones > Restricted > Sites... I can delete sites to my hearts content, but all will return on reload/reboot

*In the Registry under HKCU > Software > Microsoft > CurrentVersion > Internet Settings > ZoneMap, I've tried to delete all options in "Domains" and "EscDomains" (again, all return after a reboot)

What are the magic steps to rid myself of this list!
side rant question to the Spybot app developers - if IE's performance tanks with this setting turned on, why is there not an easy way to disable it!

A: I assume that the problem was caused by the Immunize feature.
From this Using Spybot article:

If you would like to undo the
  immunization, you can click on the
  Undo button, in the black box in
  Figure 13 above, to remove this
  protection.

If this doesn't work, my only other advice is to ask Spybot S&D for support.


text:
Q: How can I make my drop-down menu more mobile-friendly? I am using the the following HTML and CSS code for devices with a max-width of 480px.
How can I:

*

*Add the word "Menu" before the links?

*Display only "Menu"?

*Click on "Menu" to reveal links and then sub-links?

*Make "Menu", links and sublinks 100% of device width?

Please note, my knowledge of web design is limited to basic HTML and CSS. And this is my first go at designing a website.
Any help or advice would be greatly appreciated.

#menu {
    position: relative;
    top: 0;
    margin: 0;
    padding: 0;
    width: 100%;
    height: 3rem;
    font-size: 0.8rem;
    z-index: 999;
}

#menu ul {
    position: absolute;
    margin: 0;
    padding: 0;
    height: 100%;
    width: 100%;
 list-style-type: none;
 background-color: #0000ff;
 color: #ffffff;
}

#menu ul > li {
 display: block;
 float: left;
 height: auto;
 width: 20%;
 overflow: hidden;
}

#menu li > a {
 display: block;
 height: 100%;
 width: 100%;
 line-height: 3rem;
 text-align: center;
 text-decoration: none;
 background-color: #0000ff;
 color: #ffffff;
}

#menu li > span {
 display: block;
 height: 100%;
 width: 100%;
 line-height: 3rem;
 text-align: center;
 text-decoration: none;
 background-color: #0000ff;
 color: #ffffff;
}

#menu ul ul {
 display: none;
 position: static;
 height: auto;
 width: 100%;
 margin: 0;
}

#menu ul ul li {
 position: relative;
 float: none;
 display: block;
 height: 100%;
 width: 100%;
}

#menu ul ul li > a {
 height: 100%;
 width: 100%;
 text-align: center;
}

#menu li:hover > a {
 color: #0000ff;
 background-color: #ffffff;
}

#menu li:hover > span {
 color: #0000ff;
 background-color: #ffffff;
}

#menu li:hover > ul {
 display: block;
}

HOME

ABOUT

History

Champions

Presidents

Committee

Rules

BOOK

Functions

Suite

Lounge

Bar

COMPS

Fixtures

Gents

Ladies

Winners

CONTACT

Details

Join

Map

A: Please check following example

/********** Start RESET **********
 AUTHOR: Osvaldas Valutis, www.osvaldas.info
*/
* {
 -webkit-box-sizing: border-box;
 -moz-box-sizing: border-box;
 box-sizing: border-box;
 *behavior: url( '/theme/js/boxsizing.htc' );
 -webkit-tap-highlight-color: rgba( 0, 0, 0, 0 );
 -webkit-overflow-scrolling: touch;
}
html, body, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sup, sub, tt, var, b, u, i, center, ul, ol, li, dl, dt, dd, table, tr, th, td, thead, tbody, tfoot, caption, form, fieldset, legend, input, textarea, select, label, applet, object, iframe, audio, video, canvas, article, aside, canvas, details, figcaption, figure, footer, header, hgroup, menu, nav, section, summary {
 font-size: 100%;
 font-family: inherit;
 font-weight: inherit;
 font-style: inherit;
 line-height: inherit;
 vertical-align: baseline;
 border: 0;
 outline: 0;
 padding: 0;
 margin: 0;
}
html {
 font-size: 100%;
 -webkit-text-size-adjust: 100%;
 -moz-text-size-adjust: 100%;
 -ms-text-size-adjust: 100%;
 -o-text-size-adjust: 100%;
 text-size-adjust: 100%;
}
body {
 font-family: Helvetica, Arial, sans-serif;
 line-height: 1;
 color: #000;
 background-color: #fff;
}
article, aside, canvas, details, figcaption, figure, footer, header, hgroup, menu, nav, section, summary {
 display: block;
}
audio, canvas, video {
 display: inline-block;
*display: inline;
*zoom: 1;
}
audio:not([controls]) {
 display: none;
}
canvas {
 -ms-touch-action: double-tap-zoom;
}
 [hidden] {
display: none;
}
a {
 text-decoration: underline;
 color: #000;
}
a:hover {
 text-decoration: none;
}
small {
 font-size: 75%;
}
big {
 font-size: 125%;
}
em {
 font-style: italic;
}
strong {
 font-weight: bold;
}
ins {
 text-decoration: none;
}
del {
 text-decoration: line-through;
}
sup, sub {
 font-size: 75%;
 line-height: 0;
}
sup {
 vertical-align: super;
}
sub {
 vertical-align: sub;
}
pre {
 display: block;
 overflow: auto;
}
code {
 font-family: 'Courier New', Courier, monospace;
}
ul, ol {
 list-style: none;
}
table {
 table-layout: auto;
 border-collapse: separate;
 border-spacing: 0;
 empty-cells: hide;
}
img {
 vertical-align: middle;
 -ms-interpolation-mode: bicubic;
}
svg:not(:root) {
 overflow: hidden;
}
blockquote, q {
 quotes: none;
}
blockquote:before, blockquote:after, q:before, q:after {
 content: '';
 content: none;
}
input, textarea {
 -webkit-appearance: none;
}
button, input, select, textarea {
 vertical-align: baseline;
*vertical-align: middle;
 -webkit-border-radius: 0;
}
button, input {
 line-height: normal;
*overflow: visible;
}
table button, table input {
*overflow: auto;
}
button, input[type='button'], input[type='reset'], input[type='submit'] {
 cursor: pointer;
 -webkit-appearance: button;
}
textarea {
 overflow: auto;
 vertical-align: top;
}
input[type='search']::-webkit-search-decoration, input[type='search']::-webkit-search-cancel-button, input[type='search']::-webkit-search-results-button, input[type='search']::-webkit-search-results-decoration {
display: none;
}
input[type='search'] {
 -webkit-appearance: textfield;
}
input[type='radio'] {
 -webkit-appearance: radio;
}
input[type='checkbox'] {
 -webkit-appearance: checkbox;
}
input::-ms-clear {
display: none;
}
input[type='password']::-ms-reveal {
display: none;
}
.clearfix:after {
 visibility: hidden;
 display: block;
 font-size: 0;
 content: " ";
 clear: both;
 height: 0;
}
* html .clearfix {
 zoom: 1;
}
*:first-child+html .clearfix {
 zoom: 1;
}
.cleaner {
 height: 0;
 line-height: 0;
 clear: both;
}

/********** End RESET **********/

html {
 font-size: 100%;
}
body {
 font-family: 'Noticia Text', serif;
 font-weight: 400;
 -webkit-font-smoothing: antialiased;
 background-color: #f7efeb;
 padding: 1.25em; /* 20 */
}
body, a, a:hover {
 color: #111;
}
a {
 -webkit-transition: color .3s ease;
 -moz-transition: color .3s ease;
 -ms-transition: color .3s ease;
 -o-transition: color .3s ease;
 transition: color .3s ease;
}
a, a:hover {
 text-decoration: none;
}
#nav {
 width: 60em; /* 1000 */
 font-family: 'Open Sans', sans-serif;
 font-weight: 400;
 position: absolute;
 top: 25%;
 left: 50%;
 margin-left: -30em; /* 30 480 */
}
#nav > a {
 display: none;
}
#nav li {
 position: relative;
}
#nav li a {
 color: #fff;
 display: block;
}
#nav li a:active {
 background-color: #c00 !important;
}
#nav span:after {
 width: 0;
 height: 0;
 border: 0.313em solid transparent; /* 5 */
 border-bottom: none;
 border-top-color: #efa585;
 content: '';
 vertical-align: middle;
 display: inline-block;
 position: relative;
 right: -0.313em; /* 5 */
}
/* first level */

   #nav > ul {
 height: 3.75em; /* 60 */
 background-color: #e15a1f;
}
#nav > ul > li {
 width: 25%;
 height: 100%;
 float: left;
}
#nav > ul > li > a {
 height: 100%;
 font-size: 1.5em; /* 24 */
 line-height: 2.5em; /* 60 (24) */
 text-align: center;
}
#nav > ul > li:not( :last-child ) > a {
 border-right: 1px solid #cc470d;
}
#nav > ul > li:hover > a, #nav > ul:not( :hover ) > li.active > a {
 background-color: #cc470d;
}
/* second level */

    #nav li ul {
 background-color: #cc470d;
 display: none;
 position: absolute;
 top: 100%;
}
#nav li:hover ul {
 display: block;
 left: 0;
 right: 0;
}
#nav li:not( :first-child ):hover ul {
 left: -1px;
}
#nav li ul a {
 font-size: 1.25em; /* 20 */
 border-top: 1px solid #e15a1f;
 padding: 0.75em; /* 15 (20) */
}
#nav li ul li a:hover, #nav li ul:not( :hover ) li.active a {
 background-color: #e15a1f;
}
 @media only screen and ( max-width: 62.5em ) /* 1000 */ {
#nav {
 width: 100%;
 position: static;
 margin: 0;
}
}
 @media only screen and ( max-width: 40em ) /* 640 */ {
html {
 font-size: 75%; /* 12 */
}
#nav {
 position: relative;
 top: auto;
 left: auto;
}
#nav > a {
 width: 3.125em; /* 50 */
 height: 3.125em; /* 50 */
 text-align: left;
 text-indent: -9999px;
 background-color: #e15a1f;
 position: relative;
}
#nav > a:before, #nav > a:after {
 position: absolute;
 border: 2px solid #fff;
 top: 35%;
 left: 25%;
 right: 25%;
 content: '';
}
#nav > a:after {
 top: 60%;
}
#nav:not( :target ) > a:first-of-type, #nav:target > a:last-of-type {
 display: block;
}
/* first level */

   #nav > ul {
 height: auto;
 display: none;
 position: absolute;
 left: 0;
 right: 0;
}
#nav:target > ul {
 display: block;
}
#nav > ul > li {
 width: 100%;
 float: none;
}
#nav > ul > li > a {
 height: auto;
 text-align: left;
 padding: 0 0.833em; /* 20 (24) */
}
#nav > ul > li:not( :last-child ) > a {
 border-right: none;
 border-bottom: 1px solid #cc470d;
}
/* second level */

    #nav li ul {
 position: static;
 padding: 1.25em; /* 20 */
 padding-top: 0;
}
}
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1" />

 Show navigation Hide navigation

Home

 Blog

Design

HTML

CSS

JavaScript

 Work

Web Design

Typography

Front-End

About


text:
Q: Simplify $e^{\frac {(-\ln 2)}{2}}$ Simplify $\displaystyle e^{\large \frac {(-\ln2)}{2}}$
I know that $(-\ln 2)$ is $\ln\left(\frac{1}{2}\right)$ and the rule $e^{\ln x}=x$. How do I simplify with the fraction at the bottom?

A: The answer is just: $$\frac{1}{\sqrt{2}}.$$ This is because: $$\exp(-\ln(2))=\exp(\ln(1/2))=1/2.$$

A: $$ \exp(\frac{- \ln 2}{2} ) = \exp( \ln2^{-{1/2}}) = 2^{-1/2} = \frac{1}{\sqrt{2}}$$


text:
Q: Is it possible to null the value of a variable inside a method depending upon the Activity which calls it? I have a method which is called from 5 different activities.Suppose this method displays result by adding 4 different variables
Eg result=a+b+c+d;
Now if i want to stop the functionality of a certain variable depending on the activity which calls it.
for Eg
if Activity 1 calls the method then result should be a+b+d(c got null);
or if Activity 4 calls the method then result should be a+c+d(b got null);
Given a,b,c,d contains integer values.
Please help

A:
First of all integer doesn't have null value its initial value is 0.

Here is an simple example:
public void method(int a_val, int b_val, int c_val, int d_val){
  if(ACTIVITY == 1){ // condition for activity
     c_val = 0;
  }else if (ACTIVITY == 2){
     ...
  }
  ...
  result = a+ b + c + d;
}


text:
Q: How can I amend my Payload to send multiple objects in one call (Endpoint: D365FO)? I've currently got a JSON Payload designed for an OData API as follows:
{
"testData":"testData"
}
Wherein the above payload consists of one object that will be inserted into a D365 data entity. However, right now I need to do a form of testing in which I have to send multiple objects in one call, AKA my call should look something like this:
{"testData": "testData1"},
{"testData": "testData2"},
{"testData": "testData3"},
{"testData": "testData4"}

To do such testing, I need to find a way to modify my payload within PostMan; how could I do so?
Thanks!


text:
Q: Correlation or difference? appropriate test for variables with different units? In a comparative study on human motion and perception in both reality and virtual reality, I am examining differences and relations between specific entities.
In two separate experiments, TTG Estimation* and Distance Estimation* data were collected from the same set of test persons who had following tasks:

*

**TTG Estimation task: Estimation for a Time-To-Go in [seconds] - test subjects are asked to signal the point of time (in Reality and Virtual Reality) at which they feel there's just not enough time for securely crossing
the street until the arrival of a vehicle (at 3 different
speeds).

**Distance Estimation task: Test subjects are asked to estimate the distance in [m] between them and a pylon (in Reality and
Virtual Reality)

Following table shall give a visualisation of the experiment design with the corresponding variables to be examined:
+-----------------+-----------------------------+---------------------------------+
|                 | TTG Estimation Experiment   | Distance Estimation Experiment  |
+                 +-----------------------------+---------------------------------+
|                 | 30 km/h | 35 km/h | 40 km/h | 8m | 9m | 10m | 11m | 12m | 13m |
+-----------------+---------+---------+---------+----+----+-----+-----+-----+-----+
| Reality         |         |         |         |    |    |     |     |     |     |
+-----------------+---------+---------+---------+----+----+-----+-----+-----+-----+
| Virtual Reality |         |         |         |    |    |     |     |     |     |
+-----------------+---------+---------+---------+----+----+-----+-----+-----+-----+
| Test Variables  |     abs(TTG_R - TTG_VR)     |      abs(Dist_R - Dist_VR)      |
+-----------------+-----------------------------+---------------------------------+

So in general I'm interested in the answer to the following question:
Is there a relation between the estimation ability/quality for TTG and the estimation ability/quality for Distance? Or in other words ...
Do test persons with a good estimation for the TTG also give a good estimation for the Distance?
So my questions are:
a) What hypothesis approach is more appropriate? A comparison between two test variables OR a correlation analysis?
I am confused by the fact that the test variables |TTG_R - TTG_VR| and |Dist_R - Dist_VR| have different levels (TTG: 3 different vehicle speeds; Distance: 6 different distances) and that the test variables are measured in different units (TTG: s; Distance: m).
b) What exact method/test can I use to adress my point of interest? Does difference hypothesis make sense? (e.g. ANOVA for multiple factors?)
I have thought of normalising the test variables via zscore and check for bivariate correlation but then immediately I realise there are different test levels for each variable TTG: 3 different vehicle speeds; Distance: 6 different distances).
And regarding a difference hypothesis I am not sure if test levels can be used as factors?
Available software for evaluation:

*

*Matlab

*SPSS

A: So, the STAT 101 approach this problem would be a Pearson's r correlation test between error-in-distance and error-in-time. And as long as you have at least a few tens of subjects and the errors in each variable look more-or-less bell-shaped, this is probably still the first thing I would do with this problem.
Something like a paired t-test would definitely be wrong. Since the two measurements have different units, there is no way that the same-variance assumption could be satisfied. In practice this would show up as your result being unit-dependent.
ANOVAs are about comparing treatments where the independent variable levels are non-orderable and discrete and the dependent variable levels are orderable and continuous. So an ANOVA treatment is going to treat your distance and time errors in a fundamentally different way, even though they are fundamentally comparable. Also, since ANOVAs don't know anything about the ordering of the independent variable, they are not going to be as powerful.
Really, you have screwed yourself a bit by ordinal-zing variables that are fundamentally continuous, that is by binning your measurements. Making that choice is what led you consider not-really-appropriate ANOVAs, and technically it rules out continuous-variable tests like the r-test I suggested. But as long as the discrete-ness isn't too bad, it's pretty common practice to use continuous variable techniques on ordinal variables. I don't suppose you can go back to the original data and un-bin?
More complex stuff like latent factor analysis (which is not the same thing as "factor analysis" in SPSS) is basically fitting a parametric model, which can take into account other things you know about your estimators (sex, age, etc.) It's a fine next step, but there is nothing wrong with answering your first question with a simple correlation test.

A: I don't think that linear methods or measures applied to the observed variables at the raw scale will be useful, since time, distance and speed are all positive quantities and a basic result from newtonian mechanics tells us that their relationship is multiplicative, not additive. In particular, we know that
$$t=\frac{d}{v}$$
With the help of this equation we can translate the time judgments in TTG experiment to distance. In particular, $d_\mathrm{ttg}^\mathrm{estim}=t_\mathrm{ttg}^\mathrm{estim} \cdot v_\mathrm{ttg}^\mathrm{estim}$ where $v_\mathrm{ttg}^\mathrm{estim}$ is a speed estimate and is not observed. The true distance $d_\mathrm{ttg}^\mathrm{true}$ is the distance of the vehicle to the crossing at the time when the TTG jugment is made which I assume is known. In this way we obtain distance measures in the TTG experiment analogous to the Distance estimation experiment. $v_\mathrm{ttg}^\mathrm{estim}$ is not known. Perhaps one could assume that observers are accurate in their estimate $v_\mathrm{ttg}^\mathrm{estim}=v_\mathrm{ttg}^\mathrm{true}$. Otherwise one would treat $v_\mathrm{ttg}^\mathrm{estim}$ as unknown parameter.
At this point one may utilize any of the models that are suitable for strictly positive variables. A simple approach would be to assume $v_\mathrm{ttg}^\mathrm{estim}=v_\mathrm{ttg}^\mathrm{true}$, to compute $d_\mathrm{ttg}^\mathrm{estim}$, to log-transform the distances $d_\mathrm{ttg}^\mathrm{estim}$, $d_\mathrm{ttg}^\mathrm{true}$,$d_\mathrm{de}^\mathrm{estim}$, $d_\mathrm{de}^\mathrm{true}$  and to analyze the transformed values with the familiar linear methods (pearson correlation, additive contrasts, linear regression, ANOVA, etc.).
While I wrote that the the time model is not additive, in TTG experiment there are actually plausible reasons to use a model with an additive shift parameter. Namely, the observers probably consider
$$t_\mathrm{ttg}^\mathrm{estim}=t_\mathrm{walk}^\mathrm{estim}+\frac{d_\mathrm{car}^\mathrm{estim}}{v_\mathrm{car}^\mathrm{estim}}$$
That is, the time is the sum of the time until the vehicle arrives plus the time to cross the street. Unless the time to cross the street is negligable, $t_\mathrm{walk}^\mathrm{estim}$ should be included as a shift parameter in the model of the time estimates from the TTG experiment.


text:
Q: Creating a dynamic UI in winforms If I want to create a winform with dynamic UI controls appearing, what's the best way to do that?
I have a form with a textbox, a button1 to the right of it, a listbox underneath, and a button2 underneath the listbox.  Pressing button1 should generate another textbox underneath the first textbox and the listbox/button2 should be shifted down.  If anyone's used Adobe Bridge before, the batch rename window is an example of what I'm talking about.
I was thinking of simply adding textboxN.Height to this.Size, then textboxN.Height to each of the controls (except the first textbox) Y position so they all get shifted down by textboxN.Height pixels.  But I think there's a better way of doing this.  Rather, is Winforms suitable for something like this?

A: You -could- just add the height of the TextBox to the form's size, but tbh it would be better to use a constant that dictates the size of the TextBoxes, and then add that.
For moving the listBox/button2, anchor them to the bottom of the form, and they'll automatically stay at the same distance from the bottom of the form.
As for dynamic generation, use a List (or a Stack, depending on what exactly you're doing with it).
partial class Form1 : Form
{
    List<TextBox> textBoxes = new List<TextBox>(); // or stack
    const int textBoxWidth = 200;  // control variables for TextBox placement
    const int textBoxHeight = 50;
    const int textBoxMargin = 5;

    void button1_Click(object sender, EventArgs e)
    {
        this.Height += textBoxHeight + textBoxMargin;
        TextBox tb = new TextBox();

        if (textBoxes.Count == 0)
        {
            tb.Top = textBoxMargin;
        }
        else
        {
            tb.Top = ((textBoxHeight + textBoxMargin) * textBoxes.Count) + textBoxMargin;
        }

        tb.Left = textBoxMargin;
        tb.Height = textBoxHeight;
        tb.Width = textBoxWidth;
        textBoxes.Add(tb);
        this.Controls.Add(tb);
    }
}

That should work. The thing with the method here is pretty much all of the placement customisation can be done with the constant values.
Is it best to do it in WinForms? Well, there's certainly no real reason to not do it in WinForms, this functionality is easy enough to implement. I'm a WPF guy myself but this is still legit.
Edited for logic errors


text:
Q: How to show on-click the same pop-up for elements created dynamically? I'm trying to make a little project, Note using localStorage. I want for every note created to have a button with some options, like update the note or remove it, or change the style like make the font bold or italic etc. But I stumbled at adding the events on buttons to show the pop-up. On every button that I click, it shows just the pop from the first note...
index.js
import Notes from './notes.js';
import { toggleNoteModalSettings } from './helpers.js';

const notesList = document.querySelector('#notes-list');

// render all the notes
const renderNotes = (items) => {
  // loop through every note
  items.forEach((item) => {
    // create element
    const div = document.createElement('div');
    div.setAttribute('class', 'note-box-content');
    // I don't know way he didn't render,
    // but, is just a bunch of html that
    // represents the note
    div.innerHTML = ``;

    // add div to the html
    notesList.appendChild(div);
  });
};

const notes = new Notes();
// notes.addNote(
//   'exam',
//   `Adding some data to localStorage is as easy as using the setItem() method. I'll use a generic key and value for the names, but they can be any strings.`,
//   '1hr ago'
// );
// notes.addNote(
//   'personal',
//   `If you want to get the value for a particular key, you'll use the getItem() method`,
//   'November 3 2021'
// );
// notes.addNote(
//   'work',
//   `Finally, you can remove the data with removeItem().`,
//   'November 2 2021'
// );
// notes.addNote(
//   'exam',
//   `Using clear() will clear all local storage.`,
//   'November 1 2021'
// );
// notes.addNote(
//   'hobby',
//   `I like making tutorials where you build a small application completely from scratch with plain JavaScript. A to-do list is a common app idea, but without having a database to store the to-dos, it's not particularly useful, and that adds a bit of complexity beyond beginner territory.`,
//   'Novermber 1 2021'
// );
// console.log(notes.getAllNotes());
// localStorage.removeItem('notes');
// console.log(notes.getAllNotes());

// render on page load
renderNotes(notes.getAllNotes());

// add event to every btn
const btnNoteSettings = document.querySelectorAll('.btn-note-settings');
btnNoteSettings.forEach((btn) => {
  btn.addEventListener('click', toggleNoteModalSettings);
});

notes.js
export default class Note {
  constructor(category, content, timeAgo) {
    this.category = category;
    this.content = content;
    this.timeAgo = timeAgo;
  }

  getAllNotes() {
    let notes;
    if (localStorage.getItem('notes') === null) {
      notes = [];
    } else {
      notes = JSON.parse(localStorage.getItem('notes'));
    }
    return notes;
  }

  addNote(category, content, timeAgo) {
    const notes = this.getAllNotes();
    // console.log(typeof notes);

    const note = {
      category,
      content,
      timeAgo,
    };

    notes.push(note);
    localStorage.setItem('notes', JSON.stringify(notes));
  }
}

helpers.js
export const toggleNoteModalSettings = (event) => {
  const modalNoteModalSettings = document.querySelector('.note-modal-settings');

  const element = event.currentTarget;
  // console.log(element);

  if (element) {
    modalNoteModalSettings.classList.toggle('active');
  }
};

an image with the pop-up


text:
Q: Dual-Monitor Output from a new Macbook Pro I need to output to two screens from a Macbook Pro 17" I'm looking at buying. My current laptop has a VGA port and an HDMI port, and so it's pretty easy to run a dual-display setup with it. How would I connect my displays to my Macbook?
Both displays are 1080p HDMI computer monitors.
If I have to use Thunderbolt, will it work with Linux? I'm planning on dual-booting.

A: You've pretty much got two options for two external monitors on a MacBook Pro:
A) Two Apple Thunderbolt Displays
This is the least flexible, but highest performing solution. Obvious drawbacks are the cost, and not being able to use your existing displays. This only works on Thunderbolt equipped Macs with a discrete graphics card (i.e. not the 13" MacBook Pro or any MacBook Air, nor the base Mini).
B) DisplayLink adapter
You can use one display directly connected to the Thunderbolt/Mini Displayport with an mDP-HDMI adapter, and run the second one with a DisplayLink adapter. DisplayLink is essentially basic graphics card connected to your computer via USB. Because of the limitations of USB, it's not a high performance solution - don't expect to do any gaming on it. This does allow you to use your existing monitors, and at relatively modest expense. You may also want to check the current status of Lion support, as I remember seeing some posts about bugs relating to DisplayLink adapters - they may have been fixed by now however.

A: Two important things will dictate if an arbitrary MacBook Pro will support two monitors:

*

*Does your MBP have Intel integrated graphics or one of the nicer discrete graphics chips?

*Does it have one or two Thunderbolt ports?

If you have Intel's graphics only (the Intel HD Graphics), as found in the 13" MacBook Pro (and the MacBook Air and some Mac minis), you can attach one monitor to the Thunderbolt/mini DisplayPort port.
If you have discrete graphics in addition to the Intel integrated graphics (as found on the 15" and 17" MacBook Pro models), you can attach multiple monitors even if you have only one Thunderbolt port. Remember, though, that all items on the Thunderbolt chain must be Thunderbolt devices until you get to the last item, which can be mini DisplayPort (this is because TB devices have a daisy-chain port; DisplayPort devices are not required to). All adapters for other display plugs that are currently (August 2011) sold are mini DisplayPort, not Thunderbolt, so they'll end the chain. Ergo, the only way to do multiple displays is to have Apple's Thunderbolt display (which has the TB daisy-chain port) and then have an adapter (or just another display) on that. When manufacturers start to make Thunderbolt display adapters, then you can get two of them and hook up whatever displays you want.
Additionally, two Thunderbolt ports allows you to use two Thunderbolt to DVI/DP/whatever adapters rather than buying a true Thunderbolt display that will allow a second non-Thunderbolt graphics adapter to be connected down the chain.
@EmmEff's answer is correct insofar as USB to DVI adapters and their performance issues and the Dual-Link DVI stuff.

A: I personally do not believe a USB to DVI adapter is acceptable if you're looking for any video performance on the second display.  If you absolutely insist on having two external displays, this might be an option.
The Mini DisplayPort to Dual-Link DVI Adapter is for displays requiring a Dual-Link DVI input.  AFAIK, it cannot be used for connecting multiple displays.
According to this article, it is possible to connect only one Thunderbolt display to the MacBook Pro, so daisy-chaining is out.

A: This Anandtech article features a dongle that will convert a DisplayPort signal to two HDMI signals. The resolution is limited, but may be sufficient for what you want to do.


text:
Q: Compare two tables, if not exists update or insert I have a two same tables.Database mysql.
How can I compare two tables?
Table1,Table2 - the same.. differences only in rows
IF in one table id key exists,update row.If key is not exists insert new row.
Thanks.

A: One option might be to use REPLACE, which is like INSERT, except that existing rows 'in the way' are deleted before the insert.
There's also INSERT ON DUPLICATE KEY UPDATE which is somewhat similar - does what you suggest.

A: upsert http://www.xaprb.com/blog/2006/06/17/3-ways-to-write-upsert-and-merge-queries-in-mysql/


text:
Q: Issue to configure river-jdbc oracle I'm trying to use the elasticsearch river-jdbc plugin with an oracle database. When creating the river i got a exception :
[2014-12-10 11:42:44,795][WARN ][river                    ] [Agent Axis] failed to create river [jdbc][quotes]
org.elasticsearch.common.settings.NoClassSettingsException: Failed to load class with value [jdbc]
    at org.elasticsearch.river.RiverModule.loadTypeModule(RiverModule.java:87)
    at org.elasticsearch.river.RiverModule.spawnModules(RiverModule.java:58)
    at org.elasticsearch.common.inject.ModulesBuilder.add(ModulesBuilder.java:44)
    at org.elasticsearch.river.RiversService.createRiver(RiversService.java:137)
    at org.elasticsearch.river.RiversService$ApplyRivers$2.onResponse(RiversService.java:275)
    at org.elasticsearch.river.RiversService$ApplyRivers$2.onResponse(RiversService.java:269)
    at org.elasticsearch.action.support.TransportAction$ThreadedActionListener$1.run(TransportAction.java:113)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ClassNotFoundException: jdbc
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at org.elasticsearch.river.RiverModule.loadTypeModule(RiverModule.java:73)
    ... 9 more

the jdbc oracle driver ojdbc7.jar ( x64 version) is in the $ES_HOME/plugins/jdbc and also $ES_HOME/lib folder.
i'm running elasticsearch v1.4.0 under windows 7 x64, elasticsearch-river-jdbc-1.4.0.3.Beta1
here's the river config :
PUT _river/quotes/_meta
{
    "type" : "jdbc",
    "jdbc" : {
        "url" : "jdbc:oracle:thin@//localhost:1520/test",
        "user" : user,
        "password" : pwd,
        "sql" : {
            "statement" : "select id as \"_id\",quotes.* from quotes where mytimestamp > ?",
            "parameter" : ["$river.state.last_active_begin"]
        },
        "index" : "quotes",
        "type" : "quote"
    }
}

i don't see what's missing in my setup
Regards


text:
Q: Can I change the file icon with Gio?
Possible Duplicate:
How can I change the folder icon?

I'm using python. I want change a file icon with Gio from a python app. I found a lot of deprecated documentation and I'm not sure how I can do it.
I tried this, but nothing happen:
from gi.repository import Gio
f = Gio.File.parse_name('/home/my_user/Desktop/test.txt')
f.set_attribute_string("metadata::custom_icon", '/usr/share/icons/Humanity/animations/48/brasero-disc-100.svg', Gio.FileQueryInfoFlags.NONE, None)

Which class and method have I use? Any idea, please?
Thanks in advance!

A: This is mostly a duplicate of a previous question I answered, but you have 2 problems with your current code:

*

*It is custom-icon and not custom_icon

*You really do not want to set the icon of a file to be a file from the animations context of a theme. Or in general, a file at all. It's better to set the custom-icon-name attribute if you really must, and then have that icon be a part of the theme, so that it works correctly if the user changes themes.


text:
Q: Separating Websocket Publisher I have an application which has push message to client. My application built using spring [boot, security, websocket, angularjs-1]. When user login and accessing a page, user automatically subscribed to multiple end-point (url).
And then, on the same application I have a service which listen to a rabbitmq. Message on rabbitmq contains url where it will pushed + data. Whenever rabbitmq contain a message, this service will push the message to url on message.
Will my application be slow because of this pusher? Or maybe it's effect just a little bit.
I try to separate the pusher, as a daemon/jar application. When this application get message from rabbitmq, application push the message well, but user never get the message. Maybe because user login and subscribe to another application (my first application)
What the best solution for this? Is it possible to separate the pusher? Or maybe it is no problem to merged it, because the effect just a little.
This is how I push the message
@Autowired
SimpMessageSendingOperations messagingTemplate;

public void publishNewItemsState(String itemId, String[] message){
    messagingTemplate.convertAndSend("/topic/area.idsubscribed/"+itemId+"/mc1t1h", message);
}

Sorry for my bad English, and I am a newcomer in websocket


text:
Q: Using homemade scripts without regular output vector in the processing modeler As far as I know, there is no processing script that is able to create PostGIS type output layers including views and materialized views. Therefore I decided to create some alternative PostGIS geoprocessing algorithms (e.g. 'Point on surface'):

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# define Interface
##PostGIS spatial processing (QGIS 2.x)=group
##Point on surface (PostGIS)=name
##Input_layer=vector
##Output_relation_type=selection Table;View;Materialized View
##Output_schema=string public
##Output_layer=string pg_pointonsurface
##Output_primary_key=string gid
##Output_geometry_column=string geom
##Attributes_to_keep_(comma_separated_list)_[non_working_dummy]=string None
##Add_output_layer_to_map=boolean true

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4 import *

from qgis.core import *
from qgis.gui import *
from qgis.utils import *

import psycopg2

# get input parameters from GUI
inlayer = processing.getObject(Input_layer)
inlayer_dp = inlayer.dataProvider().dataSourceUri()

# get database parameters (input layer)
db_name = QgsDataSourceURI(inlayer_dp).database()
db_host = QgsDataSourceURI(inlayer_dp).host()
db_port = QgsDataSourceURI(inlayer_dp).port()
db_user = QgsDataSourceURI(inlayer_dp).username()
db_password = QgsDataSourceURI(inlayer_dp).password()

# get input layer parameters
inlayer_schema = QgsDataSourceURI(inlayer_dp).schema()
inlayer_table = QgsDataSourceURI(inlayer_dp).table()
inlayer_uic = QgsDataSourceURI(inlayer_dp).keyColumn
inlayer_geom = QgsDataSourceURI(inlayer_dp).geometryColumn()
inlayer_crs = inlayer.crs().postgisSrid()

# get output relation parameters
outrelationtype = Output_relation_type
if outrelationtype == 0:
    outrelationtype = 'TABLE'
elif outrelationtype == 1:
    outrelationtype = 'VIEW'
elif outrelationtype == 2:
    outrelationtype = 'MATERIALIZED VIEW'

outschema = Output_schema
outlayer = Output_layer
outpk = Output_primary_key
outgeom = Output_geometry_column
outadd = Add_output_layer_to_map

# check input layer
provider = inlayer.dataProvider()
if provider.name() != 'postgres':
        raise RuntimeError('Input layer \'' + inlayer.name() + '\' is not a PostgreSQL/PostGIS relation :(')

# connect to database
conn = psycopg2.connect( "dbname={0} host={1} port={2} user={3} password={4}".format( db_name, db_host, db_port, db_user, db_password ) )

# create and run query
with conn.cursor() as curs:
    sql = """CREATE {0} "{1}"."{2}" AS SELECT
    row_number() over() AS "{3}",
    ST_PointOnSurface("{4}")::geometry(Point, {5}) AS "{6}"
FROM "{7}"."{8}";
    """.format( outrelationtype, outschema, outlayer, outpk, inlayer_geom, inlayer_crs, outgeom, inlayer_schema, inlayer_table )

    progress.setInfo('Executing SQL statement ... \n')
    progress.setInfo(sql)
    curs.execute(sql)
    progress.setInfo('... done. \n')

    # create primary key, sequence and spatial index for relation type 'TABLE'
    if outrelationtype == 'TABLE':
        sql_pk = """ALTER TABLE "{0}"."{1}" ADD CONSTRAINT "{1}_pkey" PRIMARY KEY ("{2}");""".format( outschema, outlayer, outpk )
        curs.execute(sql_pk)

        sql_seq = """CREATE SEQUENCE "{0}"."{1}_{2}_seq" OWNED BY "{0}"."{1}"."{2}";
        SELECT SETVAL('"{0}"."{1}_{2}_seq"', (SELECT MAX("{2}") FROM "{0}"."{1}"));
        ALTER TABLE "{0}"."{1}"
        ALTER COLUMN "{2}" SET DEFAULT nextval('"{0}"."{1}_{2}_seq"'::regclass);
        """.format ( outschema, outlayer, outpk )
        curs.execute(sql_seq)

        sql_sidx = """CREATE INDEX "sidx_{1}_{2}" ON "{0}"."{1}" USING GIST ("{2}");""".format( outschema, outlayer, outgeom )
        curs.execute(sql_sidx)

    # commit changes if everything went OK
    conn.commit()

# load layer
if outadd:
    uri = QgsDataSourceURI()
    uri.setConnection( db_host, db_port, db_name, db_user, db_password )
    uri.setDataSource( outschema, outlayer, outgeom, None, outpk )
    vlayer = QgsVectorLayer( uri.uri(), outlayer, "postgres" )
    QgsMapLayerRegistry.instance().addMapLayer(vlayer)

Unfortunately, it's not possible to fully integrate these PostGIS scripts in the processing modeler, because they don't create regular output vectors. Is there any way to access the output function of the processing modeler?


text:
Q: Consolidating JSON Data in PHP? I'm trying to sort through every file in a directory, read the json data, decode it, put it in an array, and then write it all to a new file.
The problem I'm running into is the resulting array is just an array of arrays of json data, it seems.
Here's my code:
    $AllAppointmentDataFileName = 'AllAppointmentData.jsonp';
    $AllAppointmentDataURL = '../Appointments/' . $AllAppointmentDataFileName;
    if ($handle = opendir('../Appointments')) {

        while ( false !== ($entry = readdir($handle)) ) {
            if ($entry != "." && $entry != ".." && $entry != $AllAppointmentDataFileName) {

                $AllAppointmentData .= json_decode(file_get_contents('../Appointments/' . $entry));

                print_r($AllAppointmentData); echo "
";

                echo "$entry:
" . file_get_contents('../Appointments/' . $entry) . "
";
            }
        }

        closedir($handle);
    }

    file_put_contents($AllAppointmentDataURL, json_encode($AllAppointmentData));

The print_r just returns "Array."

A: The .= operator is for string concatenation; it is not for adding an element to an array.
You should be using [] = instead:
$AllAppointmentData[] = json_decode(file_get_contents('../Appointments/' . $entry));

If your files contain arrays that you want merged into a single array, you can use a foreach loop:
$curAppointmentData = json_decode(file_get_contents('../Appointments/' . $entry));
foreach ($curAppointmentData as $obj) {
    $AllAppointmentData[] = $obj;
}


text:
Q: Stacked bar plot : y axis gets I have a set of test data like this
 week       reason         gross
    2   Наличные            356.54
    6   FuelUp             1157.54
    7   Альянс              706.54
   10   FlashPay           1567.54
   10   Наличные            135.54
   19   FuelUp             3045.54
   19   Карты Сбербанка     723.54
   19   Наличные           1230.54
   24   FuelUp              875.54
   27   FlashPay           1260.54
   28   Альянс              556.54
   33   FlashPay           9756.54
   33   Ваучеры             756.54
   37   Ваучеры             473.54
   38   Ваучеры             358.54
   41   Карты Сбербанка     600.54
   49   Наличные            100.00

And I made a stacked bar plot with this code:
query$week = factor(query$week,ordered=TRUE)
p <- ggplot(query,aes(x=week,y=gross,fill=reason)) + theme_light() +
        geom_col(position="stack") +
        scale_fill_viridis(discrete = T) +
        labs(x="Неделя 2020")
print(p)

where query is just that pice of data (that came from PostgrSQL. So far, so good but such a code results in such a picture with an incomlete Y axis.

Why is that and what should I do to "prolong" tics and labels on the axis?

A: Your gross variable is not a number.
Starting data, where gross is a string (or factor), not a number:
query <- structure(list(week = structure(c(1L, 2L, 3L, 4L, 4L, 5L, 5L,
5L, 6L, 7L, 8L, 9L, 9L, 10L, 11L, 12L, 13L), .Label = c("2",
"6", "7", "10", "19", "24", "27", "28", "33", "37", "38", "41",
"49"), class = c("ordered", "factor")), reason = c("", "FuelUp",
"", "FlashPay", "", "FuelUp", "_", "", "FuelUp", "FlashPay",
"", "FlashPay", "", "", "", "_", ""), gross = c("356.54", "1157.54",
"706.54", "1567.54", "135.54", "3045.54", "723.54", "1230.54",
"875.54", "1260.54", "556.54", "9756.54", "756.54", "473.54",
"358.54", "600.54", "100.00")), row.names = c(NA, -17L), class = "data.frame")

(My hasty import butchered the reason ... that'll skew the display/legend a bit but does not change the premise of my answer.)
The plot:
p <- ggplot(query,aes(x=week,y=gross,fill=reason)) + theme_light() +
        geom_col(position="stack") +
        scale_fill_viridis(discrete = T) +
        labs(x="Неделя 2020")

If we convert it to numeric, the plot looks more normal.
query$gross <- as.numeric(query$gross)
p <- ggplot(query,aes(x=week,y=gross,fill=reason)) + theme_light() +
        geom_col(position="stack") +
        scale_fill_viridis(discrete = T) +
        labs(x="Неделя 2020")
p


text:
Q: How can we get the list of selected dates from days of current year in flutter? I want to get the list of dates from selected day from calendar.
The scenario is that I have a screen in which I am displaying the weekly days and user can select any of the day from week. Suppose that any user selected "Monday" and "Friday" from that weekly Calendar then I want the dates which is coming on "Monday" and "Friday" during the current whole year in a list. I attached the screen shot of that app for getting better idea.
This functionality I want in flutter. So, if anyone have idea about it then please let me know.
Any type of your help is appreciated.
Thanks in advance.
Image:


text:
Q: Prove that $\lim_{\theta \to 0}\frac{\tan\theta}{\theta} = 1$ So I've written a complete proof for this statement, and need confirmation regarding whether or not all I've written is true.
First things first, I made the substitution $\displaystyle\tan\theta=\frac{\sin\theta}{\cos\theta}$, and from here I set up the following circle with center $O$ and radius $1$ arbitrary unit to find another limit: $\displaystyle \lim_{\theta \to 0}\frac{\sin\theta}{\theta}$ (which I will later reveal why)

Given this, it's evident that:
$\Delta OBA \le$ sector area $OBA \le \Delta OTA$, which is equal to $\displaystyle\frac{1}{2}\cdot1\cdot1\sin\theta \le \frac{1}{2}\cdot1^2\cdot\theta\le\frac{1}{2}\cdot1\cdot\tan\theta$
which simplifies down to:
$\displaystyle \sin\theta \le \theta \le \frac{\sin\theta}{\cos\theta}$
and from here, dividing through by $\sin\theta$ produces:
$\displaystyle 1 \le \frac{\theta}{\sin\theta} \le \frac{1}{\cos\theta}$
and since the limit of $\cos\theta$ approaches $1$ as $\theta$ approaches $0$, the following is true:
$\displaystyle 1 \le \frac{\sin\theta}{\theta} \le 1$
which implies that $\displaystyle \lim_{\theta \to 0}\frac{\sin\theta}{\theta} = 1$
And the rest is as follows:
$\displaystyle \lim_{\theta \to 0}\frac{\tan\theta}{\theta} =\lim_{\theta \to 0}\frac{\sin\theta}{\theta}\cdot \lim_{\theta \to 0} \frac{1}{\cos\theta} = 1$
therefore; $\displaystyle \lim \atop \theta \to 0$ $\displaystyle \frac{\tan\theta}{\theta} = 1$, QED
(Is all of what I've written correct?)

A: A couple of remarks.
1- Change $<$ to $\le$.
2- Your proof presumes $\theta >0$. You also need to consider $\theta < 0$ case.
3- In both cases, establish $\cos(\theta) \le  \frac{\sin(\theta)}{\theta} \le 1$ and evaluate the limits.

A: Only one thing is wrong: don't ever have separate limits for $\sin\theta, \,\theta$ in your fraction, as that gives the indeterminate form $0/0$. The limit of $fg$ only has the obvious factorization in terms of two limits if they are finite, but $1/\theta $ diverges.


text:
Q: CSS :hover Selector does not change colour I am new to CSS, so please don't bite my head off here for something very simple. Basically, I am trying to change the color of a uni code character when hovering the cursor over it, but it does not seem to be working.
Current Code:

.fa:hover {
  color: red;
}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

Could someone please, kindly, tell me what I am doing wrong, along with some better advice on how to avoid common CSS mistakes, or if this is bad practice. Thank you!

A: The problem is that you are defining the color to white in your HTML with inline CSS. Inline styling takes precedence over external stylesheets, so your CSS is ignored. Move the CSS from the HTML document to your external CSS file.

body {
  background-color: #C2C2C2;
}

.fa {
  font-size: 19px;
  color: white;
  margin-left: 7px;
  margin-top: 5.5px;
  text-decoration: none;
}

.fa:hover{
  color: red !important;
}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>


text:
Q: How to send user data to react js after logging in when passport google oauth 20? Hi I got 2 servers running
backend server is running on port 3000 & react is running on port 3001
I have already setup the server route for the login
Its look like this
router.get("/google",passport.authenticate("google", {
scope: ["profile"],
}))

router.get("/",(req,res) => {
  res.send("Hello")
})

router.get("/google/callback",
passport.authenticate("google", { failureRedirect: ["/nouser"]),
 function(req,res) {
   console.log(req.user);
   res.redirect("/")
   }
  })

When i console.log req.user Its returning user data which is an object.
So How can i access the user data from the app.js Which is a react file (frontend)


text:
Q: Filtering Queries from Prismic and GatsbyJS Seeing some strange behavior querying a Prismic data source and filtering by a content relationship in my gatsby site. I"m trying to create a page filtering some products based on the category passed into this page. Reading both the Prismic and Gatsby docs, i should be able to filter the data with the where clause but i get this error when i try to build
error    Unknown argument "where" on field "allPrismicModel" of type "Query"

Below is the relevant sections of the query
query getProducts($uid: String) {
    allPrismicModel(where: { system_category: $uid }) {
      edges {
        node {
          data {
            system_category {
              uid
            }
            ...other fields here...
          }
        }
      }
    }
  }

Anybody ever encountered this or know how to resolve it?

A: where doesn't exist in Gatsby. I'd highly recommend using GraphiQL (under localhost:8000/___graphql) to see what you can do. There is also this doc showing all possibilities: https://www.gatsbyjs.org/docs/graphql-reference/
It'll probably will be in the end (untested):
filter: { system_category: { eq: $uid } }

A:

allPrismicModel(filter: { system_category : { eq: $uid } }) {
edges {
        node {
          data {
            system_category {
              uid
            }
            ...other fields here...
          }
        }
      }
    }
  }

This is a more common way to run that query


text:
Q: Entity Framework - CodeFirst, no database I have been playing around with EF6 CodeFirst and Migrations. So far all good. But there is one thing I don't understand (conceptually):
In my specific case I am determining the database to connect to at runtime (via some external config XML / JSON or similar). So during development I am a) not certain what database it is I am working with and b) do not necessarily have one available. But EF still requires one, because otherwise I cannot use Update-Database. And if I cannot use Update-Database, I cannot scaffold further migrations.
Is there something I am missing or do I necessarily need a dev-database to develop something using EF6?
The real problem I face is that Update-Database fails with an error telling me that connecting to a DB failed.


text:
Q: Hi I am learning about angularjs. I want to get the TEMP from one json and display that value in my component. I dont konw what I am doing wrong I m learning js fetch.
I am trying to get the value of temp from a respons and display that value in my component.js
weather.component.js
```
    myApp.component('weatherComponent', {
        template:"<p>Weather: {{vm.weather}}</p>",
        controllerAs: 'vm',
        controller: function WeatherController($scope,$element, $attrs) {
          vm = this;

          var apikey = "";
          var city = "London";

          fetch("https://api.openweathermap.org/data/2.5/weather?q="+city+"&appid=" + apikey)
          .then(function(response) {
            vm.weather = response.main.temp;
            console.log("weather: "+ vm.weather);
            return response.json();
          })
          .then(function(myJson) {
            console.log(myJson);
          });

        }
      });
```

index.html
```
<weather-component></weather-component>
<script src="utils.js"></script>
<script src="weather.component.js"></script>
 ```

In utils it is initialized var myApp = angular.module('myApp', []);

The API Response url: https://openweathermap.org/current

A: *

*To get the element from the json:

controller.weather = response.weather[0].description;

*The way to reolve this:
create a service, so I could get the data & change the component.
I discard the idea about to use "fetch".

weather.service.js
```myApp.service('weatherService', function($http, $q) {
    this.getWeather = function (apikey, city) {
        var deferred = $q.defer();
        // HTTP call
        $http.get("https://api.openweathermap.org/data/2.5/weather?q="+city+"&appid=" + apikey)
            .then(function(response) {
                deferred.resolve(response.data);
            }, function(response){
                deferred.reject(response);
            });
        return deferred.promise;
    };
});
 ```

weather.component.js
```
 myApp.component('weatherComponent', {
  template:"<p>Weather: {{weather}}</p>",
  controllerAs: 'vm',
  controller: function WeatherController($scope, weatherService, $element, $attrs) {
      var apikey = "b441194a96d8642f1609a75c1441793f";
      var city = "London";
      var controller = $scope;
      controller.weather = "None";
      weatherService.getWeather(apikey, city).then(function(response) {
          controller.weather = response.weather[0].description;
      });
  }
});
 ```


text:
Q: AEM Display DeActivate Later time In AEM (Adobe Experience Manager 6.2) a user can select a page to be "Activated Later" (Publish Later) and choose a date/time.  The Notifications display will show "Waiting for activation" with the date/time.  This is great.  But when a page is scheduled for deactivation using the "DeActivate Later" (UnPublish Later), the Notification does not contain the date/time.  Is there a way to add text to the comments section of a notification to include the date/time?  Or trigger AEM to fill it in?
Notifications:

A: This is because of difference in workflow model of both requests.
workflow model for activation request

workflow model for deactivation request:

As you can see there is a Create version step in activation request. I think this step is setting above message.
If you want to create the unpublished version for your page, you can add the same step to deactivation model or create your own process step for adding the time stamp, then add the same to the deactivation model.
It should work.


text:
Q: FCM Send message to multiple devices - which way to use? There are several ways to send FCM messages and I don't understand which one to use even if I read the documents over and over.
My use case:
I have a user that is logged into the app on her iPhone, iPad and Android tablet. I want to make sure the push notifications are sent to all of her devices.
There are three ways to do this (I'm using the admin to send the push notifications):

*

*Topic messaging (messaging().sendToTopic): My understanding this is for sending the same notification to larger groups. For example a topic could be all users that want weather notifications for New York. Not for my use case.

*Send Multicast (messaging().sendMulticast([array of tokens]): My understanding this will send the same message to all device tokens in the array (up to 100). This seems perfect for my use case, right?

*Device group messaging (messaging().sendToDeviceGroup): I don't really understand this one. Why use this instead of multicast or topics?
For my use case it seems the best way is to each time a FCM token is updated I add this token to the user in the database. I then send the notification using the admin.messaging().sendMulticast([array of tokens]). Is this what you would recommend? Why or why not?

A: You probably want to use multicast if you're targeting an individual user's specific devices.  You probably don't want to use device groups.  I suggest reading the documentation to understand how device groups work:

Device group messaging allows you to add multiple devices to a single group. This is similar to topic messaging, but includes authentication to ensure that group membership is managed only by your servers. For example, if you want to send different messages to different phone models, your servers can add/remove registrations to the appropriate groups and send the appropriate message to each group. Device group messaging differs from topic messaging in that it involves managing device groups from your servers instead of directly within your application.

Device groups are basically just topics whose membership is fully managed by your server code, not by client code.


text:
Q: Auto completion in Atom messed up I don't know whether this is specific to javascript or not, but I'm seeing this behavior:
console.lo

TAB or ENTER
console.console.log();

I would expect it to auto-complete to:
console.log();

Am I doing something wrong?

A: Atom auto-completion works like this:
log -> console.log();
so it gets confused and auto-completes console.lo -> console.console.log();
A workaround is using log as your short-hand instead.


text:
Q: How do I use jQuery UI's sortable functionality on a table hello friend i found this code from this link . when i add more data in any of <li> it become overflow . <li> height is define in css when i remove the height its not working perfectly .I tried to convert it into table rows but I fail to do this please tell me the solution . I want to add more and more data in any of <li>
Thanks friends

A: First of all if you want to add more data to the <li>, I would suggest you to use <div> rather than an <li> and then use overflow in the CSS. In a table if you have sortable then in that case dont use table. <td> within a table can be sorted but not outside of that
table. I have a sample code where I have sone it in a bunch of div's. Check it out on fiddle
http://jsfiddle.net/shivkumarganesh/jYFRB/


text:
Q: "host" a file on a specific URL for testing I want to run UI tests on my pure vanilla ES5 JS (not Angular, and no modules, important for the rest I suppose) web page but, for that, I need to it on a specific URL (set a hostname and port, and other).
I use Jasmine and Karma for my unit test and run them automatically on Travis CI.
Now I reached the point where I want have functional/UI tests. For that, Protractor, in combination with Selenium, was recommended. But I'm encountering various problems (and I'm not even close to trying to incorporate it to Travis CI).
Short version
I have a local file index.html and, in order for it to properly initialise, it requires a specific URL ("<protocole, mostly http>://<some-host>:<port>/<some-path>/index.html?<some-query>").
I can currently access the index, but only "locally" ("file:///<path-to-local-project>/index.html?<query>") and therefore am only able to test the error use case where URL is malformed (hey, at least that's one of the tests).
I need a way to host/say "file:///<path-to-local-project>/index.html?<query>" is accessed via "http://<some-host>:<port>/<some-path>/index.html?<query>" because, when integrated to the full program, the page will be hosted somewhere and the URL contains valuable information for dynamic behaviors (really have no idea which keyword to use there ("host", "route"... ?) nor am I even certain this is to be configured in protractor or actually have to prepare some kind of hosting script just for testing. And keep in mind that, in the end, I want to be able to run these on Travis CI too)
What I have
In protractor.conf.js
exports.config = {
  framework: 'jasmine',

  baseUrl: 'file:///' + __dirname,

  onPrepare: function(){
    /**
     * If you are testing against a non-angular site - set ignoreSynchronization setting to true
     *
     * If true, Protractor will not attempt to synchronize with the page before
     * performing actions. This can be harmful because Protractor will not wait
     * until $timeouts and $http calls have been processed, which can cause
     * tests to become flaky. This should be used only when necessary, such as
     * when a page continuously polls an API using $timeout.
     *
     * @type {boolean}
     */
    browser.ignoreSynchronization = true;

    global.dv = browser.driver;
    // By default, Protractor use data:text/html,<html></html> as resetUrl, but
    // location.replace from the data: to the file: protocol is not allowed
    // (we'll get 'not allowed local resource' error), so we replace resetUrl with one
    // with the file: protocol (this particular one will open system's root folder)
    browser.resetUrl = 'file://';
  },

  seleniumAddress: 'http://localhost:4444/wd/hub',

  specs: [
    'test/protractor/**/*.spec.js',
  ],

  capabilities: {
    browserName: 'chrome',
    /*
    proxy: {
      proxyType: 'manual',
      httpProxy: 'localhost:69/ID-420'
    }, //*/
    chromeOptions: {
      // --allow-file-access-from-files - allow XHR from file://
      args: ['allow-file-access-from-files']
    }
  }
};

In spec.js
describe('The main page', function () {

  beforeEach(function () {
    // jasmine.Ajax.install();  // how I intercept http requests in the unit tests. Here I may need another package apparently
    console.log("browser", browser);
    dv.ignoreSynchronization = true;
  });
  /*
  afterEach(function () {
    jasmine.Ajax.uninstall();
  });
  // */

  it('should display an error message in the alert if no parameters are provided', function () {
    browser.waitForAngularEnabled(false);
    browser.get('/index.html');

    element(by.className('ajs-content')).getText().then(console.log);
    browser.sleep(5000);
    expect(element(by.className('ajs-content')).getText()).toEqual("No ID or Host detected");
    // expect(element(by.className('ajs-content')).getText()).toEqual(new EXCEPTIONS.NoHostOrIdInURI().description); // not working because unable to import scripts without **modules** (since ES5) but np, I can hard code the expected result
    browser.getCurrentUrl().then(console.log);
  });
});

Yes, this works, but if I can't set a custom URL for the file, I cannot test any other use case... And the topics I find online often are in Angular.
Previous question (way too vague) but maybe contain additional infos.


text:
Q: Is there a library that does array equivalency for numpy.ma? There is a numpy.testing package for comparing numpy arrays, but there doesn't appear to be an equivalent for masked arrays. Is there a library out there that does this already?
I notice that numpy.ma itself has some comparison functions like numpy.ma.allequal, but this function doesn't seem to check that both array masks are identical. E.g. -
In [151]: a = ma.masked_array([0,1,2,3],[True,False,False,False])

In [152]: b = ma.masked_array([0,1,2,3],[True,True,False,False])

In [153]: ma.allequal(a,b)
Out[153]: True

A: ma.masked_array.__eq__ is actually implemented in numpy, but maybe it does not have the semantics you are looking for? You can get to the documentation with help(ma.masked_array.__eq__) with a python interpreter, it states:

Check whether other equals self elementwise

Which is what I can see given your example: it does the comparison where the data is marked as valid, and returns the result in the data field of a masked array. Wherever the data was invalid (for a or b) the resulting masked array field is masked.
>>> import numpy as np
>>> import numpy.ma as ma
>>> a = ma.masked_array([0,1,2,3],[True,False,False,False])
>>> b = ma.masked_array([0,1,2,3],[True,True,False,False])
>>> a==b
masked_array(data = [-- -- True True],
             mask = [ True  True False False],
       fill_value = True)
>>> b = ma.masked_array([0,1,2,4],[True,True,False,False])
>>> a==b
masked_array(data = [-- -- True False],
             mask = [ True  True False False],
       fill_value = True)

If you want to check that all the fields are valid and equal you could use:

    np.allfalse((a==b).data)

edit: actually, I think you would need:
not np.any((a==b).mask) and np.alltrue((a==b).compressed())

If you want to check that all the valid fields are equal you could use:
np.alltrue((a==b).compressed())

As user2357112 explained in the comment, numpy.testing provides functions for unit testing on numpy arrays, which might not be what you are looking for. It it is, you could still use the regular assert function with the examples that I provided.


text:
Q: How to satisfy both Rails controller naming conventions and naming of callback path? When using an oauth provider I want to have a callback link like so: base_url/callback. I want to have a controller responding with its index action to this url. Here's the thing however - if I create a CallbacksController the path to the index action will be:
base_url/callbacks
and I don't want it to be plural.
I don't want to use the show action as the oauth provider won't be providing a callback id to the controller and I won't be storing the callbacks in the DB anyway. So I have two choices - create a CallbackController or create a custom route like to:
get '/callback' => 'callbacks#index'

What would be the right thing to do here?

A: You could use a singular resource for this:
resource :callback, only: [:index]


text:
Q: Hide all elements except one div for print view I have the following CSS for my print style:
* {
 display:none;
}

#printableArea {
 display:block;
}

I expected this to hide all elements, and only show the printableArea, however everything gets hidden. In print view, all I get is a blank page.
I have it included properly in the HEAD, with media="print" on this particular stylesheet.

A: Answering because I found this question while searching for this
Instead of 'display: none' you can use :
* {
  visibility: hidden;
  margin:0; padding:0;
}

#printableArea * {
  visibility: visible;
}

source : https://www.concrete5.org/community/forums/5-7-discussion/need-to-print-a-certain-div-and-ignore-everythign-else-on-the-pa

A: You might try popping it up on top of everything.  This solved 90% of my problems, then I just had to make a .noprint class and add it to a few straggling elements.
.print_area{
    position: fixed;
    top: 0px;
    left: 0px;
    width: 100%;
    z-index: 9999;

    background-color: #ffffff;
}

A: If you want to use JavaScript, you can try this simple snippet that doesn't even require jQuery:
document.body.innerHTML=document.getElementById('printableArea').innerHTML;

A: If an element is not displayed, then none of its children will be displayed (no matter what their display property is set to).
* matches the  element, so the entire document is hidden.
You need to be more selective about what you hide.

A: You're taking the right general approach, but you want to use visibility: hidden instead of display: none so that you can set child elements to be visible.
See Print

 only?

A: html body * {
 display:none;
}

#printableArea {
 display:block;
}

Also, you may need an !important on #printableArea, but probably not.

A: make a div wrap everything after the body tag. Before the wrap div, put the visible item's div.
I had to do this to make a simple username-password page, and needed to hide everything, except the half-opaque sign-in form's background. So, after the correct credentials were typed in, the form would animate out, and the half-opaque page cover would animate out, and finally, EVERYTHING aside would show up and you could use the page normally.

A: There is a one-line solution:
With JQuery
var selector = '';
$(document.head).append($('style').text('*{visibility:hidden}' + selector + '{visibility:visible}'));

Without JQuery
var selector = '';
document.head.appendChild(Object.assign(document.createElement('style'), { innerText: '*{visibility:hidden}' + selector + '{visibility:visible}' });

In both examples, set the selector variable to the selector you want. For example, div#page:hover or p.class1,p.class2

A: @media print {
    * {
        visibility: hidden;
    }

    /* Show element to print, and any children he has. */
    .svgContainer, .svgContainer * {
        visibility: initial;
    }
}

Make sure any children elements are also visible. Remember that invisible elements still influence positionning of other elements in the page. In my (simple) case, I just added position: fixed; on .svgContainer (somewhere else).

A: Simply you can use the following code and assign "hide" class to that specific element you dont want to display on print page

A: There is another clean way to achieve this:
* {
    visibility: hidden;
}

#printableArea {
    visibility: visible;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
}

That way you're going to get only the #printableArea element in the print view and all of the other elements will be hidden.


text:
Q: Default directory change by command line Recently I had a need to change the installation directory of a program, and I wanted to know how to execute such a function via PowerShell, Python, or any other.
This would be for Windows, for example, when we install via UI it offers us a default installation directory, as in the example below with 7-Zip.

Through the UI we can freely change this directory, but I wanted to know how you can do the same operation from the command line, to change it to something like the example below.

This would be very useful in automation scripts, especially when working with high volumes of machines.
I appreciate any help!

A: According to 7zip documentation, to install it in a silent mode you can :
For exe installer: Use the "/S" parameter to do a silent installation and the /D="C:\Program Files\7-Zip" parameter to specify the "output directory". These options are case-sensitive.
For msi installer: Use the /q INSTALLDIR="C:\Program Files\7-Zip" parameters.
In the second case it's quite a standard for Windows.


text:
Q: Algorithm Analysis I have an algorithm with the following pseudocode:
R(n)
if(n = 1)
  return 1
else
  return(R(n-1) + 2 * n + 1)

I need to setup a recurrence relation for the number of multiplications carried out by this algorithm and solve it.
Is the following right?
R(1) = 0
R(n) = R(n-1) + n^2

A: You are performing only one multiplication per step.  Therefore, the relation will be:
R(n) = R(n-1) + 1

A: In the algorithm as shown, R(n) is calculated by adding R(n-1) to 2*n+1.  If 2*n is calculated using a multiplication, there will be one multiplication per level of recursion, thus n-1 multiplications in the calculation of R(n).
To compute that via a recurrence, let M(n) be the number of multiplications used to compute R(n).  The recurrence boundary condition is M(1) = 0 and the recurrence relation is M(i) = M(i-1) + 1 for i>1.
Errors in writing  "R(1) = 0; R(n) = R(n-1) + n^2" as the recurrence for the number of multiplications include:
• R() already is in use as a function being computed, hence re-using R() as the number of multiplications is incorrect
• Each level of recursion in the algorithm adds one multiplication, not n² multiplications.
Note, R(n) = 1 + 5 + 7 + ... + 2n+1 = 1 + 3 + 5 + 7 + ... + 2n+1 - 3 = n²-3; that is, function R(n) returns the value n²-3.


text:
Q: Caliburn Micro, Message/Action to another ViewModel I got a ShellViewModel with multiple sub views (and viewmodels). A sub view can bind to a method in the ShellViewModel easyly with Message.Attach. It bubbles up. But can I "bubble down" so the ShellViewModel triggers a method in a sub ViewModel or even from one sub view up and then down to another one?
AFAIK I could use EventAggregator but is it the most elegant way?

A: I believe, there is no such thing as "bubble down". But, you can use Bind.ModelWithoutContext to move action target to your child ViewModel:
<Button cal:Message.Attach="DoIt" cal:Bind.ModelWithoutContext="{Binding Path=ChildViewModel}" Content="Test It!"/>

There is "some" documentation on https://caliburnmicro.codeplex.com/wikipage?title=All%20About%20Actions. Hope it will help you.


text:
Q: Setting up different droppable area in one canvas HTML5 I want to have different droppable area in one canvas, an example can be seen on this link http://custom.case-mate.com/diy?bypassLandingPage=true#design/iphone5_barelythere
I want to drag and drop images on to different portions of the same canvas.
after checking the link, can anybody tell me how they have done this?

A: What you do first is to define the regions in an array that you want to use as drop zones locally on the canvas.
From there it is simply check the mouse client position that you receive in the drop event adjusted for the canvas:
/// some random regions to check against
regions = [[0, 0, 100, 100],
           [120, 50, 100, 100],
           [30, 230, 100, 100],
           [300,300,100,100]],

/// this is used to adjust mouse pos. later
rect = canvas.getBoundingClientRect(), ...

Setup canvas to handle drop events:
canvas.addEventListener('dragover', fileDragOver, false);
canvas.addEventListener('drop',     fileSelect,   false);

When you now drop files to the canvas you can check everything - here we draw a random fill color for the region the file(s) where dropped at (if any):
function fileSelect(e) {

    e.stopPropagation();
    e.preventDefault();

    /// adjust mouse position relative to canvas
    var x = e.clientX - rect.left,
        y = e.clientY - rect.top;

    /// iterate the regions
    for(i = 0; r = regions[i]; i++) {

        /// are mouse in a region?
        if (x >= r[0] && x < r[0] + r[2] &&
            y >= r[1] && y < r[1] + r[3]) {

            /// if so, fill that region
            ctx.fillStyle = 'rgba(' +
                parseInt(255 * Math.random(), 10) + ',' +
                parseInt(255 * Math.random(), 10) + ',' +
                parseInt(255 * Math.random(), 10) + ',' +
                '0.5)';

            ctx.fillRect(r[0], r[1], r[2], r[3]);

            /// ... do something else
            breaK;
        }
    }

}
Here is a working example (drop some files on the boxes):
ONLINE DEMO


text:
Q: Book about Ruby on Rails with Apache2? I used to use the Webrick server for Ruby on Rails, but now my boss asked me to run the ROR code on apache server, I see there are some difference between these two servers, and I don't know how to access the controller/action on apache, so anyone happens to know any book about ROR on apahce? Thx!

A: To run directly in Apache, your best bet is to use Phusion Passenger, which can act as an Apache module.

However, I think you're missing a bit of conceptual information as well.  Here's some of the common Rack servers used to host rails:
WEBrick: A web server implemented purely in Ruby (that ships with Ruby).  It is not very performant, and is relatively limited.  It makes for a great development webserver, but most people don't use it in production.
Thin: A very performant evented web server that is particularly easy to get up and running.
Unicorn: A forking web server that is widely used and recommended (written by GitHub) - but requires a bit more management to get up and running in production.
In nearly all cases, however, people generally have Nginx or Apache in front of their Rails webserver of choice (as a proxy):

*

*Nginx/Apache do a much better job of serving static files than any of the options above.  If you are not using a CDN to host your assets, you should definitely configure the proxy to host them.

*Nginx/Apache are great at managing large volumes of requests and queueing them so that your app server can focus on in-flight requests rather than a deluge of queued-up requests.

*Less surface area for security vulnerabilities.
My configuration of choice is Nginx+Unicorn; I find Apache too unwieldy to administrate, and Unicorn is particularly great.


text:
Q: How to disable refresh token using angular-auth-oidc-client and openiddict? I am using angular-auth-oidc-client lib with openiddict as identity server:
openiddict config:
.AddServer(options =>
   {
       // Enable the authorization, logout, token and userinfo endpoints.
       options.SetAuthorizationEndpointUris(
                 openIddictConfig.AuthorizationEndpointUris)
               .SetLogoutEndpointUris(openIddictConfig.LogoutEndpointUris)
               .SetTokenEndpointUris(openIddictConfig.TokenEndpointUris)
               .SetAccessTokenLifetime(TimeSpan.FromSeconds(10))
               .SetIdentityTokenLifetime(TimeSpan.FromSeconds(10))
               .SetUserinfoEndpointUris(openIddictConfig.UserinfoEndpointUris);

       // Mark the "email", "profile" and "roles" scopes as supported scopes.
       options.RegisterScopes(Scopes.Email, Scopes.Profile, Scopes.Roles);
       options.SetAccessTokenLifetime(TimeSpan.FromSeconds(10))
               .SetIdentityTokenLifetime(TimeSpan.FromSeconds(10));
       // Note: this sample only uses the authorization code flow but you can enable
       // the other flows if you need to support implicit, password or client credentials.
       options.AllowAuthorizationCodeFlow().RequireProofKeyForCodeExchange();
       //options.AllowRefreshTokenFlow();

       // Register the signing and encryption credentials.
       options.AddDevelopmentEncryptionCertificate()
               .AddDevelopmentSigningCertificate();

       // Register the ASP.NET Core host and configure the ASP.NET Core-specific options.
       options.UseAspNetCore()
               .DisableTransportSecurityRequirement()
               .EnableAuthorizationEndpointPassthrough()
               .EnableLogoutEndpointPassthrough()
               .EnableTokenEndpointPassthrough()
               .EnableUserinfoEndpointPassthrough()
               .EnableStatusCodePagesIntegration();

       // Encryption and signing of tokens
       options
       //    .AddEphemeralEncryptionKey()
       //    .AddEphemeralSigningKey()
           .DisableAccessTokenEncryption();
   })

Angular config:
getOpenIDConfiguration(): OpenIdConfiguration {
  return {
   authority: this.oidcConfig.authority,
   clientId: this.oidcConfig.clientId,
   redirectUrl: this.oidcConfig.redirectUrl,
   postLogoutRedirectUri: this.oidcConfig.postLogoutRedirectUri,
   scope: 'openid profile email ',
   responseType: 'code',
   silentRenew: false,
   useRefreshToken: false,
   logLevel: LogLevel.Debug,
  }
}

NB: with this configuration when the token lifetime is expired there is a refresh token.
All I need is to disable the refresh token and set the expired lifetime to the token finally how to implement an expired token handler and log out? Thank you guys for your help.


text:
Q: UpdateRecipientSignatureImage API how to construct the request body? Seems like there is no documentation on how to construct a request body or payload for UpdateRecipientSignatureImage API. I need to use this API to try update a signature for a accountless signer.
Please, if anyone had experience with this API help me.
Thank you!
Ref.: https://docs.docusign.com/esign/restapi/Envelopes/Envelopes/updateRecipientSignatureImage/#definitions

A: Include the image as the body of the Put request:

*

*Set the Content-Type header. Eg image/jpeg, image/png, etc

*Set the body of the PUT request to be the binary version of the image data.