text:
Q: how to upload a file from android application to google drive i want to upload a text file or any file from any android application to google drive.i am using this below code.but its not working proporly.can any one please help me.how to solve this.
this is main activity
package com.intel.driveapp;

import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.Activity;
import android.view.Menu;
import android.view.View;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.accounts.AccountManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.google.android.gms.common.api.GoogleApiClient;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;

public class MainActivity extends Activity
{
    static final int                REQUEST_ACCOUNT_PICKER = 1;
    static final int                REQUEST_AUTHORIZATION = 2;
    static final int                RESULT_STORE_FILE = 4;
    private static Uri              mFileUri;
    private  Drive          mService;
    private GoogleAccountCredential mCredential;
    private Context                 mContext;
    private List<File>              mResultList;
    private ListView                mListView;
    private String[]                mFileArray;
    private String                  mDLVal;
    private ArrayAdapter            mAdapter;
    private final HttpTransport m_transport = AndroidHttp.newCompatibleTransport();
    private final JsonFactory m_jsonFactory = GsonFactory.getDefaultInstance();

    GoogleApiClient mGoogleApiClient;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        // Connect to Google Drive
        mCredential = GoogleAccountCredential.usingOAuth2(this, Arrays.asList(DriveScopes.DRIVE));

        mService = new com.google.api.services.drive.Drive.Builder(
                m_transport, m_jsonFactory, mCredential).setApplicationName("AppName/1.0")
                .build();

        startActivityForResult(mCredential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);

        mContext = getApplicationContext();

        setContentView(R.layout.activity_main);
        mListView = (ListView) findViewById(R.id.listView1);

        OnItemClickListener mMessageClickedHandler = new OnItemClickListener()
        {
            public void onItemClick(AdapterView parent, View v, int position, long id)
            {
                downloadItemFromList(position);
            }
        };

        mListView.setOnItemClickListener(mMessageClickedHandler);

        final Button button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                final Intent galleryIntent = new Intent(Intent.ACTION_PICK);
                galleryIntent.setType("*/*");
                startActivityForResult(galleryIntent, RESULT_STORE_FILE);
            }
        });

        final Button button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                getDriveContents();
            }
        });
    }

    private void getDriveContents()
    {
        Thread t = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                mResultList = new ArrayList<File>();
                com.google.api.services.drive.Drive.Files f1 = mService.files();
                com.google.api.services.drive.Drive.Files.List request = null;

                do
                {
                    try
                    {
                        request = f1.list();
                        request.setQ("trashed=false");
                        com.google.api.services.drive.model.FileList fileList = request.execute();

                        mResultList.addAll(fileList.getItems());
                        request.setPageToken(fileList.getNextPageToken());
                    } catch (UserRecoverableAuthIOException e) {
                        startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
                    } catch (IOException e) {
                        e.printStackTrace();
                        if (request != null)
                        {
                            request.setPageToken(null);
                        }
                    }
                } while (request.getPageToken() !=null && request.getPageToken().length() > 0);

                populateListView();
            }
        });
        t.start();
    }

    private void downloadItemFromList(int position)
    {
        mDLVal = (String) mListView.getItemAtPosition(position);
        showToast("You just pressed: " + mDLVal);

        Thread t = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                for(File tmp : mResultList)
                {
                    if (tmp.getTitle().equalsIgnoreCase(mDLVal))
                    {
                        if (tmp.getDownloadUrl() != null && tmp.getDownloadUrl().length() >0)
                        {
                            try
                            {
                                com.google.api.client.http.HttpResponse resp =
                                        mService.getRequestFactory()
                                        .buildGetRequest(new GenericUrl(tmp.getDownloadUrl()))
                                        .execute();
                                InputStream iStream = resp.getContent();
                                try
                                {
                                    final java.io.File file = new java.io.File(Environment
                                            .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath(),
                                            tmp.getTitle());
                                    showToast("Downloading: " + tmp.getTitle() + " to " + Environment
                                            .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath());
                                    storeFile(file, iStream);
                                } finally {
                                    iStream.close();
                                }

                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        });
        t.start();
    }

    private void populateListView()
    {
        runOnUiThread(new Runnable()
        {
            @Override
            public void run()
            {
                mFileArray = new String[mResultList.size()];
                int i = 0;
                for(File tmp : mResultList)
                {
                    mFileArray[i] = tmp.getTitle();
                    i++;
                }
                mAdapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1, mFileArray);
                mListView.setAdapter(mAdapter);
            }
        });
    }

    private void storeFile(java.io.File file, InputStream iStream)
    {
        try
        {
            final OutputStream oStream = new FileOutputStream(file);
            try
            {
                try
                {
                    final byte[] buffer = new byte[1024];
                    int read;
                    while ((read = iStream.read(buffer)) != -1)
                    {
                        oStream.write(buffer, 0, read);
                    }
                    oStream.flush();
                } finally {
                    oStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    protected void onActivityResult(final int requestCode, final int resultCode, final Intent data)
    {
        switch (requestCode)
        {
            case REQUEST_ACCOUNT_PICKER:
                if (resultCode == RESULT_OK && data != null && data.getExtras() != null)
                {
                    String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
                    if (accountName != null) {
                        mCredential.setSelectedAccountName(accountName);
                        mService = getDriveService(mCredential);
                    }
                }
                break;
            case REQUEST_AUTHORIZATION:
                if (resultCode == Activity.RESULT_OK) {
                    //account already picked
                } else {
                    startActivityForResult(mCredential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
                }
                break;
            case RESULT_STORE_FILE:
                mFileUri = data.getData();
                // Save the file to Google Drive
                saveFileToDrive();
                break;
        }
    }

    private Drive getDriveService(GoogleAccountCredential credential) {
        return new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential)
            .build();
      }

    private void saveFileToDrive()
    {
        Thread t = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    /*Context context;
                    String currentDBPath = "//data//" + context.getPackageName()
                            + "//databases//" + databaseName + "";*/

                    // Create URI from real path
                    String path;
                    path = getPathFromUri(mFileUri);
                    mFileUri = Uri.fromFile(new java.io.File(path));

                    ContentResolver cR = MainActivity.this.getContentResolver();

                    // File's binary content
                    java.io.File fileContent = new java.io.File(mFileUri.getPath());
                    FileContent mediaContent = new FileContent(cR.getType(mFileUri), fileContent);

                    showToast("Selected " + mFileUri.getPath() + "to upload");

                    // File's meta data.
                    File body = new File();
                    body.setTitle(fileContent.getName());
                    body.setMimeType("text/plain");

                    com.google.api.services.drive.Drive.Files f1 = mService.files();
                    com.google.api.services.drive.Drive.Files.Insert i1 = f1.insert(body, mediaContent);
                    File file = i1.execute();

                    if (file != null)
                    {
                        showToast("Uploaded: " + file.getTitle());
                    }
                } catch (UserRecoverableAuthIOException e) {
                    startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
                } catch (IOException e) {
                    e.printStackTrace();
                    showToast("Transfer ERROR: " + e.toString());
                }
            }
        });
        t.start();
    }

    public void showToast(final String toast) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), toast, Toast.LENGTH_SHORT).show();
            }
        });
    }

    public String getPathFromUri(Uri uri)
    {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

}

but when i am uploading a image ,its showing which image is selected but after that one toast message is showing
tranfer error: com.google.api.client.googleapis.extentions.amdroid.gms.auth.GoogleAuthIOException


text:
Q: create a responsive triangle I'm trying to set two triangles in the following way:

The two triangles have to go from the middle to the outside of the browser. I tried to set it up with a wrapper and a background-color and then rotate the wrapper, but I cant get it responsive. The code I tried was:

    #page-header-wrapper-triangle {
    background-color:#e14b41 ;
    -webkit-transform: rotate(-12deg) translate3d(0, 0, 0);
    -moz-transform: rotate(-12deg);
    -o-transform: rotate(-12deg);
    -ms-transform: rotate(-12deg);
    transform: rotate(-12deg);
    margin: 0 -21px;
    -webkit-transform-origin: left center;
    -moz-transform-origin: left center;
    -o-transform-origin: left center;
    -ms-transform-origin: left center;
    transform-origin: left center;
    -webkit-backface-visibility: hidden;
    outline: 1px solid transparent;
    position: relative;
    min-height: 204px;
    z-index:1000;
    width:80%;
    }
    #page-header-wrapper-triangle-2 {

    background-color:#e14b41 ;
    -webkit-transform: rotate(12deg) translate3d(0, 0, 0);
    -moz-transform: rotate(12deg);
    -o-transform: rotate(12deg);
    -ms-transform: rotate(12deg);
    transform: rotate(12deg);
    margin: 0 -54px;
    -webkit-transform-origin: left center;
    -moz-transform-origin: left center;
    -o-transform-origin: left center;
    -ms-transform-origin: left center;
    transform-origin: left center;
    -webkit-backface-visibility: hidden;
    outline: 1px solid transparent;
    position: relative;
    min-height: 204px;
    z-index:1000;
    width:80%;
    float:right;
    top:-520px;
    }

This works when the width of the browser is 1920 px, but s soon as I change the width it doesn't work. I got no clue how I can get this responsive.
I also tried it with background pictures. But this also doesn't work.

A: You can do it with pseudo selectors :after. It's responsive-ready only for some small and mid widths. But you can easily customize with media queries and change the top and height value.
There is a live example using SCSS

.header {
  background-color: grey;
  padding-bottom: 60px;
  padding-top: 60px;
  position: relative;
  display: inline-block;
  width: 100%;
}
.header .block-left {
  float: left;
  width: 50%;
}
.header .block-left:after {
  background-color: red;
  content: ' ';
  left: 0;
  top: -125px;
  height: 200px;
  position: absolute;
  transform: skew(0deg, -15deg);
  width: 50%;
  z-index: 20;
}
.header .block-right {
  float: right;
  width: 50%;
}
.header .block-right:after {
  right: 0;
  background-color: yellow;
  content: ' ';
  top: -125px;
  height: 200px;
  position: absolute;
  transform: skew(0deg, 15deg);
  width: 50%;
  z-index: 20;
}

