text:
Q: How to insert an item in-between an array using traditional forloop based on criteria? How to insert an item in-between an array using traditional forloop based on criteria?
const itemToInsert = {id: '23r', distance: 100}

const items = [
    {id: 'rtr', distance: 200},
    {id: 'ruy', distance: 120},
    {id: 'let', distance: 90},
    {id: 'rll', distance: 170},
    {id: 'brr', distance: 210},
]

what I've tried:
for(let i=0, temp, item; i<items.length; i++) {
    item = items[i]

    if(item.distance < itemToInsert.distance) {
        temp = item
        items[i] = itemToInsert
        items.concat([temp])
    }
}

So the idea here is to insert in-between an array based on param distance.
Seems like thought mine is working fine. I see it's not inserting properly.

A: For loop sample
Based on your original post, this is a simple example of how I'd build the new array with both post and pre insertion based on criteria:

const data = ['derek', 'was', 'here', 'and', 'there'];
const newArr = [];

for (let i = 0; i < data.length; i++) {
  const datum = data[i];

  if (datum === 'here') {
    newArr.push('not');
  }

  newArr.push(datum);

  if (datum === 'and') {
    newArr.push('or');
  }
}

console.log(newArr);

Sort sample
If array order doesn't matter, I'd suggest using a sort. In this sample, I'm inserting into the array, and then sorting the array desc based on distance

const itemToInsert = {id: '23r', distance: 100}

const items = [
    {id: 'rtr', distance: 200},
    {id: 'ruy', distance: 120},
    {id: 'let', distance: 90},
    {id: 'rll', distance: 170},
    {id: 'brr', distance: 210},
]

items.push(itemToInsert);

items.sort((itemA, itemB) => {
  if (itemA.distance > itemB.distance) {
    return -1;
  } else if (itemA.distance < itemB.distance) {
    return 1;
  } else {
    return 0;
  }
})

console.log(items);


text:
Q: Конвертировать Netscape cookie в json cookie на python Затер до дыр весь гугл русский и английский, но так и не смог найти решения сего вопроса.
Собственно сабж.
У меня есть куки в base64 я их расшифровываю base64.b64decode().decode('utf-8') и получаю netscape куки которые мне нужно запихнуть в селениум и дальше с ними там работать. Для селениума нужны json куки соответсвенно, но облазив весь интернет я не нашел ни одного примера как запилить этот конвентер на python.
Все рабочие конвенторы это только сайты. С которых не понять как они там под капотом это делают.
Кто сможет подсказать как это правильно реализовать? Или можно есть какая то библиотечка, но у меня банальным поиском не получилось ее найти.

A: def base64CookieToJsonCookie(base64Cookie):
    encode_cookie = base64.b64decode(base64Cookie).decode('utf-8')
    cookies = []
    for cookie in encode_cookie.split('\n'):
        try:
            coookie = list(cookie.split('\t'))
            json_cookie = {'domain': coookie[0], 'expirationDate': coookie[4], 'hostOnly': coookie[1], 'httpOnly': coookie[3],
                    'name': coookie[5].replace('\\', '\\\\').replace('"', '\\"'), 'path': coookie[2],
                    'value': coookie[6].replace('\\', '\\\\').replace('"', '\\"')}
            cookies.append(json_cookie)
        except:
            pass
    return cookies

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to move element from one parent to another in magento 2.1 layout
I am trying to move minicart-wrapper into page-wrapper, right now it is in the parent(header). What i have done so far,

Path where i am over riding magento core module in my extended theme, my parent theme is luma:

Magento/app/design/frontend/classic/classic_theme/Magento_Checkout/layout/default.xml
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <move element="minicart.wrapper" destination="page.header" after="-"/>
    </body>
</page>

Path of the default module that i am over riding in my theme:
  Magento/vendor/magento/module-checkout/view/frontend/layout/default.xml

I am following this (Rearrange elements)
http://devdocs.magento.com/guides/v2.0/frontend-dev-guide/layouts/xml-manage.html
I am confused how if they are referring to element by class or something else. I am doing it using class in my code.
Please help!!! Thanks in advance.

A: check

../app/code/Magento/Checkout/view/frontend/layout/default.xml

here you find:
<block class="Magento\Checkout\Block\Cart\Sidebar" name="minicart" as="minicart" after="logo" template="cart/minicart.phtml">

I suspect this is the element you want to move.
To find the element you want it to move to check:

../app/code/Magento/Checkout/view/frontend/page_layout/checkout.xml

Here you will find the element:
<layout xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_layout.xsd">
    <update handle="empty"/>
    <referenceContainer name="page.wrapper">
        <container name="checkout.header.container" as="checkout_header_container" label="Checkout Page Header Container" htmlTag="header" htmlClass="page-header" before="main.content">
            <container name="checkout.header.wrapper" label="Checkout Page Header" as="checkout_header_wrapper" htmlTag="div" htmlClass="header content"/>
        </container>
    </referenceContainer>
</layout>

So you should be able to change it like:
<?xml version="1.0"?>
<!--
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <move element="minicart" destination="checkout.header.container" />
    </body>
</page>

How I found the elements generally speaking:
You can enable layout hints in the admin backend. But I never found this useful so far.
So typically I just search in my IDE over all of the magento source code for some unique element like ie. a html class name or similar. You will then often find the code either in a layout xml, phtml or html.
If you found it in xml it should be simple to see the name of the element where the htmlClass is set.
If it's in an html or phtml file you need to search this file name in the layout(.xml) instruction files so you can find at what element it is attached. That gives you the element name then you can use for further actions.
To finally see if I got the right element I add a remove instruction into the appropriate layout file.


text:
Q: After mounting using sshfs I cannot commit my changes using subversion local machine:
    Fedora 13
    Subversion: 1.6.9
remote machine:
CentSO 5.3
subversion 1.4.2

I have a project which is on the remote machine:
remote@x.x.x.x:projects/ssd1

I have mounted this on my local machine:
sshfs remote@x.x.x.x:projects/ssd1 /home/jbloggs/projects/mnt/ssd1

Everything mounts ok. So I open my project using GNU Emacs 23.2.1. When I want to comment my changes in emacs I get the following error:
can't move /home/jbloggs/projects/mnt/ssd1/.svn/tmp/entries to /home/jbloggs/mnt/ssd1/.svn/entries: Operation not permitted

Does anyone know of any way I can resolve this issue?
many thanks for any advice,

A: I think the issue is with sshfs, rather than Subversion. The short answer is: try the "rename workaround" option:
 sshfs -o workaround=rename ...

If that doesn't help see if you can rename the file manually using the Linux mv command (not the SVN one). If not, can you rename it using SFTP (ie. without using sshfs)? See http://www.mail-archive.com/macfuse-devel@googlegroups.com/msg00559.html for a more detailed discussion.

A: I think what may be going on here is that you checked out the working copy on the remote machine, and it checked out to one path, but on the mounted drive, you're working under a different path.
How different are the two paths on the local and remote machine? Would it be possible for you to make the paths identical?
I would unmount the drive, remount it with the exact same path as the path on the remote machine, do an svn cleanup, and try to commit then.

A: Why you are mounting the project path from the remote machine? Wouldn't it be easier to checkout a working copy on the local machine?


text:
Q: Unable to decode Custom object at Avro Consumer end in Kafka I have a concrete class which I am Serializing in Byte array to be sent to a Kafka topic.
For serializing I am using ReflectDatumWriter .
Before sending the bytes[] I am putting schema ID in first 4 bytes with schema ID after checking some online tutorial.
I am able to send the message but while consuming it in Avro console consumer I am getting response as :

./bin/kafka-avro-console-consumer --bootstrap-server 0:9092 --property
  schema.stry.url=http://0:8081 --property print.key=true --topic Test

"1" "\u0000"
"1" "\u0000"
"1" "\u0000"
"1" "\u0000"
"1" "\u0000"
"1" "\u0000"
"1" "\u0000"
"1" "\u0000"
"1" "\u0000"
"1" "\u0000"

    MParams ddb = new MParams();
    ddb.setKey("ss");

    for (int i = 0; i < 10; i++) {
        ProducerRecord record = new ProducerRecord<String, byte[]>("Test", "1", build(1, Producer.serialize(ddb)));
        Future resp = kafkaFullAckProducer.send(record);

        System.out.println("Success" + resp.get());
    }
}

public static <T> byte[] serialize(T data) {
    Schema schema = null;
    if (data == null) {
        throw new RuntimeException("Data cannot be null in AvroByteSerializer");
    }
    try {
        schema = ReflectData.get().getSchema(data.getClass());
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DatumWriter<T> writer = new ReflectDatumWriter<T>(schema);
        writer.write(data, new EncoderFactory().directBinaryEncoder(out, null));
        byte[] bytes = out.toByteArray();
        return bytes;
    } catch (java.io.IOException e) {
        throw new RuntimeException("Error serializing Avro message", e);
    }
}

public static byte[] build(Integer schemaId, byte[] data) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    out.write(0);
    try {
        out.write(ByteBuffer.allocate(4).putInt(schemaId).array());
        out.write(data);
        byte[] bytes = out.toByteArray();
        out.close();
        return bytes;
    } catch (IOException e) {
        throw new RuntimeException("Exception in avro record builder , msg :" + e.getMessage());
    }

@Data
public class MParams extends MetricParams{

    // POJO version

    @Nullable
    private String key;

}

@JsonTypeInfo(use = Id.CLASS, include = As.PROPERTY, property = "@c")
@Union(value= {MParams.class})
public abstract class MetricParams {

}

Working Serializer snippet
public byte[] serialize(String topic, T record) {
        Schema schema;
        int id;
        try {
            schema = ReflectData.get().getSchema(record.getClass());
            id = client.register(topic + "-value", schema);
        } catch (IOException | RestClientException e) {
            throw new RuntimeException(e);
        }
        return serializeImpl(id, schema, record);
    }

    protected byte[] serializeImpl(int id, Schema schema, T object) throws SerializationException {
        if (object == null) {
            return null;
        }
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            out.write(0x0);
            out.write(ByteBuffer.allocate(4).putInt(id).array());

            BinaryEncoder encoder = EncoderFactory.get().directBinaryEncoder(out, null);
            DatumWriter<T> writer = new ReflectDatumWriter<T>(schema);
            writer.write(object, encoder);
            encoder.flush();
            byte[] bytes = out.toByteArray();
            out.close();
            return bytes;
        } catch (IOException | RuntimeException e) {
            throw new SerializationException("Error serializing Avro message", e);
        }
    }