A: Here's a explanation of how css triangles works : http://codepen.io/chriscoyier/pen/lotjh
@import url(http://fonts.googleapis.com/css?family=Andika);

$stepTiming: 0.8s 0.2s;

.triangle-demo {
  width: 100px;
  height: 100px;
  margin: 0 auto;
  background: tan;
  border-top: 0 solid #EE7C31;
  border-left: 0 solid #F5D97B;
  border-bottom: 0 solid #D94948;
  border-right: 0 solid #8DB434;
  transition: $stepTiming;

  .step-1 & {
    border-top-width: 10px;
  }
  .step-2 & {
    border-left-width: 10px;
  }
  .step-3 & {
    border-right-width: 10px;
  }
  .step-4 & {
    border-bottom-width: 10px;
  }
  .step-6 & {
    background: transparent;
  }
  .step-7 & {
    width: 0; height: 0;
  }
  .step-8 & {
    border-left-color: transparent;
  }
  .step-9 & {
    border-right-color: transparent;
  }
  .step-10 & {
    border-top-color: transparent;
  }
}

.triangle-title {
  width: 300px;
  padding: 1rem;
  color: white;
  background: #D94948;
  border-radius: 20px;
  margin: auto;
  opacity: 0;
  transition: $stepTiming;
  .step-11 & {
    opacity: 1;
  }
}

body {
  background: #333;
  font-family: 'Andika', sans-serif;
  color: white;
  text-align: center;
  font-size: large;
  transform: translateZ(0);
}

.steps {
  position: relative;
  height: 45px;
  > div {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    opacity: 0;
    background: #333;
    transition: 0.3s;
  }
  .step-0 {
    opacity: 1;
  }
  .step-1 & .step-1 {
    opacity: 1;
  }
  .step-2 & .step-2 {
    opacity: 1;
  }
  .step-5 & .step-5 {
    opacity: 1;
  }
  .step-6 & .step-6 {
    opacity: 1;
  }
  .step-7 & .step-7 {
    opacity: 1;
  }
  .step-8 & .step-8 {
    opacity: 1;
  }
  .step-11 & .step-11 {
    opacity: 1;
  }
}

h1 {
  text-transform: uppercase;
  letter-spacing: 1px;
  font-size: 1.5rem;
  border-bottom: 1px solid #555;
  color: #999;
}

FYI http://1stwebdesigner.com/css-shapes/

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to move a row of one table into another table through select a row and then click to move it using jQuery? I am new to stackoverflow i am facing some problem i am working on two tables. It has like right button to move the row into the next table now the actual problem is i am trying to make it but it's not working.
Kindly help me.

$(function() {
  $(document).on("click", "#submit", function() {
    var getSelectedRows = $(".src-table").parents("tr");
    $(".target-table tbody").append(getSelectedRows);
  })
})

  Source table

    Select
    Firstname
    Lastname
    Age

    Jill
    Smith
    50

    Eve
    Jackson
    94

<input type="button" value="Submit" id="submit">

  Target table

    Select
    Firstname
    Lastname
    Age

A: The issue is because your selector is incorrect, hence getSelectedRows holds an empty jQuery object.
You don't need to use parents() at all as the tr are children of the table you're selecting, so just $(".src-table tr"); will work fine.
You should note that I added a
 element to the tables, otherwise you ended up duplicating the heading row. Try this:

$(function() {
  $(document).on("click", "#submit", function() {
    var getSelectedRows = $(".src-table tbody tr");
    $(".target-table tbody").append(getSelectedRows);
  })
})

Source table

      Select
      Firstname
      Lastname
      Age

      Jill
      Smith
      50

      Eve
      Jackson
      94

<input type="button" value="Submit" id="submit">

Target table

      Select
      Firstname
      Lastname
      Age

A: Replacing var getSelectedRows = $(".src-table").parents("tr");
with var getSelectedRows = $(".src-table").find("tr"); worked for me.
here is the jsFiddle
.parents() works with ancestor elements. while find() works with descendant elements. in you r code tr is the child of .src-table so you should either use  $(".src-table").find("tr"); or $(".src-table tr");

Given a jQuery object that represents a set of DOM elements, the
  .parents() method allows us to search through the ancestors of these
  elements in the DOM tree and construct a new jQuery object from the
  matching elements ordered from immediate parent on up; the elements
  are returned in order from the closest parent to the outer ones. When
  multiple DOM elements are in the original set, the resulting set will
  be in reverse order of the original elements as well, with duplicates
  removed.

A: You can select all TR elements $(".src-table tr") and append to the target table. In your function, there is no tbody
$(function() {
  $('#submit').on('click', function() {
    var getSelectedRows = $(".src-table tr");
    $(".target-table").append(getSelectedRows);
  })
});


text:
Q: Recyclerview data appear again after deleting I have a recyclerview. In its item layout , I have a plus button . If user click on that button it will become minus and new layout will added below it . If user click on minus it will remove from recyclerview as well as from the dataset .
Problem is :
When user click minus it removes properly from both recyclerview and dataset but on adding new layout it appears with old data again . I make sure that it deletes from dataset but still appears again.
My Adapter Code:
@Override
    public void onBindViewHolder(final MyViewHolder holder, final int position) {
        holder.img_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (if it is plus) {

                   holder.img_delete.setImageResource(set minus drawable);

                    MyModel model = new MyModel();
                    model.setPrice("");

                    data.add(model);

                    notifyItemInserted(position+1); //+1 Because first time im adding one data manually in onCreate to set adapter

                } else {

                    data.remove(position);

                    notifyItemRemoved(position);

                }

            }
        });


text:
Q: Fetch DayOfWeek value from asp label I have a ASP Label lblweekoff.Text and its Value could be combination of any 2 weekdays like Sun,Sat/Sun,Mon/Mon,Tue,etc., And I want to get the DayOfWeek value for the 2 weekdays split by comma to check with a date textbox txtdate.Text.
For example,
Lets say I have the below value for the label
lblweekoff.Text = "Sun,Sat";
txtDate.Text = "30/3/2019";
var dayColumns = new[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
DateTime weekday = Convert.ToDateTime(lblweekoff.Text);
var weekoff = dayColumns[(int)weekday.DayOfWeek];
DateTime Date = Convert.ToDateTime(txtDate.Text);
if(Date.DayOfWeek == weekoff)
{
    //some code
}
else
{
    //some code
}

So I want to check whether the DayOfWeek of the date selected on the textbox txtDate.Text is equal to that of one of the two DayOfWeeks value separated by comma Sun,Sat as shown on the label lblweekoff.Text and proceed further according to that.
How can I get this done? Appreciate any help, thanks in advance.

A: I have converted all controls into string, you need to changed that to your control again.
    string lblweekoff = "Sun,Sat";
    string txtDate = "30/Mar/2019"; // you might need to format this date

    var dayColumns = new[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
    var offDay = lblweekoff.Split(',').ToList();
    DateTime Date = Convert.ToDateTime(txtDate);
    if (offDay.Contains(Date.ToString("ddd")))// weekend
    {
        //some code
    }
    else
    {
        //some code
    }

A: First, I didn't quite get what you are asking but here is something that may work for you.
You can get today:
string day = DateTime.Today.DayOfWeek.ToString();
lblweekoff.Text = day;

End you can pick other one random,
Random rnd = new Random();
int day2= rnd.Next(0, 6);
lblweekoff.Text =lblweekoff.Text + ","+dayColumns[rnd];

I hope it helps,

A:         string lblweekoff = "Sun,Sat";
        string txtDate = "3/30/2019";// need format "m/dd/yyyy"
        var dayColumns = new[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
        List<string> weekday = lblweekoff.Split(',').ToList();
        if( dayColumns.Contains(Convert.ToDateTime(txtDate).ToString("ddd")))
        {

        }


text:
Q: Under what circumstances would a ProcessDiagnosticInfo be associated with multiple AppDiagnosticInfo's? I'm looking into Windows.System.Diagnostics and have found the ProcessDiagnosticInfo.GetAppDiagnosticInfos() method. I was expecting that for a given process, there would only be one app associated, not multiple, so why is this returning a List? What circumstances would cause this to return more than one value?

A: Seems I found the answer shortly after asking.

For any process associated with a UWP app, the IsPackaged property is true. So, for each of these, you can get from the ProcessDiagnosticInfo to the AppDiagnosticInfo. It might seem strange that we can get AppDiagnosticInfos (plural) from a process – but this is to allow for the possibility that a single process is associated with more than one app. That's an extremely uncommon scenario, but it is possible in the case of VoIP apps where two or more apps in the same package can share a component running in a separate process at run time. In almost all cases, though, there will only be one AppDiagnosticInfo per process.

https://blogs.windows.com/buildingapps/2017/06/28/uwp-app-diagnostics/#IXiAlM28HfPWx0hT.97


text:
Q: Using a PLSQL CASE statement I am trying to use a case statement to determine which select statement should be executed. I want to check the third character of the variable :SSN. If the third character is a dash, use the first SQL statement to mask the first 5 numbers (XX-XXX1234). Otherwise, use the second SQL statement to mask the first 5 numbers (XXX-XX-1234).
What is the correct syntax for this?
select case
    when substr(:SSN, 3,1) = '-' then
    SELECT 'XX-XXX'||substr(:SSN, 7,4) INTO :MaskedSSN FROM DUAL
else
    SELECT 'XXX-XX-'||substr(:SSN, 8,4) INTO :MaskedSSN FROM DUAL
end

A: You can use SQL CASE expression for this
select case
    when substr(:SSN, 3,1) = '-' then
     'XX-XXX'||substr(:SSN, 7,4)
else
     'XXX-XX-'||substr(:SSN, 8,4)
end
INTO :MaskedSSN
from dual

A:
Just an alternaive to try.Enjoy

SELECT DECODE(SUBSTR(:SSN, 3,1),'-','XX-XXX'
  ||SUBSTR(:SSN, 7,4),'XXX-XX-'
  ||SUBSTR(:SSN, 8,4))
INTO lv_var
FROM dual;

A: Useless use of SQL context (i.e. select from dual) in PL/SQL is a very poor practise. Here we have a perfectly valid and simple PL/SQL only solution (this is a PL/SQL question anyway):
declare
  function mask_ssn(p_ssn in varchar2) return varchar2 is
  begin
    -- the OP explicitly asked for case-statement even old boring if-statement
    -- would do
    return case
      when substr(p_ssn, 3, 1) = '-' then 'XX-XXX'  || substr(p_ssn, 7, 4)
      else                                'XXX-XX-' || substr(p_ssn, 8, 4)
    end;
  end;
begin
  dbms_output.put_line('masked: ' || mask_ssn('AB-CDE1234'));
  dbms_output.put_line('masked: ' || mask_ssn('ABC-CD-1234'));
end;
/

Output:
masked: XX-XXX1234
masked: XXX-XX-1234

(Note that I said useless use - there is many valid use scenarios, but this is not one of them.)


text:
Q: javascript show or hide when option is changed so i am trying to show or hide with javascript when option value K is pressed. When K is pressed div class "nobr" will appear. when option value K is not pressed "nobr" is hidden.
<select name="item[1502][additional_data] scustomg" style="width: 100%" onchange="setCustomPrice(1502, $(this))" id="select-custom-group">
<option value="1" data-price="300.0000">1 - €300.00</option>
<option value="2" data-price="210.0000">2 - €210.00</option>
<option value="4" data-price="189.0000">4 - €189.00</option>
<option value="6" data-price="210.0000">6 - €210.00</option>
<option value="8" data-price="210.0000">8 - €210.00</option>
<option value="9" data-price="0.0000">9 - €0.00</option>
<option value="K" data-price="0.0000">K - €0.00</option>
</select>

<input type="checkbox" id="item_use_custom_price_1502" onclick="order.toggleCustomPrice(this, 'item_custom_price_1502', 'item_tier_block_1502');">
Custom Price*

I can get Javascript work and i See pop up box. but can get this when K is pressed.

A: Obviously you need to listen to the change of the dropdown.
with jQuery, you can do
$('#select-custom-group').change(function () {
  $('.nobr ').toggle($(this).val() === 'K');
});

A: with javascript you can add onchange function having the selected option as parameter, then check if the value is your required value, if it is the case then hide the div else show the div

<select name="item[1502][additional_data] scustomg" style="width: 100%" onchange="setCustomPrice('price_info_1', this)" id="select-custom-group">
<option value="1" data-price="">Pick a Price</option>
<option value="1" data-price="300.0000">1 - €300.00</option>
<option value="2" data-price="210.0000">2 - €210.00</option>
<option value="4" data-price="189.0000">4 - €189.00</option>
<option value="6" data-price="210.0000">6 - €210.00</option>
<option value="8" data-price="210.0000">8 - €210.00</option>
<option value="9" data-price="0.0000">9 - €0.00</option>
<option value="K" data-price="0.0000">K - €0.00</option>
</select>

<input type="checkbox"  onclick="">
Custom Price*

<select name="item[1502][additional_data] scustomg" style="width: 100%" onchange="setCustomPrice('price_info_2', this)" id="select-custom-group">
<option value="1" data-price="">Pick a Price</option>
<option value="1" data-price="300.0000">1 - €300.00</option>
<option value="2" data-price="210.0000">2 - €210.00</option>
<option value="4" data-price="189.0000">4 - €189.00</option>
<option value="6" data-price="210.0000">6 - €210.00</option>
<option value="8" data-price="210.0000">8 - €210.00</option>
<option value="9" data-price="0.0000">9 - €0.00</option>
<option value="K" data-price="0.0000">K - €0.00</option>
</select>

<input type="checkbox"  onclick="">
Custom Price*


text:
Q: ASP.NET Core Razor Page multiple path routing I'm building a system using ASP.NET Core 2.0 Razor Pages (not MVC) and I'm having trouble adding multiple routes for pages.  For example, all pages should be able to be reached by abc.com/language/segment/shop/mypage or abc.com/language/shop/mypage, where both paths point to the same page. The segment path section is optional, then the pages do stuff with the optional segment info.
The question mark syntax in the CombineTemplates markup doesn't seem to work, it seems to only work in the last section of the path. Browsing to a url without a value in the {segment?} section resulted in 404.  For example:
AttributeRouteModel.CombineTemplates("{language}/{segment?}/shop", selector.AttributeRouteModel.Template);

I tried code like this below but it only appends the two paths to each other, and I need to be able to enable them both as valid.
options.Conventions.Add(new DefaultPageRouteModelConvention());
options.Conventions.Add(new SegmentPageRouteModelConvention());

In ASP.NET MVC, I could just add two different routes pointing to the same area/controller/action with two different named MapRouteWithName.
Any ideas how to do this with .NET Razor Page syntax?

A: This code works:
Add a single convention (not two different conventions):
options.Conventions.Add(new CombinedPageRouteModelConvention());

In the new convention, add both route selectors:
private class CombinedPageRouteModelConvention : IPageRouteModelConvention
    {
        private const string BaseUrlTemplateWithoutSegment = "{language}/shop";
        private const string BaseUrlTemplateWithSegment = "{language}/{segment}/shop";
        public void Apply(PageRouteModel model)
        {
            var allSelectors = new List<SelectorModel>();
            foreach (var selector in model.Selectors)
            {
                //setup the route with segment
                allSelectors.Add(CreateSelector(selector, BaseUrlTemplateWithSegment));

                //setup the route without segment
                allSelectors.Add(CreateSelector(selector, BaseUrlTemplateWithoutSegment));
            }

            //replace the default selectors with new selectors
            model.Selectors.Clear();
            foreach (var selector in allSelectors)
            {
                model.Selectors.Add(selector);
            }
        }

        private static SelectorModel CreateSelector(SelectorModel defaultSelector, string template)
        {
            var fullTemplate = AttributeRouteModel.CombineTemplates(template, defaultSelector.AttributeRouteModel.Template);
            var newSelector = new SelectorModel(defaultSelector)
            {
                AttributeRouteModel =
                {
                    Template = fullTemplate
                }
            };
            return newSelector;
        }
    }


text:
Q: how to escape * in a script I am trying to write a bash script with a function that executes the following query:
query() {
    cmd="mysql -N -B -u $user -p$password -h $host -e \"$q;\"" #2>&1";
    eval $cmd
}

with
q="select * from mydatabase.mytable"

Upon calling the query, the * character messes everything up and expands to a listing of the current directory.
How can I avoid this? The function should accept any valid SQL statement.

A: Disabling globbing with set -f seems to solve the problem:
query(){
set -f
cmd="mysql -N -B -u $user -p$password -h $host -e \"$q;\"" #2>&1";
echo $cmd
eval $cmd
set +f
}

Is this the best way?


text:
Q: How can I restore my Lenovo T500 to Switchable Graphics without being able to see the screen? I changed my Lenovo T500 from 'Switchable Graphics' to 'Discrete Graphics' in the BIOS.
Now I don't get any display out on the internal LCD, or an external VGA monitor. Not even the POST screen.
How can I revert to Switchable Graphics or Internal Graphics mode?
Even if somebody could just give me BIOS photos I might be able to step through it blind ...

A: Try F1 to enter the BIOS, F9 to load defaults, F10 to save and exit.  Both F9 and F10 will give you a yes/no prompt, but unfortunately I don't know if they default to 'yes' or 'no'.


text:
Q: Dynamically Adding OR to Ruby on Rails Query I have a table that is set up like below. Where the boolean values represent if the student is passing a class:

school_name
student
calculus
chemistry
physics
literature

central
Sam
1
1
1
0

central
Bill
1
0
0
0

central
Sara
0
1
1
0

central
Harry
1
1
1
0

north
Sam
1
1
1
1

north
Fred
1
1
1
1

west
Jim
1
1
1
1

west
Bill
0
1
1
1

The client side will allow the user to select a student name and then let them select which of multiple subjects to look into. (Little strange of a UI I know) Basically, the user might select something like:
The Students named Sam across all the Schools that is passing calculus or passing chemistry or passing literature.
OR the user might select
The Students named Sam across all the Schools that is passing calculus or passing physics.
So basically I don't know what combination of OR operators I will need for the resulting query.
I could use the client's request to dynamically write a sql query and execute it, but I am wondering if there is a more elegant way with Active Record Queries. I can't think of how dynamically tack on more .or to an Active Record Query.
Thanks


text:
Q: Playing .mp3 files with PyAudio Can pyaudio play .mp3 files? If yes, may I ask to write an example please. If no, what is the simplest way to convert .mp3 to .wav?
I have tried to use PyDub, could get my .wav file, but when I try to play it with PyAudio I get following error:
  File "C:\Python33\lib\wave.py", line 130, in initfp
    raise Error('file does not start with RIFF id')
wave.Error: file does not start with RIFF id

With other .wav samples (which where not converted from mp3) if works well.
I am using gTTS library to convert text to speech for my application. It creates short .mp3 files which I need to play then. Right now I am using just
os.system("start english.mp3")

I want to find a better way to do this. First of all I don't want to be restricted about the platform. Secondly, I don't like that the player pops-up when the file begins to play, I'd like it to stay on the background.
I try to find the minimalist solution for this, as I don't need anything more than simple playing.
UPD: I managed to play it with pyglet. Seems fine, except it takes sooo long... I have about 10 seconds delay before I hear the sound. And it doesn't work proper with threading (I want to play the .mp3 while the program is still running).
Is there the way just to make the player stay on the background and not pop-up over all other windows?

A: Here's the short answer:
ffmpeg -i song.mp3 -acodec pcm_u8 -ar 22050 song.wav

TL;DR: I'm assuming you want to play an audio file, without a front-end.
There's a library for that, called The Snack Sound Toolkit which does this beautifully:
player = Sound()
player.read('song.wav')
player.play()

I know I used this with both streams and I think mp3 files, can't remember how or in which project, I might have to look into this though. Think it was mumble related.. anyhow..
If you're completely fine with using a front-end code such as pyglet (which is my pick of the heard), you need some options and some code for this to work as best as possible.
import pyglet
from pyglet.gl import *
pyglet.options['audio'] = ('openal', 'directsound', 'silent')

music = pyglet.resource.media('music.mp3')
music.play()

pyglet.app.run()

Dependencies:
 * OpenAL (for cross-platform compatibility)
Your problem with threading, is that Pyglet is an OpenGL library. Which doesn't take too kindly to Threading at all. Unless you let Pyglet fetch the data you need.
Also, you will most likely bump into the problem of "pyglet blocks my code" (all graphic libraries do. so here's a workaround)
import pyglet, os
from time import sleep
from threading import *
from pyglet.gl import *

pyglet.options['audio'] = ('openal', 'directsound', 'silent')

class worker(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.audio_frames = []
        self.run()

    def add_frame(self, filename):
        self.audio_frames.append(filename)

    def get_frame(self):
         if len(self.audio_frames) > 0:
             return self.audio_frames.pop(0)
         return None

    def run(self):
        while 1:
            for root, folders, files in os.walk('./audio_files/'):
                for f in file:
                    self.add_frame(f)
            sleep(1)

class AudioWindow(pyglet.window.Window):
    def __init__(self):
        self.audio_worker = worker()

    def render(self):
        frame = self.audio_frames.get_frame()
        if frame:
            music = pyglet.resource.media('music.mp3')
            music.play()
    def run(self):
        while self.alive == 1:
            self.render()

        # -----------> This is key <----------
        # This is what replaces pyglet.app.run()
        # but is required for the GUI to not freeze
        #
        event = self.dispatch_events()

This is totally fine, since you're not trying to update THE graphics from another thread.
Instead, you're fetching data on the graphics terms.
You can however from worker() update a variable/list/array/w/e inside AudioWindow() without any problems, the only thing you can't do is call any graphical function from outside the graphic-class.
Without front-end the fun approach:
The most ideal way however, would to be going old-school as hell and use pyaudio and fiddle with audio frames manually. This way you can read literally any audio-file as long as you decode the data properly. I use this one(Tread lightly, cause it ain't pretty) for transporting audio myself:
import pyaudio
import wave

CHUNK_SIZE = 1024
FORMAT = pyaudio.paInt16
RATE = 44100

p = pyaudio.PyAudio()
output = p.open(format=FORMAT,
                        channels=1,
                        rate=RATE,
                        output=True) # frames_per_buffer=CHUNK_SIZE
with open('audio.wav', 'rb') as fh:
    while fh.tell() != FILE_SIZE: # get the file-size from the os module
        AUDIO_FRAME = fh.read(CHUNK_SIZE)
        output.write(AUDIO_FRAME)

This should produce something close to audio :)
The reason why wave is so overutilized in examples etc, is because it's basically a unencoded stream of sound, not encoding in any way. mp3 however is a heavily compressed audio format, format being the key-word here. You need some way of read the mp3 data and reverse it from a compact state into a stream of data which you can squeeze into the speakers.

I'm no audio expert, but this is a rough explanation of how audio works from someone fiddling about with it for a bit and got it working.
Last note:
If you're expecting to play compressed audio-files with Pyglet, you can use AVbin. A library used for compressed files.

A: My gist is here, enjoy
#!/usr/bin/env python3
"""
Play a file continously, and exit gracefully on signal

Based on https://github.com/steveway/papagayo-ng/blob/working_vol/SoundPlayer.py

@author Guy Sheffer (GuySoft) <guysoft at gmail dot com>
"""
import signal
import time
import os
import threading
import pyaudio
from pydub import AudioSegment
from pydub.utils import make_chunks

class GracefulKiller:
    kill_now = False
    def __init__(self):
        signal.signal(signal.SIGINT, self.exit_gracefully)
        signal.signal(signal.SIGTERM, self.exit_gracefully)

    def exit_gracefully(self,signum, frame):
        self.kill_now = True

    def play(self):
        """
        Just another name for self.start()
        """
        self.start()

    def stop(self):
        """
        Stop playback.
        """
        self.loop = False

class PlayerLoop(threading.Thread):
    """
    A simple class based on PyAudio and pydub to play in a loop in the backgound
    """

    def __init__(self, filepath, loop=True):
        """
        Initialize `PlayerLoop` class.

        PARAM:
            -- filepath (String) : File Path to wave file.
            -- loop (boolean)    : True if you want loop playback.
                                False otherwise.
        """
        super(PlayerLoop, self).__init__()
        self.filepath = os.path.abspath(filepath)
        self.loop = loop

    def run(self):
        # Open an audio segment
        sound = AudioSegment.from_file(self.filepath)
        player = pyaudio.PyAudio()

        stream = player.open(format = player.get_format_from_width(sound.sample_width),
            channels = sound.channels,
            rate = sound.frame_rate,
            output = True)

        # PLAYBACK LOOP
        start = 0
        length = sound.duration_seconds
        volume = 100.0
        playchunk = sound[start*1000.0:(start+length)*1000.0] - (60 - (60 * (volume/100.0)))
        millisecondchunk = 50 / 1000.0

        while self.loop:
            self.time = start
            for chunks in make_chunks(playchunk, millisecondchunk*1000):
                self.time += millisecondchunk
                stream.write(chunks._data)
                if not self.loop:
                    break
                if self.time >= start+length:
                    break

        stream.close()
        player.terminate()

    def play(self):
        """
        Just another name for self.start()
        """
        self.start()

    def stop(self):
        """
        Stop playback.
        """
        self.loop = False

def play_audio_background(audio_file):
    """
    Play audio file in the background, accept a SIGINT or SIGTERM to stop
    """
    killer = GracefulKiller()
    player = PlayerLoop(audio_file)
    player.play()
    print(os.getpid())
    while True:
        time.sleep(0.5)
        # print("doing something in a loop ...")
        if killer.kill_now:
            break
    player.stop()
    print("End of the program. I was killed gracefully :)")
    return

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(add_help=True, description="Play a file continously, and exit gracefully on signal")
    parser.add_argument('audio_file', type=str, help='The Path to the audio file (mp3, wav and more supported)')
    args = parser.parse_args()

    play_audio_background(args.audio_file)

A: We can use VLC bindings to support more file formats.
https://gist.github.com/elibroftw/b803191c3b919a67b6a65668572680cc

A: If you're using Windows with Windows Media Player installed here's a simple solution:
wmp = Dispatch('WMPlayer.OCX')
wmp.settings.autoStart = True
wmp.settings.volume = 50
wmp.URL = r"tts_cache\gtts.mp3" #auto-start
while wmp.PlayState != 1: #wait until stopped
    pythoncom.PumpWaitingMessages()
    time.sleep(0.1)
wmp.URL = ""

Unfortunately when i try to replace mp3 file with a new one it sometimes cannot be written. I think WMP blocks it or something. So i decided to create a new file every time and call it "caching".)


text:
Q: Why "-flto" silent GCC's warning "stringop-truncation" I understand that newer GCC versions introduced a warning for possibly wrong string operations "stringop-truncation"
And here's the sample code that I can easily trigger this warning:
$ cat strncpy-warning.cxx
#include <cstring>

extern char g_buf[16];

void mycopy ( const char* src_c_str )
{
    strncpy ( g_buf, src_c_str, sizeof ( g_buf ) );
}

Compile it with the following flags triggers this warning:
$ g++ --version
g++ (GCC) 8.3.0
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

$ g++ -Wall -std=c++14 -Wextra -Werror -O3 -c strncpy-warning.cxx
strncpy-warning.cxx: In function 'void mycopy(const char*)':
strncpy-warning.cxx:7:13: error: 'char* strncpy(char*, const char*, size_t)' specified bound 16 equals destination size [-Werror=stringop-truncation]
     strncpy ( g_buf, src_c_str, sizeof ( g_buf ) );
     ~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
cc1plus: all warnings being treated as errors

Which is expected, however, if I added an -flto to the flags, this warning is gone and the object file is generated:
$ g++ -Wall -std=c++14 -Wextra -Werror -O3 -c strncpy-warning.cxx -flto
$ ls strncpy-warning.o
strncpy-warning.o

Apparently, -flto WILL catch some compile time warnings so not sure why that stringop-truncation is not caught, e.g.:
$ cat strncpy-warning.cxx
#include <cstring>

extern char g_buf[16];

void mycopy ( const char* src_c_str, const char* unused )
{
    strncpy ( g_buf, src_c_str, sizeof ( g_buf ) );
}

$ g++ -Wall -std=c++14 -Wextra -Werror -O3 -c strncpy-warning.cxx -flto
strncpy-warning.cxx: In function 'void mycopy(const char*, const char*)':
strncpy-warning.cxx:5:50: error: unused parameter 'unused' [-Werror=unused-parameter]
 void mycopy ( const char* src_c_str, const char* unused )
                                      ~~~~~~~~~~~~^~~~~~
cc1plus: all warnings being treated as errors

So the question is:

*

*Is this expected behavior?

*I understand that with -flto specified for a source file, GCC will write special things into the resulting object file ( *.o ), but the question is why the warning is skipped by GCC? Is that intentional?

*Is there a way to enable this warning even in case of -flto is given?

*Or does the point-3 above make any sense?

Many thanks!

A: Roughly speaking, GCC has two kinds of warnings:

*

*Warnings generated by simple analysis of the source code

*Warnings generated by complex analysis of data flow

An unused parameter is the first kind: it's trivial to see that a parameter is simply not used in a function.
Incorrect usage of strncpy is, except for trivial cases, the second kind: the compiler needs to understand the relationship between the first and third arguments to strncpy, it needs to know the actual (or at least symbolic) value passed in the third argument, and it needs to know the actual (or at least symbolic) size available in the first argument.
The first kind of warning is generated by the frontend parser. Thus, it always fires.
The second kind is generated by the same component that optimizes the code, because only this component has the necessary information. In -flto mode, this component doesn't run for individual source files.
The second kind also sometimes depends on specific optimizations being performed at all: if you change the optimization level in your first command line to -O1, the warning isn't emitted either.


text:
Q: Pandas: Write CSV file with Windows line ending Example:
import pandas as pd
df = pd.DataFrame({'A':[1,2], 'B':[3,4]})
df.to_csv('test.csv', line_terminator='\r\n')

gives the file
,A,B\r
\r\n
0,1,3\r
\r\n
1,2,4\r
\r\n

however, I would like to have
,A,B\r\n
0,1,3\r\n
1,2,4\r\n

How can I achieve this (i.e., \r\n instead of \r\r\n). My operating system is Windows 10.

A: The following is from a submission to Kaggle. Hope you'll find it useful. I had to write the output loop myself as pandas insisted on adding both CR and LF and it caused problems for Kaagle.
import io

with io.open('../output/submission_{}.csv'.format('22-Sep-2018-Try-Something_with_re'), 'w', newline='\n') as of:
    of.write('fullVisitorId,PredictedLogRevenue\n')
    for ind in out_log.index:
       of.write('{},{}\n'.format(ind, out_log['PredictedLogRevenue'][ind]))

The main things to notice is the use of io.open, setting newline='\n' in the open call, and adding '\n' at the end of each write call.


text:
Q: Php array - merge only specific keys in single array, (
    [0] => Array
        (
            [0] => Array
                (
                    [0] => 1
                    [1] => 2
                )

            [1] => Array
                (
                    [0] => 3
                    [1] => 4
                )
         [2] => Array
                (
                    [0] => 3
                    [1] => 4
                )

        )

)

I want to merge only specific keys as below, Key 0 and 1 are merged as a single array. Like this I want.
In the below example, keys 0 and 1 are merged, it can be changing, so I want custom.. please help me
Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => 1
                    [1] => 2
                    [2] => 3
                    [3] => 4
                )
         [1] => Array
                (
                    [0] => 3
                    [1] => 4
                )

        )

)

A: This script will help you
<?php

$array = [
    [
        [
            1,
            2,
        ],
        [
            3,
            4,
        ],
        [
            3,
            4,
        ]
    ]
];

array_unshift($array[0], array_merge($array[0][0], $array[0][1]));
unset($array[0][1]);
unset($array[0][2]);
print_r($array);

output
Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => 1
                    [1] => 2
                    [2] => 3
                    [3] => 4
                )
            [3] => Array
                (
                    [0] => 3
                    [1] => 4
                )
        )
)