Deserializer :
protected T deserialize(Schema schema, byte[] payload) throws SerializationException {
        // Even if the caller requests schema & version, if the payload is null
        // cannot include it. The caller must handle
        // this case.
        if (payload == null) {
            return null;
        }

        int id = -1;
        try {
            ByteBuffer buffer = getByteBuffer(payload);
            id = buffer.getInt();
            int length = buffer.limit() - 1 - 4;

            int start = buffer.position() + buffer.arrayOffset();
            DatumReader<T> reader = new ReflectDatumReader<T>(schema);
            T res = reader.read(null, new DecoderFactory().binaryDecoder(buffer.array(), start, length, null));
            return res;
        } catch (IOException | RuntimeException e) {
            throw new SerializationException("Error deserializing Avro message for id " + id, e);
        }
    }

    private ByteBuffer getByteBuffer(byte[] payload) {
        ByteBuffer buffer = ByteBuffer.wrap(payload);
        if (buffer.get() != 0x0) {
            throw new SerializationException("Unknown magic byte!");
        }
        return buffer;
    }

A:
For serializing I am using ReflectDatumWriter . Before sending the bytes[] I am putting schema ID in first 4 bytes with schema ID

Not clear why you are trying to bypass the KafkaAvroSerializer class's default behavior. (In your case, remove Schema.Parser from that example, and use your Reflect record type rather than GenericRecord)
You can put your concrete class as the second type of the producer and as long as it implements the base Avro classes, it should be serialized correctly (meaning ID computed correctly, not some number you create, and converted to bytes), registered to the registry, then sent to Kafka
Most importantly, the schema ID is not necessarily a 1 in the registry, and by putting that, the console consumer might be trying to deserialize your messages incorrectly, resulting in the wrong output
In other words, try
ProducerRecord<String, MParams> record = new ProducerRecord<>(...)


text:
Q: Is there a more JQuery-istic way to combine handlers than a switch statement? Is it better to have multiple handlers for button click events, or is it suitable to combine click handlers with a switch statement? This works in my code, but I was wondering, is there a cooler, more JQuery-istic way to do it?
<html>
    <button id="button1">Button 1</button>
    <button id="button2">Button 2</button>
    <button id="button3">Button 3</button>
</html>

Which is better, this?
$('button').click(function(){
    switch(this.id){
        case "button1":
            alert("Do what button 1 says");
            break;

        case "button2":
            alert("Do what button 2 says");
            break;

        case "button3":
            alert("Do what button 3 says");
            break;
    }
});

Or this,
$('#button1').click(function(){
    alert("Do what button 1 says")
});

$('#button2').click(function(){
    alert("Do what button 3 says")
});

$('#button3').click(function(){
    alert("Do what button 3 says")
});

...Or is there no difference?

A: It all depends on the event handler. If there is shared code between the handlers and only a small part is specific, it might be fine to distinguish between the buttons inside the handler.
If each button handler is totally different though, why put three unrelated functions into one?
You can also create a map of functions:
var handlers = {
    id1: function() {
        // ...
    },
    id2: function() {
        //...
    }
};

and simply call a function with handlers[this.id]().
In the end, you assign an even handler to each element one way or the other, so it's more a matter of how you want to structure your code (which is personal preference more or less).

A: Your first approach will look for button elements by button tag and it will attach click e event handler to all the button elements.
Second approach will find each button by there ids and also attach click event handler to each of the button elements.
So basically there is no difference.
If you want to optimize it then you on which can work with only one event handler.
$(document).on('click', 'button', function(){
    switch(this.id){
        case "button1":
            alert("Do what button 1 says");
            break;

        case "button2":
            alert("Do what button 2 says");
            break;

        case "button3":
            alert("Do what button 3 says");
            break;
    }
});

This way it will attach only one event handler on the document and look for button selector whenever click event is triggered.
Note that instead of document it is always better to attach event on any parent element container which will always be present on the page.
Reference - http://api.jquery.com/on/

A: With all things Javascript, maintainability and readability should factor in.  With that said, and with little else to go on, I'd always prefer the latter because you have already encouraged the code to focus on the function of each individual button... and in general with any UI, any given button will have a very specific purpose relative to another.

A: For your example, you could store all messages into an array and add a class .button to your buttons in addition to the id. The idea is to extract the id on click() and take the correct message from the array. Something like:
var alerts = ['Hello', 'There', 'World'],
    $buttons = $('.button');

$buttons.click(function(){
    var n = this.id.match(/\d+/); // Assuming that id is `buttonX`...
    alert(alerts[n-1]);
});

A: The main difference I see is that option 1 is going to bind a click event to every button on the page (which will probably end up with many empty events) and the second will only attach the events to the targeted buttons.
While I'm no stickler for javascript performance, I'd say the second option is more readable and will lend itself to less maintenance issues.
If the different buttons are performing nearly the same function, albeit with slightly different parameters, then perhaps a good alternative would be to use data- attributes on the button elements and have all buttons performing the same task use the same click event, which would pull the unique parameters off of the actual html element that was clicked.  Overly simplistic example:
html:
<button data-effect="slide" ...>slide</button>
<button data-effect="fade" ...>slide</button>

javascript:
$("button[data-effect]".click(function(){
    //do stuff
    var $this = $(this);
    $this.hide($this.attr("data-effect") || "blind")
});


text:
Q: Application crash with android 2.3 I use this code to turn off the wifi connection and data connection
public static class LowBatteryReceiver extends BroadcastReceiver{
        public void onReceive(Context context, Intent intent){
            wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            wifiManager.setWifiEnabled(false);
            wifi = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);

            try {
            ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            Class<?> conmanClass = Class.forName(conman.getClass().getName());
            Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
            iConnectivityManagerField.setAccessible(true);
            Object iConnectivityManager = iConnectivityManagerField.get(conman);
            Class<?> iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
            Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
            setMobileDataEnabledMethod.setAccessible(true);
            setMobileDataEnabledMethod.invoke(iConnectivityManager, false);

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

The class will be called in a method to work but this is not important.. I have a nexus 4 with android 4.3 and the code works. Also in android 4.0.3/4, 4.1, 4.1.2, 4.2.1 and .4.2.2.. I use an ActionbarSherlock library so i can use an holo.light anctionbar also with previews android versions. A friend of mine with android 2.3.6 tryied the application and tells me has a crash.. I can't see any logcat for now but i think the problem is the code above. I know that with android 2.3 there was another way to turn the 3g off but i don't know which. How can i detect the android version and make something like : If android >= 4 use the code i posted and if android <=4 use another code (if someone can tell me which is is better thanks).
EDIT:
I found a code for data with android 2.3.. Have i to do something like
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
Method dataConnSwitchmethod;
Class telephonyManagerClass;
Object ITelephonyStub;
Class ITelephonyClass;

TelephonyManager telephonyManager = (TelephonyManager) context
        .getSystemService(Context.TELEPHONY_SERVICE);

if(telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED){
    isEnabled = true;
}else{
    isEnabled = false;
}

telephonyManagerClass = Class.forName(telephonyManager.getClass().getName());
Method getITelephonyMethod = telephonyManagerClass.getDeclaredMethod("getITelephony");
getITelephonyMethod.setAccessible(true);
ITelephonyStub = getITelephonyMethod.invoke(telephonyManager);
ITelephonyClass = Class.forName(ITelephonyStub.getClass().getName());

if (isEnabled) {
    dataConnSwitchmethod = ITelephonyClass
            .getDeclaredMethod("disableDataConnectivity");
} else {
    dataConnSwitchmethod = ITelephonyClass
            .getDeclaredMethod("enableDataConnectivity");
}
dataConnSwitchmethod.setAccessible(true);
dataConnSwitchmethod.invoke(ITelephonyStub);
}

so if the version is >= gingerbread this will be the code right?

A: Example how to use it:
 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
 // only for gingerbread and newer versions
}

Also you can check as below for the version 4>= or <=4 android.
 if(Build.VERSION.SDK_INT >= 4.0){
        //this code will be executed on devices running on DONUT (NOT ICS) or later
 }
since constant 4 represents donut: public static final int DONUT = 4;

You can find out the Android version looking at Build.VERSION.


text:
Q: statfs showing same output for all pathname Can any one please find out the problem  in this code.
Problem is its showing same output for all pathnames ,even though they have different contents,different files.
#include<stdio.h>
#include<sys/stat.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/vfs.h>
int main(int argc,char *argv[])
{
    struct statfs sb;
    if((statfs(argv[1],&sb))==0)
    {
            printf("optimal transfer blk size is %d\n",sb.f_bsize);
            printf("total data blocks are %d\n",sb.f_blocks);
            printf("free blocks in fs are %d\n",sb.f_bfree);
            printf("total file nodes in fs are %d\n",sb.f_files);
            printf("free file nodes in fs are %d\n",sb.f_ffree);
    }
}

[testuser@hdchshocms6344 ex4]$ ./a.out /home/testuser
optimal transfer blk size is 4096
total data blocks are 8819390
free blocks in fs are 6771045
total file nodes in fs are 2240224
free file nodes in fs are 1927385

[testuser@hdchshocms6344 ex4]$ ./a.out /home/testuser/harish
optimal transfer blk size is 4096
total data blocks are 8819390
free blocks in fs are 6771034
total file nodes in fs are 2240224
free file nodes in fs are 1927386

Thanks in advance.

A: statfs gives information for mounted filesystems, not directories. Unless /home/testuser/harish is a different filesystem altogether (i.e. you have mounted a partition at that location), it is expected and normal that you get the exact same information as for /home/testuser.


text:
Q: Program stuck at ProgressDialog I'm using Android Studio and Firebase. The code is not creating the new user when I run emulator. The program gets stuck at progressDialog "Registering please wait". I can manually add users in Firebase. I've enabled the email/password auth in Firebase console but still prob exists
This is MainActivity.java file.
package com.example.application.firebaseauthdemo;

import android.app.ProgressDialog;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    //defining view objects
    private EditText editTextEmail;
    private EditText editTextPassword;
    private Button buttonSignup;
    private ProgressDialog progressDialog;

    //defining firebaseauth object
    private FirebaseAuth firebaseAuth;

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

        //initializing firebase auth object
        firebaseAuth = FirebaseAuth.getInstance();

        //initializing views
        editTextEmail = (EditText) findViewById(R.id.editTextEmail);
        editTextPassword = (EditText) findViewById(R.id.editTextPassword);

        buttonSignup = (Button) findViewById(R.id.buttonSignup);

        progressDialog = new ProgressDialog(this);

        //attaching listener to button
        buttonSignup.setOnClickListener(this);
    }

    private void registerUser(){

        //getting email and password from edit texts
        String email = editTextEmail.getText().toString().trim();
        String password  = editTextPassword.getText().toString().trim();

        //checking if email and passwords are empty
        if(TextUtils.isEmpty(email)){
            Toast.makeText(this,"Please enter email",Toast.LENGTH_LONG).show();
            return;
        }

        if(TextUtils.isEmpty(password)){
            Toast.makeText(this,"Please enter password",Toast.LENGTH_LONG).show();
            return;
        }

        //if the email and password are not empty
        //displaying a progress dialog

        progressDialog.setMessage("Registering Please Wait...");
        progressDialog.show();

        //creating a new user
        firebaseAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        //checking if success
                        if(task.isSuccessful()){
                            //display some message here
                            FirebaseUser user = firebaseAuth.getCurrentUser();
                            Toast.makeText(MainActivity.this,"Successfully registered",Toast.LENGTH_LONG).show();
                        }else{
                            //display some message here
                            Toast.makeText(MainActivity.this,"Registration Error",Toast.LENGTH_LONG).show();
                        }
                        progressDialog.dismiss();
                    }
                });

    }

    @Override
    public void onClick(View view) {
        //calling register method on click
        registerUser();
    }
}