First use array_merge to merge the elements and then use array_unshift to push the new element to array and then use unset to remove the old elements


text:
Q: Azure Active Directory tokens missing App Roles in JWT I have an two applications registered in my Active Directory App registrations, a client and an API. Via the "expose an API" blade, the client app has been trusted by the API app. I have additionally added 4 application roles (IE in the manifest allowedMemberTypes: ["Application"]) to the API app, and added them as permissions to the client app.
When I get an access token via client credential flow, for the client app's appid, and decode the token via jwt.io to see the claims, I can see the roles I assigned to the client app just fine, all in a nice neat array.
However, using auth flow, and logging in as myself (belonging to the directory), using the same secret, scope, client id, etc., the app roles are missing from the token that is sent back with that flow, it is in neither the id token nor the auth token.
What am I missing here? Did I forget a step, or is it that authorization flow does not support application member approles?

A: As the official documentation said:

You can define app roles to target users, applications, or both. When
  available to applications, app roles appear as application permissions
  in the Required Permissions blade.

And, once you've added app roles (with "user" in allowedMemberTypes) in your application, you can assign users and groups to these roles in enterprise app.
If one user is assigned with any roles, you can get roles information in his id token.


text:
Q: Crash on Chrome when writing file on Webgl In Unity3d Webgl I download and write big file (about 100 mb and more) to cache (indexeddb).
I downloaded file with UnityWebRequest and write file in downloadHandler.
Sometimes after call filestream.Write() or filestream.Flush() Chrome will crash.
Exception not available, only crash tab of chrome.
Crash happens abount in 50 percent of dowloads.
public class Downloader : MonoBehaviour
{
    public IEnumerator DownloadFileCoroutine(string url, string filePath,     string clientName, int fileId, Action<int> downloadedCallback)
    {
    var currentWebRequest = UnityWebRequest.Get(url);
    currentWebRequest.downloadHandler = new ToFileDownloadHandler(new byte[64 * 1024], filePath);

    var downloadHendler = (currentWebRequest.downloadHandler as ToFileDownloadHandler);
    currentWebRequest.Send();
    while (!currentWebRequest.isDone && !currentWebRequest.isNetworkError && !currentWebRequest.isHttpError)
    {
        if (currentWebRequest.isNetworkError)
        {
            yield break;
        }
    }

    if (currentWebRequest.isNetworkError)
    {
        downloadHendler.Cancel();
    }
    else
    {
        /// suceess
    }
}

public class ToFileDownloadHandler : DownloadHandlerScript
{
    private int _expected = -1;
    private long _received = 0;
    private readonly string _filepath;
    private readonly FileStream _fileStream = null;
    private bool _canceled = false;

    public ToFileDownloadHandler(byte[] buffer, string filepath) : base(buffer)
    {
        CreateDir();
        _filepath = filepath;
        _fileStream = new FileStream(filepath, FileMode.Create, FileAccess.Write);
    }

    protected override byte[] GetData() { return null; }

    protected override bool ReceiveData(byte[] data, int dataLength)
    {
        if (data == null || data.Length < 1)
        {
            return false;
        }
        _received += dataLength;
        if (!_canceled)
        {
            _fileStream.Write(data, 0, dataLength);
            _fileStream.Flush();
        }
        return true;
    }

    protected override float GetProgress()
    {
        if (_expected < 0) return 0;
        return (float)_received / _expected;
    }

    protected override void CompleteContent()
    {
        _fileStream.Close();
        _isComplete = true;
    }

    protected override void ReceiveContentLength(int contentLength)
    {
        _expected = contentLength;
    }

    public void Cancel()
    {
        if (_canceled) return;
        _canceled = true;
        if (_fileStream != null)
        {
            _fileStream.Close();
        }
        File.Delete(_filepath);
    }

        private void CreateDir()
    {
        cachePath = Application.persistentDataPath;
        if (!Directory.Exists(cachePath))
        {
            Directory.CreateDirectory(cachePath);
        }
    }
}
}


text:
Q: Not able to connect to a Openstack Instance from external machine The IP of of an instance created through Openstack is 10.0.0.2. But when I tried to ping this IP from other machine, it was not successful, however I am able to ping this IP from the machine on which Openstack(Devstack) is installed.
What could be the reason and how to resolved this?

A: This may help you: http://www.liquidstate.net/blog/technology/openstack-havana-home-lab-on-centos6-with-external-networking/
Basically, you need a virtual router to connect from you LAN to OpenStack private network.
I think, you don't need a Floating IP exactly on each instance. Only a virtual router, then you can create a static route on each machine in you LAN, for example:
ip route add 10.0.0.0/8 via 192.168.1.100 dev em1
Good Luck!

A: This IP is a private one, by default, when you deploy a new instance it is deployed with a private IP.
If you want to have a public IP, you need to create a floating IP for your project and afterward, you should assign one IP from this pool to the server instance that you have created previously.
After that you could access to your server instance without any problem.
I hope that it could help you.


text:
Q: Why is LEFT JOIN slower than INNER JOIN? I have two queries, the first one (inner join) is super fast, and the second one (left join) is super slow. How do I make the second query fast?
EXPLAIN SELECT saved.email FROM saved INNER JOIN finished ON finished.email = saved.email;

id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   SIMPLE  finished    index   NULL    email   258 NULL    32168   Using index
1   SIMPLE  saved   ref email   email   383 func    1   Using where; Using index

EXPLAIN SELECT saved.email FROM saved LEFT JOIN finished ON finished.email = saved.email;

id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   SIMPLE  saved   index   NULL    email   383 NULL    40971   Using index
1   SIMPLE  finishedindex   NULL    email   258 NULL    32168   Using index

Edit: I have added table info for both tables down below.
CREATE TABLE `saved` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `slug` varchar(255) DEFAULT NULL,
  `email` varchar(127) NOT NULL,
  [omitted fields include varchar, text, longtext, int],
  PRIMARY KEY (`id`),
  KEY `slug` (`slug`),
  KEY `email` (`email`)
) ENGINE=MyISAM AUTO_INCREMENT=56329 DEFAULT CHARSET=utf8;

CREATE TABLE `finished` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `slug` varchar(255) DEFAULT NULL,
  `submitted` int(11) DEFAULT NULL,
  `status` int(1) DEFAULT '0',
  `name` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  [omitted fields include varchar, text, longtext, int],
  PRIMARY KEY (`id`),
  KEY `assigned_user_id` (`assigned_user_id`),
  KEY `event_id` (`event_id`),
  KEY `slug` (`slug`),
  KEY `email` (`email`),
  KEY `city_id` (`city_id`),
  KEY `status` (`status`),
  KEY `recommend` (`recommend`),
  KEY `pending_user_id` (`pending_user_id`),
  KEY `submitted` (`submitted`)
) ENGINE=MyISAM AUTO_INCREMENT=33063 DEFAULT CHARSET=latin1;

A: I'm afraid more info will probably be needed.
However, inner joins eliminate any item that has a null foreign key (no match, if you will). This means that there are less rows to scan to associate.
For a left join however, any non-match needs to be given a blank row, so all of the rows are scanned regardless -- nothing can be eliminated.
This makes the data set larger and requires more resources to process. Also, when you write your select, don't do select * -- instead, explicitly state which columns you want.

A: With INNER JOIN, MySQL generally will start with the table with the smallest number of rows. In this case, it starts with table finished and does a look up for the corresponding record in saved using the index on saved.email.
For a LEFT JOIN, (excluding some optimizations) MySQL generally joins the records in order (starting with the left most table). In this case, MySQL starts with the table saved, then attempts to find each corresponding record in finished. Since there is no usable index on finished.email, it must do a full scan for each look up.
Edit
Now that you posted your schema, I can see that MySQL is ignoring the index (finished.email) when going from utf8 to latin1 character set. You've not posted the character sets and collations for each column, so I'm going by the default character set for the table. The collations must be compatible in order for MySQL to use the index.
MySQL can coerce (upgrade) a latin1 collation, which is very limited, up to a utf8 collation such as unicode_ci (so the first query can use the index on saved.email by upgrading latin1 collation to utf8), but the opposite is not true (the second query can't use the index on finished.email since it can't downgrade a utf8 collation down to latin1).
The solution is to change both email columns to a compatible collation, perhaps most easily by making them identical character sets and collations.