(2) Project(build.gradle) file..I've already added classpath.
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.google.gms:google-services:3.1.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com" // Google's Maven repository
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

(3)  App(build.gradle) file...Here,I've added all the firebase dependencies.
apply plugin: 'com.android.application'

android
        {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig
            {
        applicationId "com.example.application.firebaseauthdemo"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support:animated-vector-drawable:26.1.0'
    compile 'com.android.support:mediarouter-v7:26.1.0'
    compile 'com.google.android.gms:play-services:11.0.4'

    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.firebase:firebase-auth:11.0.4'
    compile 'com.google.firebase:firebase-core:11.0.4'
    compile 'com.google.firebase:firebase-crash:11.0.4'
    compile 'com.google.firebase:firebase-messaging:11.0.4'
    compile 'com.google.android.gms:play-services-maps:11.0.4'
    compile 'com.google.android.gms:play-services-location:11.0.4'
    testCompile 'junit:junit:4.12'

}
apply plugin: 'com.google.gms.google-services'

I've added all the required dependencies. Plus, added the same classpath as it was in Firebase. Also, I cleaned the project and rebuild it. But still the problem can't be solved. Also,I've enabled the Email/Password Authentication in the Firebase console. Still the app keeps on getting stuck at the progressDialog and users can't be registered in the Firebase auth.

A: You should create AsyncTask for loaded work.
For Example:
AsyncTask<String, String, String> asyncTask = new AsyncTask() {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                progressDialog.setMessage("Registering Please Wait...");
                progressDialog.show();
            }

            @Override
            protected Object doInBackground(Object[] params) {
                firebaseAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        //checking if success
                        if(task.isSuccessful()){
                            //display some message here
                            FirebaseUser user = firebaseAuth.getCurrentUser();
                            Toast.makeText(MainActivity.this,"Successfully registered",Toast.LENGTH_LONG).show();
                        }else{
                            //display some message here
                            Toast.makeText(MainActivity.this,"Registration Error",Toast.LENGTH_LONG).show();
                        }

                    }
                });
                return null;
            }

            @Override
            protected void onPostExecute(Object o) {
                super.onPostExecute(o);
                progressDialog.dismiss();
            }
        };
        asyncTask.execute();

A: You should add an addOnFailureListener to check what is failing, because the addOnCompleteListener is never called.
//creating a new user
    firebaseAuth.createUserWithEmailAndPassword(email, password)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    // YOUR CODE
                }
            })
            .addOnFailureListener(this, new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });


text:
Q: Alternating Background Color react-data-table-component i need to alternating the background color of react-data-table-component
this my style
const customStyles = {
            rows: {
              style: {
                border: 'none', // override the row height
                backgroundColor: ["#FFDDDD", "#FFF4F4"],// this the color
                borderRadius:8,
                marginTop:8
              }
            },
            headCells: {
              style: {
                backgroundColor: "#FFF4F4",
                border: 'none',
                borderRadius:8,
              },
            },
            cells: {
              style: {
                paddingLeft: '8px', // override the cell padding for data cells
                paddingRight: '8px',
                border: 'none'
              },
            },
          };

how can this style work to my react-data-table-component


text:
Q: C++ pthread_create Parameter I was previously using a void* function as the third parameter of pthread_create, and here is what it looked like:
void* nameChange(void*){ ... }
...
pthread_t id;
pthread_create(&id, NULL, nameChange, NULL);

This worked. But I have made some changes to my code and need the function nameChange to be a member of my class MainWindow. Here's the only difference now:
void* MainWindow::nameChange(void*)

Now, I get an error when putting nameChange as the parameter. Here's what it says:
error: cannot convert 'MainWindow::nameChange' from type 'void* (MainWindow::)(void*)' to type 'void* (*)(void*)'
What is it that I am doing wrong here? I'm pretty new to threads, so any help is appreciated!

A: The difference between a C function and a C++ member function is that C function uses cdecl calling convention, while member functions uses thiscall calling convention. You can't call the member function directly. Member function pointers are not the same type as function pointers.
Maybe here is one workaround
void* callback(void*)
{
    MainWindow instance;
    instance.nameChange();
}

pthread_create(&id, NULL, callback, NULL);


text:
Q: Javascript gets only the first id from a foreach loop. Why? I use a foreach loop to get some tabs with different id's. This way I get tabs with ids tab1, tab2, tab3, etc. Than, when I want to get the id of each tab using javascript, it returns only the id of the first tab and uses this for all tabs. It does not loop as php do. Why?
<?php
foreach ($DB_con->query($foos) as $foo) {
    ?>
    <div id='tab<?php echo $counter_foo; ?>'>

<?php echo $counter_foo; ?>

    <?php
}
?>

A: Change the id in your HTML to class, and use getElementsByClassName instead of getElementById your in JavaScript.
Your div:

and your JS..
var dividvalue = document.getElementsByClassName('divid')[0].innerHTML;

Also consider changing divid to divclass for consistency's sake.
Full edited code:

<?php
foreach ($DB_con->query($foos) as $foo) {
    ?>
    <div id='tab<?php echo $counter_foo; ?>'>

<?php echo $counter_foo; ?>

    <?php
}
?>


text:
Q: Monoid actions - is this action inelegant? I'm recently delving into abstract algebra, and I've attempted to devise a monoid action on the natural numbers. I think I must be missing something here—is there a better way to represent these same operations as an algebra?
I've defined a transformation monoid of $\mathbb{N}$ such that the elements are the nth-prime function $p$, the "curried" multiply-by-$k$ function for all $k \in \mathbb{N}$ (which includes the identity as $k=1$), and all compositions of these. So the basis is $(n \mapsto p_n, n \mapsto n, n \mapsto 2n, n \mapsto 3n, \ldots)$. The monoid operation is function composition.
Including each separate multiply-by-$k$ function seems like a mistake, or at least inelegant—especially if I let the natural numbers also be a multiplicative monoid $(\mathbb{N}, \times)$. It seems like a redundancy.
Is there a better way to represent this? What am I missing?

A: If I understand correctly, you are defining a submonoid $T$ of the monoid $T_{\Bbb N}$ of all transformations on $\Bbb N$. Your monoid $T$ is generated by the transformation $\pi: n \to p_n$ and by the transformations $\rho_k: n \to kn$, for all $k > 0$. It turns out that the set $M = \{\rho_k \mid k > 0\}$ is closed under composition and hence forms a submonoid of $T_{\Bbb N}$, namely the monoid of all non-zero translations of $(\Bbb N, \times)$. Note that $M$ is generated by the set $P = \{\rho_p \mid \text{$p$ is prime}\}$ and is actually the free commutative monoid of base $P$. I guess that is what you mean when you talk about the redundancy of $M$.
Describing $T$ is more complicated, since it involves the powers of $\pi$. But as the submonoid $N$ of $T$ generated by $\pi$ is free and isomorphic to $({\Bbb N}, 0, +)$, I would guess that $T$ is isomorphic to the free product of $N$ and $M$.


text:
Q: Window.open() could not open new webpage? Window.open() could not open new webpage?
Is it because of my JavaScript, or there is there a problem anywhere else in my code?

function getage() {
  var age = document.getElementById("customerage").value;

  if (age > 21) {
    window.open = "beer.com";
  } else if (age > 0) {
    window.open = "http://lol.disney.com/games/tsum-tsum-tower";
  } else
    alert("Please input correct age!");
}

  <title>I drink alcohol.com</title>
  <meta charset="utf-8">
  <meta name="Sumei" content="Alcohol Web">

Welcom to "I drink alcohol.com"

Here is couple of questions for you:

How old are you?

  <form method="post">
    <input type="number" name="customerage" id="customerage" />
    <input type="submit" onclick="getage()" value="OK">
  </form>

A: If i understand correctly you want to go to pages based on iteration result
well try this piece of code, also you are not using window.open() correctly that should be used like window.open(URL, "_blank", option); if you want it to open in new tab
else go for code below
if(age>21)
{
window.location="beer.com";
}

else if(age>0)
              {window.location="http://lol.disney.com/games/tsum-tsum-tower";}
              else
              alert("Please input correct age!");
          }

well also what i think you should add something in your elseif like
else if(age>0 && age <21)

A: just use window.open
var option= "location=yes,height=570,width=520,scrollbars=yes,status=yes";
var link = URL + location.href;
var win = window.open(link, "_blank", option);