A: The LEFT JOIN query is slower than the INNER JOIN query because it's doing more work.
From the EXPLAIN output, it looks like MySQL is doing nested loop join. (There's nothing wrong with nested loops; I think that's the only join operation that MySQL uses in version 5.5 and earlier.)
For the INNER JOIN query, MySQL is using an efficient "ref" (index lookup) operation to locate the matching rows.
But for the LEFT JOIN query, it looks like MySQL is doing a full scan of the index to find the matching rows.  So, with the nested loops join operation, MySQL is doing a full index scan scan for each row from the other table. So, that's on the order of tens of thousands of scans, and each of those scans is inspecting tens of thousands of rows.
Using the estimated row counts from the EXPLAIN output, that's going to require (40971*32168=)  1,317,955,128 string comparisons.
The INNER JOIN query avoids a lot of that work, so it's a lot faster. (It's avoiding all those string comparisons by using an index operation.
-- LEFT JOIN
id select table    type   key   key_len ref    rows  Extra
-- ------ -------- -----  ----- ------- ----  -----  ------------------------
1  SIMPLE saved    index  email     383 NULL  40971  Using index
1  SIMPLE finished index  email     258 NULL  32168  Using index

-- INNER JOIN
id select table    type   key   key_len ref    rows  Extra
-- ------ -------- -----  ----- ------- ----  -----  ------------------------
1  SIMPLE finished index  email     258 NULL  32168  Using index
1  SIMPLE saved    ref    email     383 func      1  Using where; Using index
                   ^^^^^                ^^^^  ^^^^^  ^^^^^^^^^^^^

NOTE: Markus Adams spied the difference in characterset in the email columns CREATE TABLE statements that were added to your question.
I believe that it's the difference in the characterset that's preventing MySQL from using an index for your query.

Q2: How do I make the LEFT JOIN query faster?
A: I don't believe it's going to be possible to get that specific query to run faster, without a schema change, such as changing the characterset of the two email columns to match.
The only affect that the "outer join" to the finished table looks like it is to produce "duplicate" rows whenever more than one matching row is found.  I'm not understanding why the outer join is needed. Why not just get rid of it altogether, and just do:
SELECT saved.email FROM saved

A: The data types of saved.email and finished.email differ in two respects.  First, they have different lengths. Second, finished.email can be NULL. So, your LEFT JOIN operation can't exploit the index on finished.email.
Can you change the definition of finished.email to this, so it matches the field you're joining it with?
`email` varchar(127) NOT NULL

If you do you'll probably get a speedup.


text:
Q: iphone navigation model without uinavigation controller? I am writing an app that needs to display a series of approximately 10-20 'views'.  I have 4 view controllers and nibs that I would like to use.  Each view has a forward and back button on it and the views should slide in either from the right or the left depending on the button pushed.  I want to be able to reuse the nibs and controllers to present the information.  I was trying to use a uinavigation controller, but ran into the problem that you can't push a view onto the stack more than once.  The overall structure is a uinavigationcontroller within a tabbarcontroller.   Is there a way to do this with a uinavigation controller, or should I try a different approach.

A: I would suggest making a container view controller class. It would create and "own" the four different view controllers you want to use. Then use something like this to switch between them:
// get the view that's currently showing
UIView *currentView = self.view;
// get the the underlying UIWindow, or the view containing the current view view
UIView *theWindow = [currentView superview];

// remove the current view and replace with newView
[currentView removeFromSuperview];
[theWindow addSubview:newView];

// set up an animation for the transition between the views
CATransition *animation = [CATransition animation];
[animation setDuration:0.5];
[animation setType:kCATransitionPush];
[animation setSubtype:kCATransitionFromLeft];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];

[[theWindow layer] addAnimation:animation forKey:@"SwitchToView1"];

(stolen from here)


text:
Q: No. of question views in Android app There should be an indication about Total Question views, it should be either under Question title or votes.
One more thing, it would be looking good if question views can be accommodated inside every question row in questions list screen.


text:
Q: How to define an Action in an interface How can I define the StateChangedAction in an interface? I have the same Action on different controls, so I would be cleaner to work with a single interface.
Public class MyControl
    Public StateChangedAction As Action(Of ControlState)

    Public Sub New()
    End Sub
End Class


text:
Q: How to show a page loader in laravel after submitting my form How to display a loader after form submit in laravel, i am currently using css for this option...but its not working as expected.
 <button type="submit" id="submit" class="w-full px-3 py-3 font-medium text-white bg-green-400 rounded-lg">Request now</button>

A: Don't know if this is what you need. But I also hope to help you:
<form action="you_action" method="post">
    <button type="submit" id="submit" class="w-full px-3 py-3 font-medium text-white bg-green-400 rounded-lg">Request now</button>
</form>

Method: post or get
Action: Is the link to the page you want to go to when you press submit

A:

document.querySelector(".mybtn").addEventListener('click', myfunction);
var loader = document.querySelector(".myloader");
var contents = document.querySelector(".pageContents");
loader.style.display = "none";

function myfunction() {

  loader.style.display = "block";
  contents.style.display = "none";
}
.myloader {
  position: fixed;
  min-height: 100vh;
  top: 0;
  background-image: url("https://media3.giphy.com/media/KG4PMQ0jyimywxNt8i/giphy.gif?cid=ecf05e47uqzqe9qit5cdf4u7y9fqsw10slzt251h73nx9qri&rid=giphy.gif&ct=g");
  background-repeat: no-repeat;
  background-position: center;
}

.pageContents {
  position: fixed;
  min-height: 100vh;
  top: 0;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" />

    <button type="submit" id="submit" class="m-5 p-2 btn btn-primary rounded-pill mybtn">Request now</button>

Run in fullscreen. To make loading gif to stay longer, use Javascript to set a delay before form submission.


text:
Q: PHP database user selection Alright, so I have setup a very simple login in and sign up database, it is working perfectly.
However, one of the page I have created where users can check their acccount information (Username and Email) is not working fully.
I have a database that has four columns ID, username, email and password.
All I am doing is taking the user information from the database (Who is logged in) and displaying their username and email on the page.
The problem is that the code is logging every user within the database, I only want it to select one user (The user that is logged in.)
Code:
<?php
// SQL query
$strSQL = "SELECT * FROM users";

// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);

// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {

   // Write the value of the column FirstName (which is now in the array $row)
  echo $row['email'] . "<br />";
  echo $_SESSION['username'];

  }

// Close the database connection
mysql_close();
?>

I'm thankful for the help !

A: You probably need to store the username value in a $_SESSION in your login session.
if (!isset($_SESSION)) {
    session_start();
    $_SESSION['id'] = the_id_of_your_logged_username;
}

Then using the value that is stored in the $_SESSION to retrieve the logged user.
session_start();
$id = $_SESSION['id'];
$query = "SELECT * FROM users WHERE id='$id'";

In these way, you can retrieve the logged user, just commonly on how users login and gets their profile directly.

A: Your SQL query should look something like this...
"SELECT * FROM users WHERE ID = '$user_id'"

Remember to fix any SQL vulnerabilities
$user_id = mysql_real_escape_string($user_id);


text:
Q: why I can't get the value when make a jquery/ajax call on link click? In my website I have a  link where user id is store like this :

by <a href="#" onclick="ofUser(<?php echo $uid; ?>, event);"><?php echo $store_name; ?> (<?php echo $no_pro_of_user; ?>)

Here you can see variable $uid. This is the user id. So I want to make ajax call when I click on this link. It's should get the value of $uid to result page ofUser.php. But in result page (ofUser.php) it's showing :
Undefined index: id
Can you tell me how can I solve it ?
Here is the JS offUser function
function ofUser(id, event){
  id = $(id);
  event.preventDefault();
  var formData =  id;
  $.ajax({
    url :  <?php echo "'ofUser.php'"; ?>,
    type : 'POST',
    xhr : function () {
      var myXhr = $.ajaxSettings.xhr();
      return myXhr;
    },
    beforeSend : function () {
      $("#ofUser_message").val("Searching...");
    },
    success : function (data) {
      $("#danger").hide();
      $("#bydault_pagination").hide();
      $("#bydeafult_search").hide();
      $("#ofUser_message").html(data);
    },

    data: formData,
    cache: false,
    contentType: false,
    processData: false
  });
}

offUser.php
echo $uid = (int) $_POST['id'];

A: id = $(id); will cast id to jQuery object which is not making any sense here. It will make id as array(id=$(1) => [1])
Also note, your data being sent over server should be an object.
Try this:

function ofUser(id, event) {
  event.preventDefault();
  $.ajax({
    url: 'ofUser.php',
    type: 'POST',
    xhr: function() {
      var myXhr = $.ajaxSettings.xhr();
      return myXhr;
    },
    beforeSend: function() {
      $("#ofUser_message").val("Searching...");
    },
    success: function(data) {
      $("#danger").hide();
      $("#bydault_pagination").hide();
      $("#bydeafult_search").hide();
      $("#ofUser_message").html(data);
    },

    data: {
      id: id
    },
    cache: false
  });
}

Edit: Remove processData : true as it will send data as DOMDocument

A: Just try to pass  id = id; instead id = $(id); because $(id) means you are trying to get any DOM element values using jQuery, I hope it will work, also tell me that, what HTML is generated for your this code

by <a href="#" onclick="ofUser(<?php echo $uid; ?>, event);"><?php echo $store_name; ?> (<?php echo $no_pro_of_user; ?>)

A: To solve this problem, SIMPLIFY to make sure you are correctly passing the ID value. In your AJAX success function, ALERT the value you send back so you can immediately see what you received in PHP.
Try setting it up this way instead:
html:

by <a id="uid_<?php echo $uid; ?>" href="#" ><?php echo $store_name; ?> (<?php echo $no_pro_of_user; ?>)

javascript:
$('[id^=uid_]').click(function(event){
    event.preventDefault();
    var formData = this.id.split('_')[1];
    $("#ofUser_message").val("Searching...");

    $.ajax({
        type : 'POST',
         url : 'ofUser.php',
        data : id=formData,
        success : function (data) {
            alert(data);
            $("#danger").hide();
            $("#bydault_pagination").hide();
            $("#bydeafult_search").hide();
            $("#ofUser_message").html(data);
        }
    });

});

ofUser.php
$uid = $_POST['id']; //REMOVE the (int) for now, to verify what PHP is receiving - then add it back.
echo 'Received $uid';

Notes:
(1) Note that you misspelled ofUser.php and offUser.php (not sure which is correct - I went with ofUser.php)
(2) Try not to use inline javascript. jQuery is easiest to use when you break out the javascript from the HTML, as per above example.
(3) In above example, the jQuery selector starts with is used:
$('[id^=uid_]').click(function(event){

That code is fired by any element whose ID begins with uid_, as we configured the  tag's ID to appear. That makes it easy to see in your HTML.
(4) This line:
var formData = this.id.split('_')[1];

uses pure javascript to get the ID, because it's faster - and simpler to type. The code splits off the 2nd part of the ID, at the _ char, resulting in just the ID number. That ID number is then assigned to the variable formData
(5) In the AJAX code block, make sure the url is spelled correctly:
url : 'ofUser.php',

Here are some other SIMPLE AJAX examples that might help. Don't just look at them - reproduce them on your server and play with them. They are simple, but you may learn a lot:
AJAX request callback using jQuery

A: When click over any hyperlink then start redirecting to provided URL. so you need to prevent its default action using below code inside your click event handler
event.preventDefault();


text:
Q: Extending/implementing force:slds at component level With Lightning most of my use case has been creating a component and adding it to the Lightning app builder page. I use  just to preview my component behavior from developer console.
Having said this I see developers/salesforce docs load the SLDS as static resource and reference it in components using ltng:require
https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/apps_slds.htm
http://www.sfdcmonkey.com/2016/12/26/use-lightning-design-system-framework/
The major disadvantage I see with this method is getting struck to a specific version and constantly having to update the slds version in the static resource to the latest version from the server.
Is there any way I can extend/ implement the force:slds as an interface at a component level?
For the sake of argument if I use only lightning:XXXX components in my code, I will inherit lightning styling by default but this is not possible all the time. When using ui:XXX and custom html components I will have to use the SLDS as a static resource to apply styling on my non lightning:XXXX components.
Am I missing something basic (or) is loading SLDS as a static resource the only way to use SLDS at a component level?

A: You don't need to load anything. The slds just works by default in lightning
I may be missing some use cases though as I am not sure why there is documentation stating you should extend force:slds when I have never needed to.....


text:
Q: Is it safe to return a vector of std::shared_ptr? Is my code in risk of memory-leak for returning vector of std::shared_ptr? I think it's safe because the reference count will not be zero till the end of main function. Am I right?
#include <iostream>
#include <vector>
#include <memory>

using namespace std;

class A {
    public:
    A(int v):a(v){}
    int a;
};

typedef std::shared_ptr<A> APtr;

vector<APtr> test() {
    APtr x(new A(1));
    APtr y(new A(2));
    APtr z(new A(3));
    APtr a(new A(4));
    return vector<APtr>({x, y, z, a});
}

int main()
{
   cout << "Hello World" << endl;
   vector<APtr> b = test();
   for(auto k : b) {
       cout << k->a << "\n";
   }
   return 0;
}

A: Yes, this is safe and memory-leak free. Your test function creates the pointers, and they'll all have a reference count of one. Once the function returns, they're copied into b which increases the reference count, then they go out of scope and decrease the reference count back down to 1. The A are all cleaned up correctly at the end of main.
Putting a breakpoint (or cout statement) in ~A should also show you this correctly. One final minor note, you should prefer make_shared over new


text:
Q: How to know if a thick lense system is divergent or convergent I know that the sign of the effective focal lenght (f) of a lense will determine if a that lense is divergent(f<0) or convergent(f>0), but with a system made of a combination of thick lenses and thin lenses, that no longer holds true, so how do i know if the system is divergent or convergent? I have heard that it has to do with the principal planes,but i was not able to understand why or how.

A: This method does not use the concept of principal planes, but can be used as a way to find if the system behaves as convergent or divergent
You may try making an image of an object kept at infinity, by the combination.

*

*If the image formed is real, and the image is formed in from of the last - the combination acts as convergent.

*

*If the image formed is virtual, and behind the last lens - the combination is divergent.

This method might be calculation wise a bit long, but it'll work.


text:
Q: JavaFX ignoring backgrounds and fontweights I am in the process of learning basic Java and JavaFX.  I am trying to apply certain styles to a simple program.  I have successfully connected the CSS and SOME styles work and others are ignored.  I am especially having an issue with -fx-background-color and -fx-font-weight, thusly.  The CSS is as follows:
.label{
-fx-font-size: 16px;
-fx-font-weight: bold;
-fx-font-family: Tarazedi;
-fx-text-fill: #FF9900;
}

#h1bar {
-fx-text-fill: #000000;
-fx-effect: dropshadow( gaussian, #000000, 1, 0, 1, 1 );
-fx-background-color: linear-gradient( to right,
                             rgba(255, 153, 0, 1) 0px,
                             rgba(255, 153, 0, 1) 16px,
                             rgba(171, 153, 0, 0.67) 32px,
                             rgba(171, 153, 0, 0.67) 480px,
                             rgba(255, 153, 0, 0.33) 720px,
                             rgba(255, 153, 0, 0) 960px
                           );
-fx-padding: 4px;
-fx-background-radius: 16px;
}

The Java is as follows:
    primaryStage.setTitle("Welcome to tarazedi.com!");                      // Define window and title bar.
    GridPane grid = new GridPane();                                         // Create a GridPane

    grid.setHgap(16);                                                       // Set 10px gridlines.
    grid.setVgap(16);
    grid.setPadding(new Insets(32, 32, 32, 32));                            // TRBL padding.

    Label scenetitle = new Label("\uf0a3  Welcome to tarazedi.com!");
    scenetitle.setId("h1bar");
    grid.add(scenetitle, 0, 0, 2, 1);

    Label userName = new Label("User Name:");
    grid.add(userName, 0, 1);

    TextField userTextField = new TextField();
    grid.add(userTextField, 1, 1);

    Label pw = new Label("Password:");
    grid.add(pw, 0, 2);

    PasswordField pwBox = new PasswordField();
    grid.add(pwBox, 1, 2);

    Button btn = new Button("Sign in");
    HBox hbBtn = new HBox(10);
    hbBtn.setAlignment(Pos.BOTTOM_RIGHT);
    hbBtn.getChildren().add(btn);
    grid.add(hbBtn, 1, 4);

    final Text actiontarget = new Text();
    grid.add(actiontarget, 1, 6);

    btn.setOnAction((ActionEvent e) -> {
        actiontarget.setFill(Color.FIREBRICK);
        actiontarget.setText("Sign in button pressed");
    });

    Scene scene = new Scene(grid, 400, 400);                                // Grid is the root node.
    primaryStage.setScene(scene);                                           // Display it.
    scene.getStylesheets().add(VictorSheckelsFX.class.getResource("VictorStyle.css").toExternalForm());
    primaryStage.show();

The expected behavior would cause the header bar to look roughly like the orange bars on my site: http://victorsheckels.com/. Instead I have solid orange bars, no dropshadow, and no boldness on my font.  The font size, family, and color are WAI as are the padding and radius.

A: Use percentages instead of pixels. JavaFX does not support non-percentage stops as reported here
For example:
-fx-background-color: linear-gradient(to right,
rgba(255, 153, 0, 1) 0%,
rgba(255, 153, 0, 1) 1.6%,
rgba(171, 153, 0, 0.67) 3.3%,
rgba(171, 153, 0, 0.67) 50%,
rgba(255, 153, 0, 0.33) 75%,
rgba(255, 153, 0, 0) 100%);


text:
Q: Div passing full width of parent div Hello I have a daughter div that is passing the full width of the parent div for some reason I still can't find the solution:
like this:

for some reason instead of skipping paragraph it is always horizontal I've tried everything and found no solution.
code:
<Styled.ChatBox>
 <Styled.ChatLog>
    <Styled.MessageWrapper user={true}>
      <Styled.ChatMessage user={true}>{props.children}</Styled.ChatMessage>
    </Styled.MessageWrapper>
 </Styled.ChatLog>
</Styled.ChatBox>

css:
const messageBot = css`
  align-self: flex-start;
  background-color: #e0e0e0;
  color: black;
  border-radius: 8px;
  padding: 10px 10px 10px 15px;
  font-size: 15px;
  font-family: sans-serif;
`;
const messageClient = css`
  align-self: flex-end;
  background-color: #1a6fe8;
  color: white;
  border-radius: 8px;
  padding: 10px 10px 10px 15px;
  font-size: 15px;
  font-family: sans-serif;
`;
const ChatBox = styled.div`
  display: ${props => (props.widget ? 'none' : 'flex')};
  position: absolute;
  position: fixed;
  right: 20px;
  bottom: 20px;
  flex-direction: column;
  max-width: 22em;
  width: 100%;
  height: 30em;
  border-radius: 6px;
  box-shadow: rgba(0, 0, 0, 0.5) 0px 0px 10px 2px;
  background: ${props => (props.widget ? 'red' : 'blue')};
`;
const ChatLog = styled.div`
  display: flex;
  flex-direction: column;
  max-height: 400px;
  width: 100%;
  overflow-y: auto;
  flex: 1 100%;
  background: red;
  padding: 10px 10px 0px 10px;
  box-sizing: border-box;
`;
const MessageWrapper = styled.div`
  background: yellow;
  display: flex;
  align-items: center;
  flex-direction: row;
  box-sizing: border-box;
  width: 100%;
  justify-content: ${props => (props.user ? 'flex-end' : 'flex-start')};
`;
const ChatMessage = styled.div`
  position: relative;
  margin: 1ex;
  padding: 1ex;
  border-radius: 2px;
  :before {
    content: '';
    position: absolute;
    top: 50%;
    right: ${props => (props.user ? '-5px' : '')};
    left: ${props => (props.user ? '' : '1px')};
    height: 15px;
    width: 15px;
    background: ${props => (props.user ? '#1a6fe8' : '#e0e0e0')};
    transform: rotate(45deg);
    transform-origin: top right;
  }
  ${props => (props.user ? messageClient : messageBot)}
`;

I know that my div that is passing the size is ChatMessage
I believe she is the problem
img:

example on:
https://codesandbox.io/s/cool-water-1dwqx

A: You need to handle the overflow of the element.
const ChatMessage = styled.div`
  ...
  overflow: hidden;
  word-break: break-all;
`;


text:
Q: Открыть внешнее приложение внутри своего. C++, Qt Я бы хотел открывать windows приложения внутри своего, для примера можно взять тот же калькулятор или блокнот. Насколько я помню, я запускал приложение, а после, по хэндлу окна, пытался перенести его внутрь моего. В итоге я просто куда-то терял окно приложения, но при этом процесс оставался в памяти. Использовал я createWindowContainer, если не ошибаюсь. Если можно, хотелось бы увидеть минимальный рабочий пример запуска калькулятора внутри своего Qt приложения.

A: Используйте QX11EmbedContainer.
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    if (app.arguments().count() != 2) {
        qFatal("Error - expected executable path as argument");
        return 1;
    }

    QX11EmbedContainer container;
    container.show();

    QProcess process(&container);
    QString executable(app.arguments()[1]);
    QStringList arguments;
    arguments << QString::number(container.winId());
    process.start(executable, arguments);

    int status = app.exec();
    process.close();
    return status;
}


text:
Q: Pearson's independence test I know that for I*J contingency tables, Pearson's test of independence the distribution under null is $\chi^2((I-1)(J-1))$. I am curious why it is the case and no books I see seems to prove this.
You can just give me a link or book/paper names if you have that. I know that by a direct application of multivariate CLT we can test $p=p_0$ for the ($IJ$) cells and the test statistic follows $\chi^2(IJ-1)$.
To be clear, I know intuitive explanation like 'estimating k variables reduces k degree of freedom' and that's not something I want.

A: I don't think that you will find an elementary proof anywhere, because a rigorous proof is quite hard. Here is an outline of how the proof goes---as far as I know it has not been published anywhere.
The key part of the proof is to show that Pearson's statistic is a score test statistic. (In theoretical statistics, a score test statistic is one based on the log-likelihood derivatives.) Specifically, let $y_{ij}$, $i=1,\ldots,I$, $j=1,\ldots,J$ be the table of counts. We assume that the $y_{ij}$ are Poisson distributed with means $\mu_{ij}$ given by the log-linear model
$$\log\mu_{ij}=\mu_0+\alpha_i+\beta_j$$
where the $\alpha_i$ and $\beta_j$ are row and column effects respectively. Then Pearson's statistic for independence can be shown to be equal to the score test statistic for testing the above log-linear model vs the saturated model in which all the $\mu_{ij}$ are different. The statistic is on $(I-1)(J-1)$ degrees of freedom because that is the difference in the number of parameters in the two models. The proof that Pearson's statistic is a score test is harder than one might expect, and is given here:
http://www.statsci.org/smyth/pubs/goodness.pdf
Finally, the chisquare distribution for the statistic is proved by showing that the log-likelihood derivatives are asymptotically normal as the means $\mu_{ij}$ become large.


text:
Q: Why would jQuery prependTo duplicate the element(s) I'm moving? tl;dr: Here is a recording of my problem where I set a breakpoint, reload the page and step through the code: http://recordit.co/uNtqr31G0e
I created this code a few weeks ago and it's been working perfectly, but after checking the website today (and messing with some unrelated owl-carousel JavaScript) any elements on our product page moved with insertAfter or prependTo are showing twice in the new location once the JavaScript executes. This was working perfectly yesterday though.
Embedded is the stripped down version of the code from the product page that I'm modifying, but the code works fine using StackOverflows code editor & Codepen.io

$(document).ready(function() {
  var shoppingCartIcon = $('.describe-list-icon .fa-shopping-cart');
        var pricingDescribeList = shoppingCartIcon.closest('.describe-list');
        pricingDescribeList.addClass('pricing');
        pricingDescribeList.prependTo('.content');
});

$229.99

<div id="book_button_partyz_id_73847" class="button_book" style="cursor:pointer; display:inline-block" onclick="if(navigator.cookieEnabled){if(typeof last_item_container_id != "undefined") { document.getElementById("container_" + last_item_container_id).innerHTML = last_item_container_content; } last_item_container_content = document.getElementById("container_partyz_id_73847").innerHTML; last_item_container_id = "partyz_id_73847"; document.getElementById("container_partyz_id_73847").innerHTML = "

"; ajax_link("item_container","store.item.calendar?root_path=&responsive=1&show_instructions=1&show_start_form=1&itemid=partyz_id_73847","post_info=1"); this.style.display = "none";}else{alert("Cookies are not enabled.  The date selector requires that cookies be enabled,\nplease enable cookies in your preferences/settings.");}"><nobr>Add to Cart</nobr>

Codepen Link: https://codepen.io/CodeBradley/pen/oMYzoB
The product page I'm referring to: https://partyz.ourers.com/items/dunk_tank/
The actual JavaScript:
https://files.sysers.com/cp/upload/partyz/editor/full/main.js


text:
Q: Dockerfile CMD unable to locate entrypoint file I have a dockerfile that ends with
COPY ./entrypoint.sh /usr/local/bin
RUN chmod +x /usr/local/bin/entrypoint.sh

CMD /usr/local/bin/entrypoint.sh

but after building the image, when I try to run it, I get
/bin/sh: /usr/local/bin/entrypoint.sh: not found

If I change the last line to
CMD ls -l /usr/local/bin/

when I run the image, I get the output
-rwxr-xr-x    1 root     root           484 Jul 21 13:07 entrypoint.sh

which shows that the entrypoint.sh file is actually in the directory.
When I use docker export to export the filesystem of the container after running it, I can also find the entrypoint.sh file in /usr/local/bin/
I'm not sure what's causing the entrypoint.sh file to not be found, any help would be much appreciated.

A: I was using windows to write the entrypoint.sh file.
As octagon_octopus suggested, changing the line breaks of the entrypoint.sh file from CRLF to LF fixed the issue!

A: I'm not sure what you're trying to do with your container, but have you tried swapping CMD for ENTRYPOINT in your Dockerfile?
Another thing worth trying is to specify that you want to run the file with shell
CMD ["/bin/sh", "/usr/local/bin/entrypoint.sh"]
I'd suggest having a look at this


text:
Q: is there any inmemmory MapReduce techniques in opensource I am trying to find techniques to make hadoop faster.Is there any 'inmemory hadoop mapreduce' techniques in 'open source' like gridgain? For gridgain i am only able to download evaluation version.

A: You might be looking for Apache Spark.
To run programs faster, Spark offers a general execution model
that can optimize arbitrary operator graphs, and supports in-memory
computing, which lets it query data faster than disk-based engines like Hadoop.

It is a bit different to code though, as it was mainly designed for Scala. So you don't write map and reduce functions anymore, but declaratively build blocks of your computations- thus Spark is a lot more flexible than MapReduce.
Let's take a look at WordCount, the Java version looks a bit verbose:
 JavaPairRDD<String, Integer> ones = words.map(new PairFunction<String, String, Integer>() {
      public Tuple2<String, Integer> call(String s) {
        return new Tuple2<String, Integer>(s, 1);
      }
    });

    JavaPairRDD<String, Integer> counts = ones.reduceByKey(new Function2<Integer, Integer, Integer>() {
      public Integer call(Integer i1, Integer i2) {
        return i1 + i2;
      }
    });

Maybe it will get better with the Java 8 features.
In Scala it is much more compact:
val file = spark.textFile("hdfs://...")
val counts = file.flatMap(line => line.split(" "))
                  .map(word => (word, 1))
                  .reduceByKey(_ + _)
counts.saveAsTextFile("hdfs://...")


text:
Q: 'uninitialized constant SubcategoriesController' - Rails I have a SubcategoriesController
class Categories::SubcategoriesController < ApplicationController
  def new
    @category = Category.find(params[:category_id])
    @subcategory = Subcategory.new
  end

  def edit
  end

  def create
  end

  def destroy
  end
end

These are my routes
resources :categories do
    resources :subcategories, except: [:index, :show]
  end

When I'm trying to visit categories_path, it throws uninitialized constant SubcategoriesController
Where did I go wrong?

A: Current route configuration expects to find SubcategoriesController in app/controllers/subcategories_controller.rb, but you have declared Categories::SubcategoriesController (perhaps in app/controllers/categories/subcategories_controller.rb).
Try moving and renaming the controller so router can find it.
Hope that helps!


text:
Q: Can someone explain this project to me? Can you explain the schematic so I understand how it works? https://electronicsprojectshub.com/how-to-make-an-automatic-night-light-using-ldr/
Can someone explain this project to me? Can you explain the schematic so I understand how it works? A very very simple explanation please. I will be starting my electronics degree soon and I just wanted to get ahead so assume I know nothing except the real bare basics.
Circuit:

A: I was going to say "read the description on the page you linked to", but the description there is wrong. (don't believe everything you see on the Internet!)
An LDR will have a high resistance in the dark, and low in light.
If light hits the LDR, it will have a low resistance, pulling Q1's base up.  Q1 will turn on, pulling its collector, and Q2's base low, so Q2 will be off, and the relay will be released, turning the light off.
If the LDR is in the dark, it will have high resistance, allowing Q1 to turn off, so Q1's collector and Q2's base go high, pulling Q2's collector low and turning the relay on.

A: The first thing I recommend you is "test the LDR yourself". The internet is a good place to get ideas but I suggest you not to blindly follow those instructions.
In case of this project,the LDR explained totally wrong. Grab a LDR, a multimeter and measure its resistance in different lighting conditions.
In the circuit, I can see the transistor Q1 being operated in voltage divider configuration. The LDR and resistor R3 forms a voltage divider. So high resistance in LDR means higher drop in voltage at LDR which eventually means low voltage remaining for the R3 resistor. This voltage is also the base voltage. Lower base voltage means the transistor is in off state. So the transistor's collector is high (not due to weed). This  again implies that the base of Q2 is high and Q2 is switched on. So the collector is low and the relay is turned on.
In case the LDR drops low voltage, more of the supply voltage is remaining for the R3. This higher voltage across R3 causes base of Q1 to go high and Q1 is switched on. The collector of Q1 goes low and the base of Q2 is low. So, the transistor Q2 is switched off and the collector of Q2 goes high. The relay is now switched off.
After making this circuit and seeing the outcome, interchange the position of the LDR and R3 resistor. And see the outcome.