A: use window.open() to open in new tab, and use window.location.href to open link in same tab

              <title>I drink alcohol.com</title>
              <meta charset="utf-8">
              <meta name="Sumei" content="Alcohol Web">
            `

Welcom to "I drink alcohol.com"

Here is couple of questions for you:

How old are you?

             <form method="post">
             <input type="number" name="customerage" id="customerage"/>
             <input type="submit" onclick="getage()" value="OK">
             </form>


text:
Q: extract images from pdf with php I'm trying to extract images from PDF with PHP.
I have succeeded partially - I have a gray scale image...

...and I know that I have to apply a formula on it to get colors!
But first, I need to convert binary data of the image to numbers, and then apply the formula from the Adobe PDF specs.
So basically, suppose you have the attached image (with all of the data from the PDF, no modification) and it's
1. CYMK image
2. 8 bit for each component

and you need to convert it to a colored image with PHP using attached the Adobe spec, under the "Image" section.
What can I do to solve that?

A: You can use pdfimages.
The package gets installed when you install xpdf. The manpage describes:

  Pdfimages saves images from a Portable Document Format  (PDF)  file  as Portable Pixmap (PPM), Portable Bitmap (PBM), or JPEG files.

  Pdfimages  reads  the  PDF file, scans one or more pages, PDF-file, and writes one PPM, PBM, or JPEG file for each  image,  image-root-nnn.xxx, where  nnn  is  the image number and xxx is the image type (.ppm, .pbm, .jpg).

  NB: pdfimages extracts the raw image data from the  PDF  file,  without performing  any  additional  transforms.  Any rotation, clipping, color inversion, etc. done by the PDF content stream is ignored.

A: The image you are showing is not grayscale, it is just inverted. Try to invert color bytes and you'll end up with good colors. There is a fuss about CMYK color storage in JPEG images caused by  Photoshop storing 100% colors as 0x0.
edit : how to invert in PHP, taken from this blogpost It is working on rgb data and must be adapted to work with CMYK
<?php
function image_filter_invert(&$image){
    $width = imagesx($image);
    $height = imagesy($image);
    for($x = 0; $x < $width; $x++){
        for($y = 0; $y < $height; $y++){
            $rgb = imagecolorat($image, $x, $y);
            $r = 0xFF-(($rgb>>16)&0xFF);
            $g = 0xFF-(($rgb>>8)&0xFF);
            $b = 0xFF-($rgb&0xFF);
            $color = imagecolorallocate($image, $r, $g, $b);
            imagesetpixel($image, $x, $y, $color);
        }
    }
}

?>


text:
Q: Select distinct in two column but group by one I need to select from the database results for make a menu as in example:
http://it.tinypic.com/r/2f092pv/8
Record sql example:
Field-------Product ----Macrocategories---Microcategories--Price----
Value-------Nvidia------ Hardware ----- Graphic Cards ---- 399$ -----
I tried this:
$select_MENU = "select distinct macrocategories, microcategories from catalog";

        $result_MENU = mysql_query($select_MENU);

if ($result_MENU)
        while($dati = mysql_fetch_assoc($result_MENU))
        {
        echo "
$dati[macrocategories]

$dati[microcategories]

";

        }
        ?>

The result: 1
Macrocategories for each result of microcategories
Help me please...

A: There are a couple oddities in your HTML in general:
// You will want to switch to PDO or mysqli prepared statements for security and deprecated reasons
// Distinct will only select unique instances in your table
$select_MENU = "select distinct macrocategories, microcategories from catalog";
$result_MENU = mysql_query($select_MENU); ?>

<?php
if($result_MENU) {
        while($dati = mysql_fetch_assoc($result_MENU)) { ?>

<?php echo $dati['macrocategories']; ?>

<a href="index.php?microcategories=<?php echo $dati['microcategories']; ?>"><?php echo $dati['microcategories']; ?>
<?php
            }
    } ?>


text:
Q: I want to change the string to datetime but it says OutOfBoundsDatetime I want to change the string to datetime but it says 'OutOfBoundsDatetime: Out of bounds nanosecond timestamp: 1010-08-28 00:00:00' and in my dataframe doesn't has '1010-08-28' data, It works to other columns but not this column. How can I fix this?

A: I'm not sure what you're using to convert your date, but I've found dateutil.parser to work really good for all formats.
from dateutil.parser import parse

newDate = parse("1010-08-28")
print(newDate)

Then you can easily manipulate the date variable with the datetime module to use as needed.


text:
Q: find method in mongoDB does not filter results I have a method from which I am retrieving data from database like this.
const popularBookGenreDB = async (genre) => {
try {
    //Remaining to filters books by genre available
    console.log("{ genres: genre }", { "genres": genre });
    const enw = await Books.find({ genres: genre }).sort({ bbeScore: -1 }).limit(2)
    return enw;
} catch (error) {
    throw error;
}};

It supposed to filter the results by looking if specific genre is in genres list of element but it only returns the items ranked by bbeScore. it does not take into account the genres list at all.
When I run same query {genres : "Romance"} on MongoDB Atlas find search field it works as expected. but when I try to run it on node server it does not take into account the genres list.
I have document as.
{
        "_id": "62b77562076177189c8f53af",
        "title": "The Hunger Games",
        "series": "The Hunger Games #1",
        "author": [
            "Suzanne Collins"
        ],
        "rating": 4.33,
        "description": "WINNING MEANS FAME AND FORTUNE.LOSING MEANS CERTAIN DEATH.THE HUNGER GAMES HAVE BEGUN. . . .In the ruins of a place once known as North America lies the nation of Panem, a shining Capitol surrounded by twelve outlying districts. The Capitol is harsh and cruel and keeps the districts in line by forcing them all to send one boy and once girl between the ages of twelve and eighteen to participate in the annual Hunger Games, a fight to the death on live TV.Sixteen-year-old Katniss Everdeen regards it as a death sentence when she steps forward to take her sister's place in the Games. But Katniss has been close to dead before—and survival, for her, is second nature. Without really meaning to, she becomes a contender. But if she is to win, she will have to start making choices that weight survival against humanity and life against love.",
        "language": "English",
        "isbn": "9780439023481",
        "genres": [
            "Young Adult",
            "Fiction",
            "Dystopia",
            "Fantasy",
            "Science Fiction",
            "Romance",
            "Adventure",
            "Teen",
            "Post Apocalyptic",
            "Action"
        ],
        "characters": [
            "Katniss Everdeen",
            "Peeta Mellark",
            "Cato (Hunger Games)",
            "Primrose Everdeen",
            "Gale Hawthorne",
            "Effie Trinket",
            "Haymitch Abernathy",
            "Cinna",
            "President Coriolanus Snow",
            "Rue",
            "Flavius",
            "Lavinia (Hunger Games)",
            "Marvel",
            "Glimmer",
            "Clove",
            "Foxface",
            "Thresh",
            "Greasy Sae",
            "Madge Undersee",
            "Caesar Flickerman",
            "Claudius Templesmith",
            "Octavia (Hunger Games)",
            "Portia (hunger Games)"
        ],
        "bookFormat": "Hardcover",
        "edition": "First Edition",
        "pages": 374,
        "publisher": "Scholastic Press",
        "publishDate": "09/14/08",
        "firstPublishDate": "",
        "awards": [
            "Locus Award Nominee for Best Young Adult Book (2009)",
            "Georgia Peach Book Award (2009)",
            "Buxtehuder Bulle (2009)",
            "Golden Duck Award for Young Adult (Hal Clement Award) (2009)",
            "Grand Prix de l'Imaginaire Nominee for Roman jeunesse étranger (2010)",
            "Books I Loved Best Yearly (BILBY) Awards for Older Readers (2012)",
            "West Australian Young Readers' Book Award (WAYRBA) for Older Readers (2010)",
            "Red House Children's Book Award for Older Readers & Overall (2010)",
            "South Carolina Book Award for Junior and Young Adult Book (2011)",
            "Charlotte Award (2010)",
            "Colorado Blue Spruce Young Adult Book Award (2010)",
            "Teen Buckeye Book Award (2009)",
            "Pennsylvania Young Readers' Choice Award for Young Adults (2010)",
            "Rhode Island Teen Book Award (2010)",
            "Dorothy Canfield Fisher Children's Book Award (2010)",
            "Evergreen Teen Book Award (2011)",
            "Soaring Eagle Book Award (2009)",
            "Milwaukee County Teen Book Award Nominee (2010)",
            "Sakura Medal for Middle School Book (2010)",
            "Michigan Library Association Thumbs Up! Award (2009)",
            "Florida Teens Read (2009)",
            "Deutscher Jugendliteraturpreis for Preis der Jugendjury (2010)",
            "Iowa High School Book Award (2011)",
            "New Mexico Land of Enchantment Award for Young Adult (2011)",
            "Eliot Rosewater Indiana High School Book Award (2010)",
            "The Inky Awards for Silver Inky (2009)",
            "California Young Readers Medal for Young Adult (2011)",
            "Lincoln Award (2011)",
            "Kinderboekwinkelprijs (2010)",
            "Missouri Truman Readers Award (2011)",
            "CYBILS Award for Young Adult Fantasy & Science Fiction (2008)",
            "Literaturpreis der Jury der jungen Leser for Jugendbuch (2010)",
            "The Inky Awards Shortlist for Silver Inky (2009)",
            "Prix Et-lisez-moi (2011)",
            "Missouri Gateway Readers Award (2011)",
            "Oklahoma Sequoyah Award for High School and Intermediate (2011)",
            "Premio El Templo de las Mil Puertas for Mejor novela extranjera perteneciente a saga (2009)",
            "Rebecca Caudill Young Readers' Book Award (2011)",
            "LovelyBooks Leserpreis for Fantasy (2009)",
            "LovelyBooks Leserpreis for Bestes Cover/Umschlag (2009)",
            "Premi Protagonista Jove for Categoria 13-14 anys (2010)"
        ],
        "numRating": 6376780,
        "ratingByStars": [
            "3444695",
            "1921313",
            "745221",
            "171994",
            "93557"
        ],
        "likedPercent": 0,
        "setting": [
            "District 1",
            "anem",
            "Capito",
            "anem",
            "Panem (United States)"
        ],
        "coverImg": "https://i.gr-assets.com/images/S/compressed.photo.goodreads.com/books/1586722975l/2767052.jpg",
        "bbeScore": 2993816,
        "bbeVotes": 30516,
        "price": 5.09
    },

Expected Result that I would get document that would contain genre item in (eg. 'Romance') document and no others.
example :
Expected :
 [
    {title : "Hunger games" , ... , genres : [... , "Romance"...]}
    {title : "Pride and Prejudice" , ... , genres : [... , "Romance"...]}
  ]

Returned Output
 [
    {title : "Hunger games" , ... , genres : [... , "Romance"...]}
    {title : "HarryPotter" , ... , genres : [......]} // No "Romance" in genres list
  ]

Routes.js file
    // router.route("/books").get(searchBooks)
router.route("/books/popular/:genre").get(PopularBookGenre)
// router.route("/books/popular").get(popularBooks)
router.route("books/autocomplete").get(autoCompleteBooks)

If this doesn't work How can I use aggregatePipeline to solve this problem. Again the query works in mongoDB online find search field for collection but not with node.

A: use $all operator to find documents , in which array contains specific value
const popularBookGenreDB = async (genre) => {
    try {
        const enw = await Books.find({'genres': {'$all':[genre]} })
        .sort({ bbeScore: -1 })
        .limit(2);

        return enw;
    } catch (error) {
        throw error;
    }};


text:
Q: jQuery: onclick, edit field and show+save into an variable Right now I have this in Javascript without jQuery:
Here is it: http://jsbin.com/ewihu3
It's working just fine, but I wish to use jQuery for making the code simpler and shorter.
I want exactly same things to do as on the example above, that when you click on the text, it should turn into an input field. And on blur it should display what you've edited in the box, and then make a variable (like e.value on the example above) so I can send that in a ajax call later.
How can i do this in jQuery?

A: You can use the jEditable plugin
Or you can start something similar pretty simply by yourself too, with something like this:
$('span.editable').click(function() {
   var input = $('<input type="text" />', {
      value: $(this).text()
   }).click(function() {
      $.get('editsave.php?tekstny=' + $(this).value(), function(response) {
         var span = $('span', {
            text: response
         });
         $(this).replaceWith(span);
      });
   });
   $(this).replaceWith(input);
});

A: Editable header or Button by clicking on edit button, type your own text and click on Ok to replace your text.

function editable() {
  var h1 = document.getElementsByTagName("H1")[0];
  var att = document.createAttribute("contenteditable");
  att.value = "true";
  h1.setAttributeNode(att);
}

function noteditable() {
  var h1 = document.getElementsByTagName("H1")[0];
  var att = document.createAttribute("contenteditable");
  att.value = "flase";
  h1.setAttributeNode(att);
}

function editable2() {
  var input = document.getElementsByTagName("input")[0];
  var att = document.createAttribute("type");
  att.value = "text";
  input.setAttributeNode(att);
}

function noteditable2() {
  var input = document.getElementsByTagName("input")[0];
  var att = document.createAttribute("type");
  att.value = "button";
  input.setAttributeNode(att);
}
$('.my-button').click(function() {
  $(".my-textbox").focus()
});
$('.my-button2').click(function() {
  $(".button").focus()
});
body {
  text-align: center;
}

Hello World

<button class='my-button' onclick="editable()">Edit</button>
<button onclick="noteditable()">OK</button>

<input type="button" class="button" value="Hello World" />

<button class='my-button2' onclick="editable2()">Edit</button>
<button onclick="noteditable2()">OK</button>


text:
Q: Retrieve ID of JSON when POST in Firebase, Android I POST a JSON into my Firebase Database, using okHttp. Then I retrieve a response and I do:
response.body().string();

But when I print this, instead of a JSON I get:
/**/ gotData({"name":"my_object_ID"});

I want to extract the JSON inside of that String.


text:
Q: how to convert one expression to another I equated them to each other, and they were equal, but .. how to make another from one

A: The standard tricks to "deradicalize" are:
1) If you have $\sqrt a$ by itself in the denominator, such as $\frac M{\sqrt a}$, then multiply top and bottom by $\sqrt{a}$ to get $\frac {M\sqrt{a}}{\sqrt a\sqrt a}=\frac {M\sqrt{a}}{a}$
1b) If you have $m\sqrt a$ in the denominator, you can multiply top and bottom by $\sqrt a$ (the $m$ isn't relevant) to get $\frac {M}{m\sqrt a}=\frac {M\sqrt a}{ma}$.
2) If you have $\sqrt a$ as part of a sum (or difference) in the denominator, such as $\frac M{\sqrt a \pm k}$ then multiply by the complement[1] of the denominator, that is:
$\frac M{\sqrt a \pm k}=\frac {M(\sqrt a \mp k)}{(\sqrt a \pm k)(\sqrt a \mp k)} =\frac {M(\sqrt a \mp k)}{a - k^2}$
2a) If you have a $\sqrt a \pm \sqrt b$, two radicals, in a sum on the denominator, you can multiply by the complement in the same way.
$\frac M{\sqrt a \pm \sqrt b} = \frac {M(\sqrt a \mp \sqrt b)}{(\sqrt a \pm \sqrt b)(\sqrt a \mp \sqrt b)}=\frac {M(\sqrt a \mp \sqrt b)}{a-b}$.
(This assumes, of course that $a \ne b$.  But if $a = b$ we'd have $\frac M{\sqrt a + \sqrt b} =\frac M{\sqrt a + \sqrt a} =\frac M{2\sqrt a}$ in which case you do 1b.)
2b) If you have $m\sqrt a \pm mk$ or $m\sqrt a \pm m\sqrt b$ in the denominator you can factor the $m$ out multiply top and bottom by the complement of $\sqrt a\pm k$ or $\sqrt a \pm \sqrt b$ which is $\sqrt a\mp k$ or $\sqrt a\mp \sqrt b$ and do as above.
2c) If you have $m\sqrt a \pm nk$ and $m,n$ have a common factor $d$ you can factor the $d$ out and ... do as above.
====
So you have in the denominator $\sqrt 3y + 2y$.  You can do 2b).
Factor out the $y$ to get $y(\sqrt 3 + 2)$ and mulitply top and bottom by the complement; $\sqrt 3 - 2$.
$\frac {\sqrt 3y + x-2y}{\sqrt 3y +  2y}=\frac {(\sqrt 3y + x-2y)(\sqrt 3-  2)}{y(\sqrt 3 +  2)(\sqrt 3-  2)}=\frac {(\sqrt 3-  2)(\sqrt 3y + x-2y)}{y(3 -4)}=\frac {(\sqrt 3-  2)(\sqrt 3y + x-2y)}{-y}=-\frac {(\sqrt 3-  2)(\sqrt 3y + x-2y)}{y}$
=======
[1]  The complement of a sum $m \pm n$ is $m \mp n$.  By multiplying together the sum and the difference:  $(m+n)(m-n)= m\cdot m -m\cdot n + n\cdot m - n\cdot n = m^2 - n^2$ we get a "neat" difference between two squares and all the "middle stuff" cancels out.
If one, or both, of the terms is a radical that the radical is squared and ... isn't a radical any more:
$(\sqrt a + \sqrt b)(\sqrt a - \sqrt b) = \sqrt a\sqrt a -\sqrt a\sqrt b +\sqrt a\sqrt b -\sqrt b\sqrt b = \sqrt a^2 -\sqrt b^2 = a-b$.

A: $$\frac{\sqrt3y+2x-2y}{\sqrt3y+2y} = \frac{\sqrt3y+2x-2y}{y\left(\sqrt3+2\right)}\left(\frac{\sqrt3-2}{\sqrt3-2}\right) = \frac{\left(\sqrt3y+2x-2y\right)\left(\sqrt3-2\right)}{-y}$$


text:
Q: System blows up when trying to optimise vehicle movement using control package I am attempting to optimise the movement of a vehicle from position A to position B. I have tried copying the code from the documentation, but it does not work when I paste it.
This is my code so far:
import numpy as np
import control as ct
import control.optimal as opt
import matplotlib.pyplot as plt

def vehicle_update(t, x, u, params):
    # Get the parameters for the model
    l = params.get('wheelbase', 3.)         # vehicle wheelbase (m)
    phimax = params.get('maxsteer', 0.5)    # max steering angle (rad)

    # Saturate the steering input
    phi = np.clip(u[1], -phimax, phimax)

    # Return the derivative of the state
    return np.array([
        np.cos(x[2]) * u[0],            # xdot = cos(theta) v
        np.sin(x[2]) * u[0],            # ydot = sin(theta) v
        (u[0] / l) * np.tan(phi)        # thdot = v/l tan(phi)
    ])

def vehicle_output(t, x, u, params):
    return x                            # return x, y, theta (full state)

# Define the vehicle steering dynamics as an input/output system
vehicle = ct.NonlinearIOSystem(
    vehicle_update, vehicle_output, states=3, name='vehicle',
    inputs=('v', 'phi'), outputs=('x', 'y', 'theta'))

#We consider an optimal control problem that consists of "changing lanes" by moving from the point x = 0 m, y = -2 m, \theta = 0 to the point x = 100 m, y = 2 m, \theta = 0) over a period of 10 seconds and with a with a starting and ending velocity of 10 m/s:
x0 = [0, -2, 0]; u0 = [10, 0]
xf = [100, 2, 0]; uf = [10, 0]
Tf = 10
#To set up the optimal control problem we design a cost function that penalizes the state and input using quadratic cost functions:

Q = np.diag([0.1, 10, 0.1])    # keep lateral error low
R = np.eye(2) * 0.1
cost = opt.quadratic_cost(vehicle, Q, R, x0=xf, u0=uf)
#We also constraint the maximum turning rate to 0.1 radians (about 6 degees) and constrain the velocity to be in the range of 9 m/s to 11 m/s:

constraints = [ opt.input_range_constraint(vehicle, [8, -0.1], [11, 0.1]) ]
#Finally, we solve for the optimal inputs:

horizon = np.linspace(0, Tf, 20, endpoint=True)
bend_left = [10, 0.01]        # slight left veer

result = opt.solve_ocp(
    vehicle, horizon, x0, cost, constraints, initial_guess=bend_left,
    options={'eps': 0.01})    # set step size for gradient calculation

# Extract the results
u = result.inputs
t, y = ct.input_output_response(vehicle, horizon, u, x0)

#Plotting the results:
Norows = 3
Nocols = 1
width = 10
height = 10

fig, axes = plt.subplots(nrows=Norows, ncols=Nocols, figsize=(width, height)) #Graph Layout

# Plot the results
plt.subplot(Norows, Nocols, 1)
plt.plot(y[0], y[1])
plt.plot(x0[0], x0[1], 'ro', xf[0], xf[1], 'ro')
plt.xlabel("x [m]")
plt.ylabel("y [m]")

plt.subplot(Norows, Nocols, 2)
plt.plot(t, u[0])
plt.axis([0, 10, 8.5, 11.5])
plt.plot([0, 10], [9, 9], 'k--', [0, 10], [11, 11], 'k--')
plt.xlabel("t [sec]")
plt.ylabel("u1 [m/s]")

plt.subplot(Norows, Nocols, 3)
plt.plot(t, u[1])
plt.axis([0, 10, -0.15, 0.15])
plt.plot([0, 10], [-0.1, -0.1], 'k--', [0, 10], [0.1, 0.1], 'k--')
plt.xlabel("t [sec]")
plt.ylabel("u2 [rad/s]")

plt.suptitle("Lane change manoeuvre")
plt.tight_layout()
plt.show()

Despite the effort, the system appears to blow up, as shown in the first graph when running the code.


text:
Q: Getting Javascript Object Elements to Appear Next to HTML Buttons I'm having trouble with DOM manipulation. I'm trying to make the code below into a working quiz.
How do I associate the possibleAnswers with the buttons in my HTML? And how do I cycle through them when continuing through the quiz onto other questions? I cut out a most of the questions to save space.
Thanks.
Javascript:
let q9 = {
question : 'Which of the following films is NOT part of the Walt
Disney Studios Silly Symphonies?',
possibleAnswers : ['A. The Night Before Christmas',
             'B. Three Little Pigs',
             'C. The Old Mill',
             'D. The Gallopin\' Gaucho'],
flags : [false, false, false, true],
answer : 'D. The Gallopin\' Gaucho'
};

let q10 = {
question : 'Which wartime activity did the Walt Disney Studios
partake in to support the American war effort?',
possibleAnswers : ['A. Recycling used film footage',
              'B. Designing US Army & US Navy insignia',
              'C. Hosted a Studio Victory Garden where employees grew
food for their families',
              'D. Forced employees to carpool by closing parking lots
to non-carpool cars'],
flags : [false, true, false, false],
answer : 'B. Designing US Army & US Navy insignia'
}

 let questionArray = [q1, q2, q3, q4, q5, q6, q7, q8, q9, q10];

//hide answer buttons
$("#answers").hide();

 $(function() {

 const answerContainers =

$("#begin_button").on("click", function() {
  $(this).hide()
  $('#insert_question').text(question1.question);
  $("#answers").show()
  $('#insert_question').text(question1.answerSelections);

Here's the HTML:
<!DOCTYPE html>

 <link rel="stylesheet" type="text/css" href="actionmovies.css"/>

<title>Question This: Action Movie Edition</title>

$( function() {
$( document ).tooltip();
 } );

Question This: Super Action Movie Edition

<audio autoplay>

</audio>

<button class="Begin" id="begin_button" name="Start!" value="Begin
Trivia"></button>

      <input type="button" class="answerOptions" id="choice1">

1

</input>

        <input type="button" class="answerOptions" id="choice2">

2

</button>

        <input type="button" class="answerOptions" id="choice3">

3

</button>

        <input type="button" class="answerOptions" id="choice4">

4

</button>

    <input type="button" class="answerOptions" id="choice5">

5

</button>


text:
Q: Searching index position in python cols = [2,4,6,8,10,12,14,16,18] # selected the columns i want to work with
df = pd.read_csv('mywork.csv')
df1 = df.iloc[:, cols]
b= np.array(df1)
b
outcome
b = [['WV5 6NY' 'RE4 9VU' 'BU4 N90' 'TU3 5RE' 'NE5 4F']
   ['SA8 7TA' 'BA31 0PO' 'DE3 2FP' 'LR98 4TS' 0]
   ['MN0 4NU' 'RF5 5FG' 'WA3 0MN' 'EA15 8RE' 'BE1 4RE']
   ['SB7 0ET' 'SA7 0SB' 'BT7 6NS' 'TA9 0LP' 'BA3 1OE']]

a = np.concatenate(b) #concatenated to get a single array, this worked well

a = np.array([x for x in a if x != 'nan'])
a = a[np.where(a != '0')] #removed the nan
print(np.sort(a)) # to sort alphabetically

#Sorted array
['BA3 1OE' 'BA31 0PO' 'BE1 4RE' 'BT7 6NS' 'BU4 N90'
'DE3 2FP' 'EA15 8RE' 'LR98 4TS' 'MN0 4NU', 'NE5 4F' 'RE4 9VU'
'RF5 5FG' 'SA7 0SB' 'SA8 7TA' 'SB7 0ET' 'TA9 0LP' 'TU3 5RE'
'WA3 0MN' 'WV5 6NY']

#Find the index position of all elements of b in a(sorted array)
def findall_index(b, a )
    result = []
    for i in range(len(a)):
       for j in range(len(a[i])):
           if b[i][j] == a:
               result.append((i, j))
    return result
print(findall_index(0,result))

I am still very new with python, I tried finding the index positions of all element of b in a above.  The underneath codes blocks doesn't seem to be giving me any result.  Please can some one help me.
Thank you in advance.

A: One way you could approach this is by zipping (creating pairs) the index of elements in b with the actual elements and then sorting this new array based on the elements only. Now you have a mapping from indices of the original array to the new sorted array. You can then just loop over the sorted pairs to map the current index to the original index.
I would highly suggest you to code this yourself, since it will help you learn!


text:
Q: How can I pass the name of the file that was changed in launchd? I am trying to watch a directory for changes via launchd. My plist
file looks like this:
<key>ProgramArguments</key>
<array>
  <string>/Users/myname/bin/boink</string>
  <string>path modified</string>
</array>

All this works OK, but I would like to pass the name of the file that
was changed as an argument to the script /Users/myname/bin/boink
Is that possible? the man page isn't very helpful, nor did googling help a lot.
Thanks.

A: The short answer is: no. launchd(8) uses Kqueue (http://en.wikipedia.org/wiki/Kqueue) to receive this kind of notification. Unfortunately kqueue(2) does not return which item has triggered the event.
You may want to use the launchd(8) key QueueDirectories instead. It works essentially the same way WatchPaths works, but it assumes that the processing agent/daemon is moving the processed items from the directory being monitored to another one. So whenever an event is triggered your job can process every file in the monitored directory. Just make sure you move them after processing.


text:
Q: Storing props as a state in React js constructor() {
    super();

    this.state = {

        idnum: this.props.match.params.id,
        pokemon: [],
        imgurl: '',
        abilities: [],
        types: []
    };

    this.clickHandler = this.clickHandler.bind(this);
};

clickHandler(e) {

    this.setState({
        idnum: this.props.match.params.id
    })
    console.log("passed" , this.props.match.params.id)
}

I am trying to store this.props.match.params.id which is a id number passed in as a prop into one of my states in React.js  this.props.match.params.id works in my componentWillMount function that uses this id number to call a specific data from an API, but it gives me that match is undefined when I try to store it in my state.
I need this to work so that I can make the page re-render when Linking to the page with previous Id number by doing
<Link to={{ pathname: '/details/' + (parseInt(this.props.match.params.id) - 1) }}><Button onClick = {this.clickHandler }>Prev</Button></Link>

What is the way to store my this.props.match.params.id into my state?

A: To access props in the constructor, you can do the following:
constructor(props) {
  super(props)
  this.state = {
    idnum: props.match.params.id
  }
}


text:
Q: Find the start and end of a redirect chain I have a table of URL redirects in a SQL server table, each redirect has an ID, a FromURL and a ToURL field.
I've been asked to find where we have a chain of redirects in the table so that we can replace them with a single redirect so that users are only redirected once rather than multiple times.
An example of the table is below:

As you can see, if a user visits URL A, they will be redirected to B, then from B to C then from C to D we'd like to replace this with a single redirect from A to D to speed up the page load.
I thought I might be able to do this without cursors with a recursive CTE but I got completely stuck with this, the best I managed to to was find the start of each chain with the following:
SELECT  r.ID ,
        r.FromURL ,
        r.ToURL
FROM    dbo.redirect r
WHERE   fromURL NOT IN ( SELECT ToURL
                         FROM   dbo.redirect r2 )

This gives me the start of the chains (or the ones that aren't in a chain at all) by selecting any records where the FromURL hasn't been redirected by any other redirect.  When I tried following through some of the recursive CTE examples, all I ended up with was junk data or hitting the recursion limit.
Ideally what I'd like to get out of this is data similar to the following:

As you can see, the chains of redirects have been replaced with a single one, so every level in the hierarchy now goes directly to the end of the chain.
I'm just a DBA who agreed to do something for our web team that I have now found completely out of my ability with T-SQL so if anyone can help me out that would be most appreciated.

A: The general solution can be found searching for: "Directed Acyclic Graph", "Traversal", "SQL".  hansolav.net/sql/graphs.html#topologicalsorting has some good info.
If you need a fast answer, here's a quick-and-dirty method.  It's not efficient, and it needs an acyclic input, but it's readable to someone not familiar with sql.
SELECT id, FromUrl, ToUrl
INTO #temp
FROM dbo.redirect

WHILE @@ROWCOUNT > 0
BEGIN
  UPDATE cur
  SET ToUrl = nxt.ToURL
  FROM #temp cur
  INNER JOIN #temp nxt ON (cur.ToURL = nxt.FromURL)
END

SELECT * FROM #temp

Alternatively, with a recursive CTE:
;WITH cte AS (
  SELECT 1 as redirect_count, id, FromURL, ToUrl
  FROM dbo.redirect
  UNION ALL
  SELECT redirect_count + 1, cur.id, cur.FromURL, nxt.ToURL
  FROM cte cur
  INNER JOIN @t nxt ON (cur.ToURL = nxt.FromURL)
)
SELECT
  t1.id, t2.FromUrl, t2.ToUrl
FROM dbo.redirect t1
CROSS APPLY (
  SELECT TOP 1 FromUrl, ToUrl
  FROM cte
  WHERE id = t1.id
  ORDER BY redirect_count DESC
) t2


text:
Q:  configuration error on Godaddy Hosting I deployed a web application in Godaddy Hosting and created a virtual directory also. But when I try to access the application via URL, I get this following error

`Server Error in '/' Application.
Configuration Error
Description: An error occurred during the processing of a
  configuration file required to service this request. Please review the
  specific error details below and modify your configuration file
  appropriately.
Parser Error Message: It is an error to use a section registered as
  allowDefinition='MachineToApplication' beyond application level.  This
  error can be caused by a virtual directory not being configured as an
  application in IIS.

Source Error:
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
I tried to google it and almost most of the answers are related to virtual directory. I have attached my web.config here.
I checked with the hosting support also, but they say, it could be coding error. So let me know, if I have to think in other prespective.

<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=152368
  -->
`<configuration>`
   `<connectionStrings>
    <add name="ApplicationServices" connectionString="data            source=.\SQLEXPRESS;Integrated     Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"     providerName="System.Data.SqlClient" />
    <add name="fbpmProjectDetailsEntities"        connectionString="metadata=res://*/Models.ProjectDetail.csdl|res://*/Models.ProjectDetail.ss    dl|res://*/Models.ProjectDetail.msl;provider=System.Data.SqlClient;provider connection     string="data source=.\SQLEXPRESS;attachdbfilename=|DataDirectory|\fbpm.mdf;integrated     security=True;user instance=True;multipleactiveresultsets=True;App=EntityFramework""     providerName="System.Data.EntityClient" />
    <add name="fbpmUserEntities"      connectionString="metadata=res://*/Models.UserModel.csdl|res://*/Models.UserModel.ssdl|res:/    /*/Models.UserModel.msl;provider=System.Data.SqlClient;provider connection      string="data source=.\SQLEXPRESS;attachdbfilename=|DataDirectory|\fbpm.mdf;integrated     security=True;user instance=True;multipleactiveresultsets=True;App=EntityFramework""     providerName="System.Data.EntityClient" />
    <add name="fbpmUserPaySchedEntities"      connectionString="metadata=res://*/Models.UserPaymentSchedule.csdl|res://*/Models.UserPaymentSchedule.ssdl|res://*/Models.UserPaymentSchedule.msl;provider=System.Data.SqlClient;provide    r connection string="data     source=.\SQLEXPRESS;attachdbfilename=|DataDirectory|\fbpm.mdf;integrated security=True;user     instance=True;multipleactiveresultsets=True;App=EntityFramework""     providerName="System.Data.EntityClient" />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="1.0.0.0" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral,     PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral,   PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral,  PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      </assemblies>
    </compilation>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn" timeout="2880" />
    </authentication>
    <membership>
  <providers>
    <clear />
    <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="true" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="true" maxInvalidPasswordAttempts="3" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="10" applicationName="/" />
  </providers>
</membership>
<profile>
  <providers>
    <clear />
    <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
  </providers>
</profile>
<roleManager enabled="true">
  <providers>
    <clear />
    <add connectionStringName="ApplicationServices" applicationName="/"
      name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" />
    <add applicationName="/" name="AspNetWindowsTokenRoleProvider"
      type="System.Web.Security.WindowsTokenRoleProvider" />
  </providers>
</roleManager>
<pages>
  <namespaces>
    <add namespace="System.Web.Helpers" />
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Routing" />
    <add namespace="System.Web.WebPages" />
  </namespaces>
</pages>
<customErrors mode="Off"/>
  </system.web>
  <system.webServer>
      <modules runAllManagedModulesForAllRequests="false">
          <remove name="FormsAuthenticationModule" />
          <add name="FormsAuthenticationModule"     type="System.Web.Security.FormsAuthenticationModule" />
          <remove name="UrlAuthorization" />
          <add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule"     />
      </modules>
    <validation validateIntegratedModeConfiguration="false" />
   <!--<modules runAllManagedModulesForAllRequests="true" />-->
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
     </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>`

Please help me to identify the issue.
Thanks, Senti

A: I'm guessing that the real problem is the element before authentication, which is compilation.  This suggests that the targetFramework attribute may actually be the culprit, which in itself suggests that you may not have configured the IIS application pool to use .NET v4, but rather v2.0

A: Make sure the directory that you have your files in can be accessed by the IIS, this error occurs when the IIS can access the folder. just change the permissions to give access to the folder by IUSR and IIS_IUSR


text:
Q: Why can OverflowExceptions happen for decimal->byte conversions but not for uint->byte? I'm wondering if anyone can explain an OverflowException I am seeing.
Consider the following code:
        uint fred = 32768;
        byte wilma = (byte)fred;
        decimal bamBam = fred;
        wilma = (byte)bamBam;

I only get an OverflowException on the last line (when casting a decimal to a byte).  I do not get it when casting the same value in an uint to a byte.
I can't understand why this is the case.  Any suggestions?

A: The explicit conversion from decimal to byte is documented to throw this exception when the decimal is outside of the range of byte (0 to 255).

Overflow Exception: value is less than Byte.MinValue or greater than
  Byte.MaxValue.

And on the second line, you should be noticing that the value silently wraps, wilma is 0, so there is data loss in that legal conversion. If you would like to see the same behavior as above exhibited for the uint-to-byte integral conversion, you would run in a checked context.
checked
{
    uint fred = 32768;
    byte wilma = (byte)fred;
}

In an unchecked context, overflows are ignored for conversions between integral types. Higher order bits are discarded. (See: Section 4.1.5 of the C# language specification.)

The checked and unchecked operators and statements are used to control
  overflow checking for integral-type arithmetic operations and
  conversions (§7.6.12). In a checked context, an overflow produces a
  compile-time error or causes a System.OverflowException to be thrown.
  In an unchecked context, overflows are ignored and any high-order bits
  that do not fit in the destination type are discarded.

As for avoiding these issues, use the types that are appropriate to the data you are storing. If the data exceeds the range of byte, use a larger type. Conversions between integral types and floating point numbers are particularly problematic, as the ranges of the latter values can far exceed the range of integers, and of course data loss with decimal places is unavoidable.
However, if you continue to operate with decimal-to-byte conversions, you will need to keep in mind (and compare against) the minimum and maximum values of byte.


text:
Q: How to get into a vob on rcleartool I have type the lsvob command in rcleartool and it is giving me the list of vob's.
Now how to get into a particular vob?
I am trying cd /clinical but getting error:
CRCLI2027E Unable to change directory to "/clinical": No such directory.

A: Since you are using CCRC (the ClearCase Remote Client), in order to access files in a VOB, you must

*

*Create an automatic view or a Web view using the ClearTeam Explorer (CTE) GUI or 'rcleartool mkview ...' from the command line.

*If you're using an automatic view, mount the VOB using CTE or 'rcleartool mount ...'.  If you're using a Web view, add a load rule to the view's configuration using CTE (i.e. add "/clinical" in the "Load Rules" tab - accessible from the "Show ClearCase View Configuration" menu item on the context menu for the view)  or 'rcleartool edcs' (i.e. add a line "load /clinical" to the configuration specification).

Then go to the view root directory (R:\<view_tag>\ for an automatic view or the path to the copyarea for a Web view) and the VOB tag should be visible in that directory.  You can 'cd' into the VOB from that context.
For more details the man pages for the commands are at:
mkview
mount
edcs

A: /clinical is not a path, it is a vob tag.
See "VOB tags and VOB access".
To access it contents, you need either:

*

*a snapshot or ccweb view, with a load rule for that vob
LOAD /clinical

(See more at "ClearCase view configuration" and "View or edit load rules")

*

*or a dynamic view, with that vob mounted beforehand (rcleartool mount)
rcleartool mount /clinical

(then start the dynamic view)


text:
Q: Facebook API comments count I searched everything here and didn't find the answer.
I'm calling FB API to get some posts analytics, but I find a strange behaviour. If I call for example
134572506600855_2227601433964608/?fields=comments.limit(0).summary(true)
I get comments total_count=100
134572506600855_2227601433964608/comments?limit=0&summary=true&filter=stream
I get comments total_count=575
this is because I added filter=stream, so it counts comments-of-comments like it does in the public counter. I need to use the first call because I get all the other details there and i want to avoid an API call for each post just to get the right comments total_count, but I cannot get filter=stream working with the first call,any suggestion?


text:
Q: Cannot open i3 on ubuntu 20.04 I install i3 with
sudo apt install i3
Then I command to check version is
i3 version 4.17.1 (2019-08-30) © 2009 Michael Stapelberg and contributors

When I logout my profile and switch GUI from Ubuntu on Wayland to i3
the system forces me to log in again.
picture -> when I switch GUI
Can you help me, please? ;_; (PS. It's my first time to install i3)


text:
Q: I'm trying to add poster URLs to my neo4j movie database using JavaScript, but I'm getting this undefined object error all the time I'm completely new to JavaScript and having a hard time trying to understand asynchronous calls. Do I need to nest another promise object to set the poster URLs?
async function getIds() {
    const result = await session.run("MATCH (m :Movie) RETURN m.imdbId LIMIT 5");
    const ids = [];
    result.records.forEach(record => ids.push(record._fields[0]));
    return ids;
}

async function imdbIds() {
    const ids = await getIds();
    console.log(ids);
    const response = await Promise.all(ids.map(async id => {
        // webscraper that returns poster url of each imdbid
        const url = toString(scraper(id));
        console.log(url);

        // query to set poster of each id in neo4j db
        const result = await session.run("MATCH (m :Movie {imdbId : $id}) SET m.poster = $url RETURN m.poster", { id, url });
        result.records.forEach(record => console.log(record._fields[0]));
        return result;
    }));
    console.log(response);
}

imdbIds();

Console logs still no luck:
[ '0114709', '0113497', '0113228', '0114885', '0113041' ]
[object Undefined]
[object Undefined]
[object Undefined]
[object Undefined]
[object Undefined]
[object Undefined]
[object Undefined]
[object Undefined]
[object Undefined]
[object Undefined]
[ { records: [ [Record] ],
    summary:
     ResultSummary {
       statement: [Object],
       statementType: 'rw',
       counters: [StatementStatistics],
       updateStatistics: [StatementStatistics],
       plan: false,
       profile: false,
       notifications: [],
       server: [ServerInfo],
       resultConsumedAfter: [Integer],
       resultAvailableAfter: [Integer] } } ...

A: The problem is your getIds function. you have wrapped a already promise returning function in another promise. second problem is your getIds function. you are doing asynchronous operation in forEach which will not work. Replace it with Promise.all it should be like this
async function getIds() {
  const result = await session.run("MATCH (m :Movie) RETURN m.imdbId LIMIT 5");
  const ids = [];
  result.records.forEach(record => ids.push(record._fields[0]));
  return ids;
}

async function imdbIds() {
  const ids = await getIds();
  console.log(ids);
  const response = await Promise.all(ids.map(async id => {
    // webscraper that returns poster url of each imdbid
    const url = toString(scraper(id));
    console.log(url);

    // query to set poster of each id in neo4j db
    const result = await session.run("MATCH (m :Movie {imdbId : $id}) SET m.poster = $url RETURN m.poster", {id, url});
    result.records.forEach(record => console.log(record._fields[0]));
    return result;
  }));
  console.log(response);
}

A: figured it out, thanks for help mr. ashish modi
async function setPosters() {
    const result = await session.run("MATCH (m :Movie) RETURN m.imdbId LIMIT 15");
    result.records.forEach(async record => {
        const imdbId = record._fields[0];
        const url = await scraper(imdbId);
        await session.run("MATCH (m :Movie {imdbId : $imdbId}) SET m.poster = $url RETURN m.poster", { imdbId, url });
    });
}

setPosters();


text:
Q: Upload of image doesn't work (dealing with cropper.js on a modal) I have a modal in my signup.html that should display a image cropper, from cropper.js when a file is uploaded. But if I try to change the file I'm uploading, the modal shows up with the first file that I used. What am I doing wrong?
P.S.: Is the first time I'm using cropper.js.
Here is my code:
signup.html:
{% extends 'base.html' %}

{% load static %}

{% block content %}

    <form enctype="multipart/form-data" method="POST" class="post-form">

+ Cadastro de novo aluno

        {% csrf_token %}
        {{ credentials_form }}
        {{ personal_info_form }}
        <button type="submit" class="save btn btn-default">Confirmar</button>
    </form>

        ×

        <button class="crop">Cortar</button>

{% endblock %}

image_cropper.js:
showModal = () => {
    let modal = document.querySelector('#modal');
    let image = document.querySelector('#image');

    let file = document.querySelector('input[type=file]').files[0];
    let fileReader = new FileReader();

    fileReader.onload = () => {
        modal.style.display = 'flex';
        image.src = fileReader.result;
        let cropper = new Cropper(image, {
            dragMode: 'move',
            aspectRatio: 1 / 1,
            autoCropArea: 0.65,
            restore: false,
            guides: false,
            center: false,
            highlight: false,
            cropBoxMovable: false,
            cropBoxResizable: false,
            toggleDragModeOnDblclick: false,
        });

        let crop_button = document.querySelector('.crop');
        crop_button.onclick = cropper.crop;
    }

    if (file) {
        fileReader.readAsDataURL(file);
    } else {
        image.src = '';
    }
}

closeModal = () => {
   let modal = document.querySelector('#modal');
   picture_input.value = '';
   modal.style.display = 'none';
}

let picture_input = document.querySelector('#id_picture');
picture_input.onchange = showModal;

let close_button = document.querySelector('.close');
close_button.onclick = closeModal;

The file input is rendered by Django, but it looks like this:
<input name="picture" accept="image/*" required="" id="id_picture" type="file">

A: To delete the instance of the image, you need to use the destroy() method available. In my code, I put it like this:
close_button.onclick = closeModal = () => {
    modal.style.display = 'none';
    cropper.destroy();
}


text:
Q: Screenshot of running Google Chrome browser in OS X from Python When I run Selenium-style integration tests with Google Chrome on OS X from a Python script, I'd like to take screenshots at each step. I'd like to just capture the Google Chrome window, not the whole desktop. Is there any way to do a screen grab of a currently running Google Chrome window in OS X from a Python script?

A: I've not done it from OS X on Chrome, but does something like this not work:
browser.open("/page-to-capture")
png = browser.capture_screenshot_to_string()
with open("screenshot.png", "wb") as fh:
    fh.write(png.decode('base64'))

Certainly it has worked for me in the past using selenium on linux with firefox.

A: Sounds like you are looking for the "screencapture" command line tool under MacOS.  Can you call that from your Python script?
One of the options is "-w", which is "window selection mode".  I'm not certain if this will work from within a script (i.e. does it require user interaction?), but if that doesn't work you could also try "-m", which is the "only capture main monitor" option.

A: It turns out that selenium has a get_screenshot_as_file method that works with OS X and Google Chrome.


text:
Q: Does running time for one thread is same for running time of 1000 threads in python multi-threading? While trying the below python code which illustrates the multi-threading concept,it took 0.8 sec.
import time
import threading

def calc_square(numbers):
    print("calculate square numbers")
    for n in numbers:
        time.sleep(0.2)
        print('square:',n*n)

def calc_cube(numbers):
    print("calculate cube of numbers")
    for n in numbers:
        time.sleep(0.2)
        print('cube:',n*n*n)

arr = [2,3,8,9]

t = time.time()

t1= threading.Thread(target=calc_square, args=(arr,))
t2= threading.Thread(target=calc_cube,args=(arr,))

t1.start()
t2.start()

t1.join()
t2.join()

print("done in : ",time.time()-t,"seconds")

Here 2 threads are created each of each function. If again we are creating threads like t3,t4...t10 it took same 0.8 sec. Does this will be same for 1000 threads?
 Since for loop in python is not parallel, we cant use for loop for running this.
  for i in range(1000):
    t1= threading.Thread(target=calc_square, args=(arr,))
    t1.start()
    t1.join()

could not be used. So my doubt is, is that same 0.8 sec for 1000 threads?


text:
Q: How to start at x = 0 with given xrange in gnuplot? in gnuplot, is it possible to start the graph at x = 0 in given x range?
Let say that I have this code:
set xrange [100:500]
plot "input.txt" using 2:1:(1.0) notitle with lines lw 1

Consequently, the graph will start at x = 100 and end at x = 500.
I want the graph to start at x = 0 and end at x = 400 with the given range [100:500].
How can I do this?
Thanks!

A: Just use an xrange of [0:400] and subtract 100 from your data values:
set xrange [0:400]
plot "input.txt" using ($2-100):1 with lines


text:
Q: How do I solve this (multiplication of exponents) I can not find any help to spread the exponent across the brackets
$$\left[-3(-2)^2\right]^{-1}$$

A: $$\left[-3(-2)^2\right]^{-1} = \dfrac{1}{-3(-1\cdot 2)^2} \;=\; \left(-\dfrac{1}{3\left[(-1)^2\cdot 2^2\right]}\right).$$
Now simplify, using the correct order of operations, some of which I've completed above: take exponents, then multiply within the parentheses, then multiply the two resulting terms in the denominator...
Recall:
$a^{-1} = \dfrac{1}{a}\;\;$ for all real $a$, $a\neq 0$
$(ab)^2 = a^2b^2\;\;$ for all $a, b \in \mathbb{R}$
$\dfrac{1}{-a} = \dfrac{-1}{a} = -\dfrac{1}{a}$

Tip: the acronym PEMDAS is common to help remember the order in which to perform operations It stands for Parentheses, Exponents, (Multiplication, Division), (Addition, Subtraction), and serves as a reminder for remembering the precedence of operations (order to perform operations): Multiplication and Division have equal precedence, so when they occur together in an expression, apply from left to right. Same applies to Addition/subtraction.


text:
Q: Obtener el valor de un editText y parsearlo a LocalTime EditText et;
LocalTime t;
No pongo el findView completo pero esta puesto
findViewById(R.id.et)
findViewById(R.id.et)
String s= et.getText().toString();
time=LocalTime.parse(t);
error en la consola
2022-12-05 19:18:18.402 4776-4776/codewithcal.au.calendarappexample E/AndroidRuntime: FATAL EXCEPTION: main
Process: codewithcal.au.calendarappexample, PID: 4776
java.lang.RuntimeException: Unable to start activity ComponentInfo{codewithcal.au.calendarappexample/codewithcal.au.calendarappexample.EventEditActivity}: java.time.format.DateTimeParseException: Text '' could not be parsed at index 0


text:
Q: iOS: setAllowsEditing only for video I am using UIImagePickerController with:
[picker setAllowsEditing:YES];`

picker.mediaTypes is set to kUTTypeMovie and kUTTypeImage
But I would like to set this option only for movies and not for images. How can I implement this?

A: you can try to make two sperate buttons(action) for movie and image. when the user wants to capture image disable the editing. Or, I would go with
Fully-Customized Media Capture and Browsing which will enable you to do many flexible  things
EDIT: Also 'cameraOverlayView' can help. you make a custom view where you make button to handle the event.


text:
Q: Error 404 Posting data from web client to web server I cannot figure this out for the life of me, basically, I am using Visual Studio to implement a client-server system. I am new to this so this might seem like a simple problem.
I want to simply be able to allow the user to register to the system and store their details on SQL server. I have a web client which has a communication class to communicate with the web server, on this communication class I am trying to post the details that the user has input and route them to the necessary class on the server side which will deal with inserting the record.
I know the code is correct I am just pretty sure there is some syntax error or something. Basically I am getting a 404 error not found. I have checked for hours that my url address is exactly the same on both client and server side. Any help would be appreciated, this has been a nightmare for me.
Also the class 'UserM' is just the model that contains the information about the user table. I have also rechecked the ports and they are correct.
CLIENT SIDE COMMUNICATION CLASS:
private static string URL = "http://localhost:12804/api/Users/";

    public static UserM Register(UserM user)
    {

       var request = HttpWebRequest.Create(String.Format(URL + "Register?email={0}&password={1},forename={2},surname={3},dob={4},balance={5},nooflogins={6},joindate={7}", user.Email, user.Password, user.Forename, user.Surname, user.DoB, user.Balance, user.NoOfLogins, user.JoinDate));// "/save" or "/update"

        request.ContentType = "application/json"; // tell the API we want Json returned
        request.Method = "POST";

        try
        {
            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                string JSONPost = JsonConvert.SerializeObject(user, Formatting.None,
                    new JsonSerializerSettings()
                   {
                        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                    });

                streamWriter.Write(JSONPost);
                streamWriter.Flush();
                streamWriter.Close();
            }

           using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return null;
                }
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    return JsonConvert.DeserializeObject<UserM>(reader.ReadToEnd()); //if user is succesfully inserted into database
                }
           }
        }
        catch (Exception ex)
        {
            return null;
        }

    }

SERVER SIDE CLASS:
[Route("api/Users/Register"), AcceptVerbs("GET")]
     public UserM RegisterUser(string email, string password, string forename, string surname, DateTime DoB, decimal balance, int NoOfLogins, DateTime joindate)
    {
        using (TestDBDataContext tdb = new TestDBDataContext())
        {
            //check is user already exists in database
            if (tdb.User.Where(x => x.Email == email).Count() <= 0)
            {
                User temp = new User()
                {
                    Email = email,
                    Password = password,
                    Forename = forename,
                    Surname = surname,
                    DoB = DoB,
                    Balance = balance,
                    NoOfLogins = NoOfLogins,
                    JoinDate = joindate
                };

                tdb.User.InsertOnSubmit(temp);

                try
                {
                    tdb.SubmitChanges();
                    return new UserM(temp);
                }
                catch (Exception ex)
                {
                    return null;
                }
            }
            else
            {
                return null;
            }

        }
    }

A: Use the ampersand & instead of comma , in your query string:
&password={1}&forename={2}&surname={3}...


text:
Q: Global call to the notification function in VUEJS I want to make a global function with message passing based on the vue-notification component
I can call a simple alert from the desired component
notification.js
export function notifAlert(message)  {
    alert(message)
}

in text.vue page
import { notifAlert } from '@/utils/notification'
export default {
...
    methods: {
        onButtonClick() {
            notifAlert('1123');
        }
    }
}

but I can't figure out how to connect vue-notification to also call them as a simple message
notification.js
import VueNotifications from "vue-notifications";

export function notifAlert(messageText)  {
    notifications: {
        showSuccessMsg(): {
            type: VueNotifications.types.success,
            title: "Success",
            message: messageText
        },
        showInfoMsg: { ... },
        showWarnMsg: { ... },
        showErrorMsg: { ... },
    }
}

And how do I call showSuccessMsg (text) and others in methods?

A: Should be able to accomplish this with mixins ..
Example: https://codesandbox.io/s/github/oze4/vue-mixin-notifications-poc/tree/master/?fontsize=14


text:
Q: err_too_many_redirects when trying to redirect non www to www Inside virtuahost apache conf file
/etc/apache2/sites-available/000-default.conf
I tried to put these code inside apache conf file
ServerName example.com
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com
RewriteRule ^/(.*)$ http://www.example.com/$1 [L,R=301]

also I tried,
< If "%{HTTP_HOST} != 'YOUR-DOMAIN.com'">
Redirect "/" "http://www.YOUR-DOMAIN.com/"
</If>

also did this
<VirtualHost *:80>
    ServerName example.com
    Redirect permanent / http://www.example.com/
</VirtualHost>

<VirtualHost *:80>
    ServerName www.example.com
    # real server configuration
</VirtualHost>

A: Your last code block should have worked 100%.
As @HBrujin commented this looks like a cache fault from an initial redirect error.
I suggest you try using Google Chrome with networking tools which allow you to load a page with all caches disabled.
Simply inspect your page and navigate to Networking tab. Check the disable cache checkbox and reload your page with the 3d code block of yours.
It should work.
You can check this article as well on how to clear your cache from all browsers.