Programs & Examples On #Compound index

Find files and tar them (with spaces)

There could be another way to achieve what you want. Basically,

  1. Use the find command to output path to whatever files you're looking for. Redirect stdout to a filename of your choosing.
  2. Then tar with the -T option which allows it to take a list of file locations (the one you just created with find!)

    find . -name "*.whatever" > yourListOfFiles
    tar -cvf yourfile.tar -T yourListOfFiles
    

Correctly determine if date string is a valid date in that format

I'm afraid that most voted solution (https://stackoverflow.com/a/19271434/3283279) is not working properly. The fourth test case (var_dump(validateDate('2012-2-25')); // false) is wrong. The date is correct, because it corresponds to the format - the m allows a month with or without leading zero (see: http://php.net/manual/en/datetime.createfromformat.php). Therefore a date 2012-2-25 is in format Y-m-d and the test case must be true not false.

I believe that better solution is to test possible error as follows:

function validateDate($date, $format = 'Y-m-d') {
    DateTime::createFromFormat($format, $date);
    $errors = DateTime::getLastErrors();

    return $errors['warning_count'] === 0 && $errors['error_count'] === 0;
}

textarea's rows, and cols attribute in CSS

<textarea rows="4" cols="50"></textarea>

It is equivalent to:

textarea {
    height: 4em;
    width: 50em;
}

where 1em is equivalent to the current font size, thus make the text area 50 chars wide. see here.

Move to another EditText when Soft Keyboard Next is clicked on Android

If you have the element in scroll view then you can also solve this issue as :

<com.google.android.material.textfield.TextInputEditText
                android:id="@+id/ed_password"
                android:inputType="textPassword"
                android:focusable="true"
                android:imeOptions="actionNext"
                android:nextFocusDown="@id/ed_confirmPassword" />

and in your activity:

edPassword.setOnEditorActionListener(new EditText.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_NEXT) {
                focusOnView(scroll,edConfirmPassword);
                return true;
            }
            return false;
        }
    });

public void focusOnView(ScrollView scrollView, EditText viewToScrollTo){
    scrollView.post(new Runnable() {
        @Override
        public void run() {
            scrollView.smoothScrollTo(0, viewToScrollTo.getBottom());
            viewToScrollTo.requestFocus();
        }
    });
}

Get Line Number of certain phrase in file Python

for n,line in enumerate(open("file")):
    if "pattern" in line: print n+1

How to change the default encoding to UTF-8 for Apache?

This is untested but will probably work.

In your .htaccess file put:

<Files ~ "\.html?$">  
     Header set Content-Type "text/html; charset=utf-8"
</Files>

However, this will require mod_headers on the server.

Display names of all constraints for a table in Oracle SQL

Use either of the two commands below. Everything must be in uppercase. The table name must be wrapped in quotation marks:

--SEE THE CONSTRAINTS ON A TABLE
SELECT COLUMN_NAME, CONSTRAINT_NAME FROM USER_CONS_COLUMNS WHERE TABLE_NAME = 'TBL_CUSTOMER';

--OR FOR LESS DETAIL
SELECT CONSTRAINT_NAME FROM USER_CONSTRAINTS WHERE TABLE_NAME = 'TBL_CUSTOMER';

Javascript to export html table to Excel

For UTF 8 Conversion and Currency Symbol Export Use this:

var tableToExcel = (function() {
  var uri = 'data:application/vnd.ms-excel;base64,'
    , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><?xml version="1.0" encoding="UTF-8" standalone="yes"?><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
    , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
    , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
  return function(table, name) {
      if (!table.nodeType) table = document.getElementById(table)
      var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
    window.location.href = uri + base64(format(template, ctx))
  }
})()

How to display an image stored as byte array in HTML/JavaScript?

Try putting this HTML snippet into your served document:

<img id="ItemPreview" src="">

Then, on JavaScript side, you can dynamically modify image's src attribute with so-called Data URL.

document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;

Alternatively, using jQuery:

$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);

This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..." part) in the URL accordingly.

Similar Questions:

Ruby objects and JSON serialization (without Rails)

Jbuilder is a gem built by rails community. But it works well in non-rails environments and have a cool set of features.

# suppose we have a sample object as below
sampleObj.name #=> foo
sampleObj.last_name #=> bar

# using jbuilder we can convert it to json:
Jbuilder.encode do |json|
  json.name sampleObj.name
  json.last_name sampleObj.last_name
end #=> "{:\"name\" => \"foo\", :\"last_name\" => \"bar\"}"

Running a Python script from PHP

To clarify which command to use based on the situation

exec() - Execute an external program

system() - Execute an external program and display the output

passthru() - Execute an external program and display raw output

Source: http://php.net/manual/en/function.exec.php

Why is $$ returning the same id as the parent process?

$$ is defined to return the process ID of the parent in a subshell; from the man page under "Special Parameters":

$ Expands to the process ID of the shell. In a () subshell, it expands to the process ID of the current shell, not the subshell.

In bash 4, you can get the process ID of the child with BASHPID.

~ $ echo $$
17601
~ $ ( echo $$; echo $BASHPID )
17601
17634

How to inspect Javascript Objects

Use your console:

console.log(object);

Or if you are inspecting html dom elements use console.dir(object). Example:

let element = document.getElementById('alertBoxContainer');
console.dir(element);

Or if you have an array of js objects you could use:

console.table(objectArr);

If you are outputting a lot of console.log(objects) you can also write

console.log({ objectName1 });
console.log({ objectName2 });

This will help you label the objects written to console.

Detect click event inside iframe

I know this is old but the ID's don't match in your code one is choose_pic and one is choose_pics:

<input type=button id=choose_pics value='Choose'>

$("#filecontainer").contents().find("#choose_pic").click(function(){
    //do something      
}); 

NPM doesn't install module dependencies

I suspect you're facing the issue where your package.json file is not in the same directory as your Gruntfile.js. When you run your grunt xxx commands, you get error an message like:

Local Npm module "xxx" not found. Is it installed?

For now, the solution is:

  • Create package.json in the same directory as Gruntfile.js
  • Define the modules required by your grunt project
  • Execute npm install to load them locally
  • Now the required grunt command should work.

IMHO, it is sad that we cannot have grunt resolve modules loaded from a parent npm module (i.e. package.json in a parent directory within the same project). The discussion here seems to indicate that it was done to avoid loading "global" modules but I think what we want is loading from "my project" modules instead.

Activity <App Name> has leaked ServiceConnection <ServiceConnection Name>@438030a8 that was originally bound here

You mention the user switching between Activities pretty quickly. Could it be that you're calling unbindService before the service connection has been established? This may have the effect of failing to unbind, then leaking the binding.

Not entirely sure how you could handle this... Perhaps when onServiceConnected is called you could call unbindService if onDestroy has already been called. Not sure if that'll work though.


If you haven't already, you could add an onUnbind method to your service. That way you can see exactly when your classes unbind from it, and it might help with debugging.

@Override
public boolean onUnbind(Intent intent) {
    Log.d(this.getClass().getName(), "UNBIND");
    return true;
}

Hide/Show Action Bar Option Menu Item for different fragments

Hello I got the best solution of this, suppose if u have to hide a particular item at on create Menu method and show that item in other fragment. I am taking an example of two menu item one is edit and other is delete. e.g menu xml is as given below:

sell_menu.xml

 <?xml version="1.0" encoding="utf-8"?>
 <menu xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto">

<item
    android:id="@+id/action_edit"
    android:icon="@drawable/ic_edit_white_shadow_24dp"
    app:showAsAction="always"
    android:title="Edit" />

<item
    android:id="@+id/action_delete"
    android:icon="@drawable/ic_delete_white_shadow_24dp"
    app:showAsAction="always"
    android:title="Delete" />

Now Override the two method in your activity & make a field variable mMenu as:

  private Menu mMenu;         //  field variable    


  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.sell_menu, menu);
    this.mMenu = menu;

    menu.findItem(R.id.action_delete).setVisible(false);
    return super.onCreateOptionsMenu(menu);
  }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.action_delete) {
       // do action
        return true;
    } else if (item.getItemId() == R.id.action_edit) {
      // do action
        return true;
    }

    return super.onOptionsItemSelected(item);
 }

Make two following method in your Activity & call them from fragment to hide and show your menu item. These method are as:

public void showDeleteImageOption(boolean status) {
    if (menu != null) {
        menu.findItem(R.id.action_delete).setVisible(status);
    }
}

public void showEditImageOption(boolean status) {
    if (menu != null) {
        menu.findItem(R.id.action_edit).setVisible(status);
    }
}

That's Solve from my side,I think this explanation will help you.

How to disassemble a binary executable in Linux to get the assembly code?

An interesting alternative to objdump is gdb. You don't have to run the binary or have debuginfo.

$ gdb -q ./a.out 
Reading symbols from ./a.out...(no debugging symbols found)...done.
(gdb) info functions 
All defined functions:

Non-debugging symbols:
0x00000000004003a8  _init
0x00000000004003e0  __libc_start_main@plt
0x00000000004003f0  __gmon_start__@plt
0x0000000000400400  _start
0x0000000000400430  deregister_tm_clones
0x0000000000400460  register_tm_clones
0x00000000004004a0  __do_global_dtors_aux
0x00000000004004c0  frame_dummy
0x00000000004004f0  fce
0x00000000004004fb  main
0x0000000000400510  __libc_csu_init
0x0000000000400580  __libc_csu_fini
0x0000000000400584  _fini
(gdb) disassemble main
Dump of assembler code for function main:
   0x00000000004004fb <+0>:     push   %rbp
   0x00000000004004fc <+1>:     mov    %rsp,%rbp
   0x00000000004004ff <+4>:     sub    $0x10,%rsp
   0x0000000000400503 <+8>:     callq  0x4004f0 <fce>
   0x0000000000400508 <+13>:    mov    %eax,-0x4(%rbp)
   0x000000000040050b <+16>:    mov    -0x4(%rbp),%eax
   0x000000000040050e <+19>:    leaveq 
   0x000000000040050f <+20>:    retq   
End of assembler dump.
(gdb) disassemble fce
Dump of assembler code for function fce:
   0x00000000004004f0 <+0>:     push   %rbp
   0x00000000004004f1 <+1>:     mov    %rsp,%rbp
   0x00000000004004f4 <+4>:     mov    $0x2a,%eax
   0x00000000004004f9 <+9>:     pop    %rbp
   0x00000000004004fa <+10>:    retq   
End of assembler dump.
(gdb)

With full debugging info it's even better.

(gdb) disassemble /m main
Dump of assembler code for function main:
9       {
   0x00000000004004fb <+0>:     push   %rbp
   0x00000000004004fc <+1>:     mov    %rsp,%rbp
   0x00000000004004ff <+4>:     sub    $0x10,%rsp

10        int x = fce ();
   0x0000000000400503 <+8>:     callq  0x4004f0 <fce>
   0x0000000000400508 <+13>:    mov    %eax,-0x4(%rbp)

11        return x;
   0x000000000040050b <+16>:    mov    -0x4(%rbp),%eax

12      }
   0x000000000040050e <+19>:    leaveq 
   0x000000000040050f <+20>:    retq   

End of assembler dump.
(gdb)

objdump has a similar option (-S)

Changing width property of a :before css selector using JQuery

Pseudo-elements are not part of the DOM, so they can't be manipulated using jQuery or Javascript.

But as pointed out in the accepted answer, you can use the JS to append a style block which ends of styling the pseudo-elements.

Correct use of transactions in SQL Server

At the beginning of stored procedure one should put SET XACT_ABORT ON to instruct Sql Server to automatically rollback transaction in case of error. If ommited or set to OFF one needs to test @@ERROR after each statement or use TRY ... CATCH rollback block.

Sublime text 3. How to edit multiple lines?

Thank you for all answers! I found it! It calls "Column selection (for Sublime)" and "Column Mode Editing (for Notepad++)" https://www.sublimetext.com/docs/3/column_selection.html

How do I drop a foreign key constraint only if it exists in sql server?

Ok, I know I'm late to the party, but here is the syntax I think is best. Add a schema name if needed to the OBJECT_ID clause.

IF OBJECTPROPERTY(OBJECT_ID(N'My_FK_name'),'IsConstraint') =1
ALTER TABLE dbo.TableName DROP CONSTRAINT My_FK_name

How to list all dates between two dates

Create a stored procedure that does something like the following:

declare @startDate date;
declare @endDate date;

select @startDate = '20150528';
select @endDate = '20150531';

with dateRange as
(
  select dt = dateadd(dd, 1, @startDate)
  where dateadd(dd, 1, @startDate) < @endDate
  union all
  select dateadd(dd, 1, dt)
  from dateRange
  where dateadd(dd, 1, dt) < @endDate
)
select *
from dateRange

SQL Fiddle with demo.

Or better still create a calendar table and just select from that.

importing external ".txt" file in python

numpy's genfromtxt or loadtxt is what I use:

import numpy as np
...
wordset = np.genfromtxt(fname='words.txt')

This got me headed in the right direction and solved my problem.

Load text file as strings using numpy.loadtxt()

There is also read_csv in Pandas, which is fast and supports non-comma column separators and automatic typing by column:

import pandas as pd
df = pd.read_csv('your_file',sep='\t')

It can be converted to a NumPy array if you prefer that type with:

import numpy as np
arr = np.array(df)

This is by far the easiest and most mature text import approach I've come across.

Setting Android Theme background color

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="android:Theme.Holo.NoActionBar">
        <item name="android:windowBackground">@android:color/black</item>
    </style>

</resources>

Launch Bootstrap Modal on page load

Update 2020 - Bootstrap 4

The modal markup has changed slightly for Bootstrap 4. Here's how you can open the modal on page load, and optionally delay display of the modal...

$(window).on('load',function(){
    var delayMs = 1500; // delay in milliseconds

    setTimeout(function(){
        $('#myModal').modal('show');
    }, delayMs);
});    

<div class="modal fade" id="myModal">
      <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">My Modal</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">
                    ...
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary mx-auto" data-dismiss="modal">Close</button>
                </div>
            </div>
      </div>
</div>

Demo on Codeply

Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT

I've combine multiple answers into one working solution that results with file path

Mime type is irrelevant for the example purpose.

            Intent intent;
            if(Build.VERSION.SDK_INT >= 19){
                intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false);
                intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
            }else{
                intent = new Intent(Intent.ACTION_GET_CONTENT);
            }
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setType("application/octet-stream");
            if(isAdded()){
                startActivityForResult(intent, RESULT_CODE);
            }

Handling result

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if( requestCode == RESULT_CODE && resultCode == Activity.RESULT_OK) {
        Uri uri = data.getData();
        if (uri != null && !uri.toString().isEmpty()) {
            if(Build.VERSION.SDK_INT >= 19){
                final int takeFlags = data.getFlags() & Intent.FLAG_GRANT_READ_URI_PERMISSION;
                //noinspection ResourceType
                getActivity().getContentResolver()
                        .takePersistableUriPermission(uri, takeFlags);
            }
            String filePath = FilePickUtils.getSmartFilePath(getActivity(), uri);
            // do what you need with it...
        }
    }
}

FilePickUtils

import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

public class FilePickUtils {
    private static String getPathDeprecated(Context ctx, Uri uri) {
        if( uri == null ) {
            return null;
        }
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = ctx.getContentResolver().query(uri, projection, null, null, null);
        if( cursor != null ){
            int column_index = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }
        return uri.getPath();
    }

    public static String getSmartFilePath(Context ctx, Uri uri){

        if (Build.VERSION.SDK_INT < 19) {
            return getPathDeprecated(ctx, uri);
        }
        return  FilePickUtils.getPath(ctx, uri);
    }

    @SuppressLint("NewApi")
    public static String getPath(final Context context, final Uri uri) {
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[] {
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context The context.
     * @param uri The Uri to query.
     * @param selection (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

}

Check if property has attribute

There's no fast way to retrieve attributes. But code ought to look like this (credit to Aaronaught):

var t = typeof(YourClass);
var pi = t.GetProperty("Id");
var hasIsIdentity = Attribute.IsDefined(pi, typeof(IsIdentity));

If you need to retrieve attribute properties then

var t = typeof(YourClass);
var pi = t.GetProperty("Id");
var attr = (IsIdentity[])pi.GetCustomAttributes(typeof(IsIdentity), false);
if (attr.Length > 0) {
    // Use attr[0], you'll need foreach on attr if MultiUse is true
}

Create excel ranges using column numbers in vba?

To reference range of cells you can use Range(Cell1,Cell2), sample:

Sub RangeTest()
  Dim testRange As Range
  Dim targetWorksheet As Worksheet
  
  Set targetWorksheet = Worksheets("MySheetName")
  
  With targetWorksheet
    .Cells(5, 10).Select 'selects cell J5 on targetWorksheet
    Set testRange = .Range(.Cells(5, 5), .Cells(10, 10))
  End With
  
  testRange.Select 'selects range of cells E5:J10 on targetWorksheet
  
End Sub

enter image description here

delete_all vs destroy_all?

You are right. If you want to delete the User and all associated objects -> destroy_all However, if you just want to delete the User without suppressing all associated objects -> delete_all

According to this post : Rails :dependent => :destroy VS :dependent => :delete_all

  • destroy / destroy_all: The associated objects are destroyed alongside this object by calling their destroy method
  • delete / delete_all: All associated objects are destroyed immediately without calling their :destroy method

How to create a timer using tkinter?

from tkinter import *
import time
tk=Tk()
def clock():
    t=time.strftime('%I:%M:%S',time.localtime())
    if t!='':
        label1.config(text=t,font='times 25')
    tk.after(100,clock)
label1=Label(tk,justify='center')
label1.pack()
clock()
tk.mainloop()

How to capture a list of specific type with mockito

I had the same issue with testing activity in my Android app. I used ActivityInstrumentationTestCase2 and MockitoAnnotations.initMocks(this); didn't work. I solved this issue with another class with respectively field. For example:

class CaptorHolder {

        @Captor
        ArgumentCaptor<Callback<AuthResponse>> captor;

        public CaptorHolder() {
            MockitoAnnotations.initMocks(this);
        }
    }

Then, in activity test method:

HubstaffService hubstaffService = mock(HubstaffService.class);
fragment.setHubstaffService(hubstaffService);

CaptorHolder captorHolder = new CaptorHolder();
ArgumentCaptor<Callback<AuthResponse>> captor = captorHolder.captor;

onView(withId(R.id.signInBtn))
        .perform(click());

verify(hubstaffService).authorize(anyString(), anyString(), captor.capture());
Callback<AuthResponse> callback = captor.getValue();

Laravel Mail::send() sending to multiple to or bcc addresses

the accepted answer does not work any longer with laravel 5.3 because mailable tries to access ->email and results in

ErrorException in Mailable.php line 376: Trying to get property of non-object

a working code for laravel 5.3 is this:

$users_temp = explode(',', '[email protected],[email protected]');
    $users = [];
    foreach($users_temp as $key => $ut){
      $ua = [];
      $ua['email'] = $ut;
      $ua['name'] = 'test';
      $users[$key] = (object)$ua;
    }
 Mail::to($users)->send(new OrderAdminSendInvoice($o));

Displaying splash screen for longer than default seconds

1.Add a another view controller in “didFinishLaunchingWithOptions”

 UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

UINavigationController *homeNav = [storyboard instantiateViewControllerWithIdentifier:@"NavigationControllerView"];
UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"SplashViewController"];

self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.rootViewController = homeNav;
[self.window makeKeyAndVisible];

[(UINavigationController *)self.window.rootViewController pushViewController:viewController animated:NO];
}

2.In view did load of SplashView Controller

  [self performSelector:@selector(removeSplashScreenAddViewController) withObject:nil afterDelay:2.0];

3.In removeSplashScreenAddViewController method you can add your main view controller for eg.-

- (void) removeSplashScreenAddViewController {`  UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
UINavigationController *homeNav = [storyboard instantiateViewControllerWithIdentifier:@"HomeNav"];
UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:viewControllerName];

UIWindow *window =  [StaticHelper mainWindow];
window.rootViewController = homeNav;
[window makeKeyAndVisible];

[(UINavigationController *)window.rootViewController pushViewController:viewController animated:NO];`}

Multi-statement Table Valued Function vs Inline Table Valued Function

Maybe in a very condensed way. ITVF ( inline TVF) : more if u are DB person, is kind of parameterized view, take a single SELECT st

MTVF ( Multi-statement TVF): Developer, creates and load a table variable.

How to find the minimum value in an ArrayList, along with the index number? (Java)

Here's what I do. I find the minimum first then after the minimum is found, it is removed from ArrayList.

ArrayList<Integer> a = new ArrayList<>();
a.add(3);
a.add(6);
a.add(2);
a.add(5);

while (a.size() > 0) {
    int min = 1000;
    for (int b:a) {
        if (b < min)
            min = b;
    }
    System.out.println("minimum: " + min);
    System.out.println("index of min: " + a.indexOf((Integer) min));
    a.remove((Integer) min);
}

Parsing domain from a URL

Check out parse_url():

$url = 'http://google.com/dhasjkdas/sadsdds/sdda/sdads.html';
$parse = parse_url($url);
echo $parse['host']; // prints 'google.com'

parse_url doesn't handle really badly mangled urls very well, but is fine if you generally expect decent urls.

Javascript form validation with password confirming

add this to your form:

<form  id="regform" action="insert.php" method="post">

add this to your function:

<script>
    function myFunction() {
        var pass1 = document.getElementById("pass1").value;
        var pass2 = document.getElementById("pass2").value;
        if (pass1 != pass2) {
            //alert("Passwords Do not match");
            document.getElementById("pass1").style.borderColor = "#E34234";
            document.getElementById("pass2").style.borderColor = "#E34234";
        }
        else {
            alert("Passwords Match!!!");
            document.getElementById("regForm").submit();
        }
    }
</script>

Adding/removing items from a JavaScript object with jQuery

First off, your quoted code is not JSON. Your code is JavaScript object literal notation. JSON is a subset of that designed for easier parsing.

Your code defines an object (data) containing an array (items) of objects (each with an id, name, and type).

You don't need or want jQuery for this, just JavaScript.

Adding an item:

data.items.push(
    {id: "7", name: "Douglas Adams", type: "comedy"}
);

That adds to the end. See below for adding in the middle.

Removing an item:

There are several ways. The splice method is the most versatile:

data.items.splice(1, 3); // Removes three items starting with the 2nd,
                         // ("Witches of Eastwick", "X-Men", "Ordinary People")

splice modifies the original array, and returns an array of the items you removed.

Adding in the middle:

splice actually does both adding and removing. The signature of the splice method is:

removed_items = arrayObject.splice(index, num_to_remove[, add1[, add2[, ...]]]);
  • index - the index at which to start making changes
  • num_to_remove - starting with that index, remove this many entries
  • addN - ...and then insert these elements

So I can add an item in the 3rd position like this:

data.items.splice(2, 0,
    {id: "7", name: "Douglas Adams", type: "comedy"}
);

What that says is: Starting at index 2, remove zero items, and then insert this following item. The result looks like this:

var data = {items: [
    {id: "1", name: "Snatch", type: "crime"},
    {id: "2", name: "Witches of Eastwick", type: "comedy"},
    {id: "7", name: "Douglas Adams", type: "comedy"},     // <== The new item
    {id: "3", name: "X-Men", type: "action"},
    {id: "4", name: "Ordinary People", type: "drama"},
    {id: "5", name: "Billy Elliot", type: "drama"},
    {id: "6", name: "Toy Story", type: "children"}
]};

You can remove some and add some at once:

data.items.splice(1, 3,
    {id: "7", name: "Douglas Adams", type: "comedy"},
    {id: "8", name: "Dick Francis", type: "mystery"}
);

...which means: Starting at index 1, remove three entries, then add these two entries. Which results in:

var data = {items: [
    {id: "1", name: "Snatch", type: "crime"},
    {id: "7", name: "Douglas Adams", type: "comedy"},
    {id: "8", name: "Dick Francis", type: "mystery"},
    {id: "4", name: "Ordinary People", type: "drama"},
    {id: "5", name: "Billy Elliot", type: "drama"},
    {id: "6", name: "Toy Story", type: "children"}
]};

var self = this?

I haven't used jQuery, but in a library like Prototype you can bind functions to a specific scope. So with that in mind your code would look like this:

 $('#foobar').ready('click', this.doSomething.bind(this));

The bind method returns a new function that calls the original method with the scope you have specified.

What's the difference between returning value or Promise.resolve from then()

Both of your examples should behave pretty much the same.

A value returned inside a then() handler becomes the resolution value of the promise returned from that then(). If the value returned inside the .then is a promise, the promise returned by then() will "adopt the state" of that promise and resolve/reject just as the returned promise does.

In your first example, you return "bbb" in the first then() handler, so "bbb" is passed into the next then() handler.

In your second example, you return a promise that is immediately resolved with the value "bbb", so "bbb" is passed into the next then() handler. (The Promise.resolve() here is extraneous).

The outcome is the same.

If you can show us an example that actually exhibits different behavior, we can tell you why that is happening.

How can I store HashMap<String, ArrayList<String>> inside a list?

First, let me fix a little bit your declaration:

List<Map<String, List<String>>> listOfMapOfList = 
    new HashList<Map<String, List<String>>>();

Please pay attention that I used concrete class (HashMap) only once. It is important to use interface where you can to be able to change the implementation later.

Now you want to add element to the list, don't you? But the element is a map, so you have to create it:

Map<String, List<String>> mapOfList = new HashMap<String, List<String>>();

Now you want to populate the map. Fortunately you can use utility that creates lists for you, otherwise you have to create list separately:

mapOfList.put("mykey", Arrays.asList("one", "two", "three"));

OK, now we are ready to add the map into the list:

listOfMapOfList.add(mapOfList);

BUT:

Stop creating complicated collections right now! Think about the future: you will probably have to change the internal map to something else or list to set etc. This will probably cause you to re-write significant parts of your code. Instead define class that contains you data and then add it to one-dimentional collection:

Let's call your class Student (just as example):

public Student {
    private String firstName;
    private String lastName;
    private int studentId;

    private Colectiuon<String> courseworks = Collections.emtpyList();

    //constructors, getters, setters etc
}

Now you can define simple collection:

Collection<Student> students = new ArrayList<Student>();

If in future you want to put your students into map where key is the studentId, do it:

Map<Integer, Student> students = new HashMap<Integer, Student>();

How to find the Windows version from the PowerShell command line

(Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name BuildLabEx).BuildLabEx

auto refresh for every 5 mins

Auto reload with target of your choice. In this case target is _self set to every 5 minutes.

300000 milliseconds = 300 seconds = 5 minutes

as 60000 milliseconds = 60 seconds = 1 minute.

This is how you do it:

<script type="text/javascript">
function load()
{
setTimeout("window.open('http://YourPage.com', '_self');", 300000);
}
</script>
<body onload="load()">

Or this if it is the same page to reload itself:

<script type="text/javascript">
function load()
{
setTimeout("window.open(self.location, '_self');", 300000);
}
</script>
<body onload="load()">

TypeError: 'bool' object is not callable

Actually you can fix it with following steps -

  1. Do cls.__dict__
  2. This will give you dictionary format output which will contain {'isFilled':True} or {'isFilled':False} depending upon what you have set.
  3. Delete this entry - del cls.__dict__['isFilled']
  4. You will be able to call the method now.

In this case, we delete the entry which overrides the method as mentioned by BrenBarn.

Get row-index values of Pandas DataFrame as list?

If you're only getting these to manually pass into df.set_index(), that's unnecessary. Just directly do df.set_index['your_col_name', drop=False], already.

It's very rare in pandas that you need to get an index as a Python list (unless you're doing something pretty funky, or else passing them back to NumPy), so if you're doing this a lot, it's a code smell that you're doing something wrong.

Javascript: 'window' is not defined

Trying to access an undefined variable will throw you a ReferenceError.

A solution to this is to use typeof:

if (typeof window === "undefined") {
  console.log("Oops, `window` is not defined")
}

or a try catch:

try { window } catch (err) {
  console.log("Oops, `window` is not defined")
}

While typeof window is probably the cleanest of the two, the try catch can still be useful in some cases.

'ls' in CMD on Windows is not recognized

Use the command dir to list all the directories and files in a directory; ls is a unix command.

How to convert integers to characters in C?

void main ()
 {
    int temp,integer,count=0,i,cnd=0;
    char ascii[10]={0};
    printf("enter a number");
    scanf("%d",&integer);
     if(integer>>31)
     {
     /*CONVERTING 2's complement value to normal value*/    
     integer=~integer+1;    
     for(temp=integer;temp!=0;temp/=10,count++);    
     ascii[0]=0x2D;
     count++;
     cnd=1;
     }
     else
     for(temp=integer;temp!=0;temp/=10,count++);    
     for(i=count-1,temp=integer;i>=cnd;i--)
     {

        ascii[i]=(temp%10)+0x30;
        temp/=10;
     }
    printf("\n count =%d ascii=%s ",count,ascii);

 }

C++ Returning reference to local variable

A local variable is memory on the stack, that memory is not automatically invalidated when you go out of scope. From a Function deeper nested (higher on the stack in memory), its perfectly safe to access this memory.

Once the Function returns and ends though, things get dangerous. Usually the memory is not deleted or overwritten when you return, meaning the memory at that adresss is still containing your data - the pointer seems valid.

Until another function builds up the stack and overwrites it. This is why this can work for a while - and then suddenly cease to function after one particularly deeply nested set of functions, or a function with really huge sized or many local objects, reaches that stack-memory again.

It even can happen that you reach the same program part again, and overwrite your old local function variable with the new function variable. All this is very dangerous and should be heavily discouraged. Do not use pointers to local objects!

How do I prompt for Yes/No/Cancel input in a Linux shell script?

This is what I usually need in a script/function:

  • default answer is Yes, if you hit ENTER
  • accept also z (in case you mix up you are on QWERTZ Layout)
  • accept other lanyuages ("ja", "Oui", ...)
  • handle the right exit in case you are inside a function
while true; do
    read -p "Continue [Y/n]? " -n 1 -r -e yn
    case "${yn:-Y}" in
        [YyZzOoJj]* ) echo; break ;;
        [Nn]* ) [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1 ;; # handle exits from shell or function but don't exit interactive shell
        * ) echo "Please answer yes or no.";;
    esac
done
echo "and off we go!"

Export P7b file with all the certificate chain into CER file

The selected answer didn't work for me, but it's close. I found a tutorial that worked for me and the certificate I obtained from StartCom.

  1. Open the .p7b in a text editor.
  2. Change the leader and trailer so the file looks similar to this:

    -----BEGIN PKCS7-----
    [... certificate content here ...]
    -----END PKCS7-----
    

For example, my StartCom certificate began with:

    -----BEGIN CERTIFICATE----- 

and ended with:

    -----END CERTIFICATE----- 
  1. Save and close the .p7b.
  2. Run the following OpenSSL command (works on Ubuntu 14.04.4, as of this writing):

    openssl pkcs7 -print_certs –in pkcs7.p7b -out pem.cer
    

The output is a .cer with the certificate chain.

Reference: http://www.freetutorialssubmit.com/extract-certificates-from-P7B/2206

Convert to/from DateTime and Time in Ruby

While making such conversions one should take into consideration the behavior of timezones while converting from one object to the other. I found some good notes and examples in this stackoverflow post.

How can I programmatically invoke an onclick() event from a anchor tag while keeping the ‘this’ reference in the onclick function?

Granted, OP stated very similarly that this didn't work, but it did for me. Based on the notes in my source, it seems it was implemented around the time, or after, OP's post. Perhaps it's more standard now.

document.getElementsByName('MyElementsName')[0].click();

In my case, my button didn't have an ID. If your element has an id, preferably use the following (untested).

document.getElementById('MyElementsId').click();

I originally tried this method and it didn't work. After Googling I came back and realized my element was by name, and didn't have an ID. Double check you're calling the right attribute.

Source: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click

Jquery change <p> text programmatically

Try the following, note that when user refreshes the page, the value is "Male" again, data should be stored on database.

<p id="pTest">Male</p>
<button>change</button>

<script>
$('button').click(function(){
     $('#pTest').text('test')
})
</script>

http://jsfiddle.net/CA5Cs/

how to save canvas as png image?

I really like Tovask's answer but it doesn't work due to the function having the name download (this answer explains why). I also don't see the point in replacing "data:image/..." with "data:application/...".

The following code has been tested in Chrome and Firefox and seems to work fine in both.

JavaScript:

function prepDownload(a, canvas, name) {
    a.download = name
    a.href = canvas.toDataURL()
}

HTML:

<a href="#" onclick="prepDownload(this, document.getElementById('canvasId'), 'imgName.png')">Download</a>
<canvas id="canvasId"></canvas>

Best way to check if MySQL results returned in PHP?

if (mysql_num_rows($result)==0) { PERFORM ACTION }

For PHP 5 and 7 and above use mysqli:

if (mysqli_num_rows($result)==0) { PERFORM ACTION }

This gets my vote.

OP assuming query is not returning any error, so this should be one of the way

How to find out what type of a Mat object is with Mat::type() in OpenCV

For debugging purposes in case you want to look up a raw Mat::type in a debugger:

+--------+----+----+----+----+------+------+------+------+
|        | C1 | C2 | C3 | C4 | C(5) | C(6) | C(7) | C(8) |
+--------+----+----+----+----+------+------+------+------+
| CV_8U  |  0 |  8 | 16 | 24 |   32 |   40 |   48 |   56 |
| CV_8S  |  1 |  9 | 17 | 25 |   33 |   41 |   49 |   57 |
| CV_16U |  2 | 10 | 18 | 26 |   34 |   42 |   50 |   58 |
| CV_16S |  3 | 11 | 19 | 27 |   35 |   43 |   51 |   59 |
| CV_32S |  4 | 12 | 20 | 28 |   36 |   44 |   52 |   60 |
| CV_32F |  5 | 13 | 21 | 29 |   37 |   45 |   53 |   61 |
| CV_64F |  6 | 14 | 22 | 30 |   38 |   46 |   54 |   62 |
+--------+----+----+----+----+------+------+------+------+

So for example, if type = 30 then OpenCV data type is CV_64FC4. If type = 50 then the OpenCV data type is CV_16UC(7).

HTML 5 Favicon - Support?

The answers provided (at the time of this post) are link only answers so I thought I would summarize the links into an answer and what I will be using.

When working to create Cross Browser Favicons (including touch icons) there are several things to consider.

The first (of course) is Internet Explorer. IE does not support PNG favicons until version 11. So our first line is a conditional comment for favicons in IE 9 and below:

<!--[if IE]><link rel="shortcut icon" href="path/to/favicon.ico"><![endif]-->

To cover the uses of the icon create it at 32x32 pixels. Notice the rel="shortcut icon" for IE to recognize the icon it needs the word shortcut which is not standard. Also we wrap the .ico favicon in a IE conditional comment because Chrome and Safari will use the .ico file if it is present, despite other options available, not what we would like.

The above covers IE up to IE 9. IE 11 accepts PNG favicons, however, IE 10 does not. Also IE 10 does not read conditional comments thus IE 10 won't show a favicon. With IE 11 and Edge available I don't see IE 10 in widespread use, so I ignore this browser.

For the rest of the browsers we are going to use the standard way to cite a favicon:

<link rel="icon" href="path/to/favicon.png">

This icon should be 196x196 pixels in size to cover all devices that may use this icon.

To cover touch icons on mobile devices we are going to use Apple's proprietary way to cite a touch icon:

<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">

Using rel="apple-touch-icon-precomposed" will not apply the reflective shine when bookmarked on iOS. To have iOS apply the shine use rel="apple-touch-icon". This icon should be sized to 180x180 pixels as that is the current size recommend by Apple for the latest iPhones and iPads. I have read Blackberry will also use rel="apple-touch-icon-precomposed".

As a note: Chrome for Android states:

The apple-touch-* are deprecated, and will be supported only for a short time. (Written as of beta for m31 of Chrome).

Custom Tiles for IE 11+ on Windows 8.1+

IE 11+ on Windows 8.1+ does offer a way to create pinned tiles for your site.

Microsoft recommends creating a few tiles at the following size:

Small: 128 x 128

Medium: 270 x 270

Wide: 558 x 270

Large: 558 x 558

These should be transparent images as we will define a color background next.

Once these images are created you should create an xml file called browserconfig.xml with the following code:

<?xml version="1.0" encoding="utf-8"?>
<browserconfig>
  <msapplication>
    <tile>
      <square70x70logo src="images/smalltile.png"/>
      <square150x150logo src="images/mediumtile.png"/>
      <wide310x150logo src="images/widetile.png"/>
      <square310x310logo src="images/largetile.png"/>
      <TileColor>#009900</TileColor>
    </tile>
  </msapplication>
</browserconfig>

Save this xml file in the root of your site. When a site is pinned IE will look for this file. If you want to name the xml file something different or have it in a different location add this meta tag to the head:

<meta name="msapplication-config" content="path-to-browserconfig/custom-name.xml" />

For additional information on IE 11+ custom tiles and using the XML file visit Microsoft's website.

Putting it all together:

To put it all together the above code would look like this:

<!-- For IE 9 and below. ICO should be 32x32 pixels in size -->
<!--[if IE]><link rel="shortcut icon" href="path/to/favicon.ico"><![endif]-->

<!-- Touch Icons - iOS and Android 2.1+ 180x180 pixels in size. --> 
<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">

<!-- Firefox, Chrome, Safari, IE 11+ and Opera. 196x196 pixels in size. -->
<link rel="icon" href="path/to/favicon.png">

Windows Phone Live Tiles

If a user is using a Windows Phone they can pin a website to the start screen of their phone. Unfortunately, when they do this it displays a screenshot of your phone, not a favicon (not even the MS specific code referenced above). To make a "Live Tile" for Windows Phone Users for your website one must use the following code:

Here are detailed instructions from Microsoft but here is a synopsis:

Step 1

Create a square image for your website, to support hi-res screens create it at 768x768 pixels in size.

Step 2

Add a hidden overlay of this image. Here is example code from Microsoft:

<div id="TileOverlay" onclick="ToggleTileOverlay()" style='background-color: Highlight; height: 100%; width: 100%; top: 0px; left: 0px; position: fixed; color: black; visibility: hidden'>
  <img src="customtile.png" width="320" height="320" />
  <div style='margin-top: 40px'>
     Add text/graphic asking user to pin to start using the menu...
  </div>
</div>

Step 3

You then can add thew following line to add a pin to start link:

<a href="javascript:ToggleTileOverlay()">Pin this site to your start screen</a>

Microsoft recommends that you detect windows phone and only show that link to those users since it won't work for other users.

Step 4

Next you add some JS to toggle the overlay visibility

<script>
function ToggleTileOverlay() {
 var newVisibility =     (document.getElementById('TileOverlay').style.visibility == 'visible') ? 'hidden' : 'visible';
 document.getElementById('TileOverlay').style.visibility =    newVisibility;
}
</script>

Note on Sizes

I am using one size as every browser will scale down the image as necessary. I could add more HTML to specify multiple sizes if desired for those with a lower bandwidth but I am already compressing the PNG files heavily using TinyPNG and I find this unnecessary for my purposes. Also, according to philippe_b's answer Chrome and Firefox have bugs that cause the browser to load all sizes of icons. Using one large icon may be better than multiple smaller ones because of this.

Further Reading

For those who would like more details see the links below:

What is an optional value in Swift?

In objective C variables with no value were equal to 'nil'(it was also possible to use 'nil' values same as 0 and false), hence it was possible to use variables in conditional statements (Variables having values are same as 'TRUE' and those with no values were equal to 'FALSE').

Swift provides type safety by providing 'optional value'. i.e. It prevents errors formed from assigning variables of different types.

So in Swift, only booleans can be provided on conditional statements.

var hw = "Hello World"

Here, even-though 'hw' is a string, it can't be used in an if statement like in objective C.

//This is an error

if hw

 {..}

For that it needs to be created as,

var nhw : String? = "Hello World"

//This is correct

if nhw

 {..}

jQuery Change event on an <input> element - any way to retain previous value?

I created these functions based on Joey Guerra's suggestion, thank you for that. I'm elaborating a little bit, perhaps someone can use it. The first function checkDefaults() is called when an input changes, the second is called when the form is submitted using jQuery.post. div.updatesubmit is my submit button, and class 'needsupdate' is an indicator that an update is made but not yet submitted.

function checkDefaults() {
    var changed = false;
        jQuery('input').each(function(){
            if(this.defaultValue != this.value) {
                changed = true;
            }
        });
        if(changed === true) {
            jQuery('div.updatesubmit').addClass("needsupdate");
        } else {
            jQuery('div.updatesubmit').removeClass("needsupdate");
        }
}

function renewDefaults() {
        jQuery('input').each(function(){
            this.defaultValue = this.value;
        });
        jQuery('div.updatesubmit').removeClass("needsupdate");
}

onclick="location.href='link.html'" does not load page in Safari

I had the same error. Make sure you don't have any <input>, <select>, etc. name="location".

How do I use the lines of a file as arguments of a command?

None of the answers seemed to work for me or were too complicated. Luckily, it's not complicated with xargs (Tested on Ubuntu 20.04).

This works with each arg on a separate line in the file as the OP mentions and was what I needed as well.

cat foo.txt | xargs my_command

One thing to note is that it doesn't seem to work with aliased commands.

The accepted answer works if the command accepts multiple args wrapped in a string. In my case using (Neo)Vim it does not and the args are all stuck together.

xargs does it probably and actually gives you separate arguments supplied to the command.

How to extract one column of a csv file

You can also use while loop

IFS=,
while read name val; do
        echo "............................"

        echo Name: "$name"
done<itemlst.csv

Android Studio was unable to find a valid Jvm (Related to MAC OS)

On Mac OS X Yosemite just install:

Java SE Development Kit 8

and

Java Version 8 Update 25

It's all, work for me!

Nesting queries in SQL

The way I see it, the only place for a nested query would be in the WHERE clause, so e.g.

SELECT country.name, country.headofstate
FROM country 
WHERE country.headofstate LIKE 'A%' AND 
country.id in (SELECT country_id FROM city WHERE population > 100000)

Apart from that, I have to agree with Adrian on: why the heck should you use nested queries?

Run AVD Emulator without Android Studio

For Linux/Ubuntu

Create a new File from Terminal as

gedit emulator.sh (Use any Name for file here i have used "emulator")

now write following lines in this file

cd /home/userName/Android/Sdk/tools/

./emulator @your created Android device Name

(here after @ write the name of your AVD e.g

./emulator @Nexus_5X_API_27 )

Now save the file and run your emulator using following commands

./emulator.sh

In case of Permission denied use following command before above command

chmod +x emulator.sh

All set Go..

Show loading image while $.ajax is performed

You can, of course, show it before making the request, and hide it after it completes:

$('#loading-image').show();
$.ajax({
      url: uri,
      cache: false,
      success: function(html){
        $('.info').append(html);
      },
      complete: function(){
        $('#loading-image').hide();
      }
    });

I usually prefer the more general solution of binding it to the global ajaxStart and ajaxStop events, that way it shows up for all ajax events:

$('#loading-image').bind('ajaxStart', function(){
    $(this).show();
}).bind('ajaxStop', function(){
    $(this).hide();
});

What is the difference between `Enum.name()` and `Enum.toString()`?

Use toString() when you want to present information to a user (including a developer looking at a log). Never rely in your code on toString() giving a specific value. Never test it against a specific string. If your code breaks when someone correctly changes the toString() return, then it was already broken.

If you need to get the exact name used to declare the enum constant, you should use name() as toString may have been overridden.

reading text file with utf-8 encoding using java

I ran into the same problem every time it finds a special character marks it as ??. to solve this, I tried using the encoding: ISO-8859-1

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("txtPath"),"ISO-8859-1"));

while ((line = br.readLine()) != null) {

}

I hope this can help anyone who sees this post.

how to compare the Java Byte[] array?

As byte[] is mutable it is treated as only being .equals() if its the same object.

If you want to compare the contents you have to use Arrays.equals(a, b)

BTW: Its not the way I would design it. ;)

Expected linebreaks to be 'LF' but found 'CRLF' linebreak-style

Just made autocrlf param in .gitconfig file false and recloned the code. It worked!

[core] autocrlf = false

How to customize a Spinner in Android

I have build a small demo project on this you could have a look to it Link to project

How to plot a function curve in R

plot has a plot.function method

plot(eq, 1, 1000)

Or

curve(eq, 1, 1000)

How to change a <select> value from JavaScript

 <script language="javascript" type="text/javascript">
        function selectFunction() {
             var printStr = document.getElementById("select").options[0].value
            alert(printStr);
            document.getElementById("select").selectedIndex = 0;
        }
    </script>

Java, Shifting Elements in an Array

Just for completeness: Stream solution since Java 8.

final String[] shiftedArray = Arrays.stream(array)
        .skip(1)
        .toArray(String[]::new);

I think I sticked with the System.arraycopy() in your situtation. But the best long-term solution might be to convert everything to Immutable Collections (Guava, Vavr), as long as those collections are short-lived.

OSX - How to auto Close Terminal window after the "exit" command executed.

Create a script:

cat ~/exit.scpt

like this:

  • Note: If there is only one window, just quit the application, else simulate command + w to close the tab)

tell application "Terminal" set WindowNum to get window count if WindowNum = 1 then quit else tell application "System Events" to keystroke "w" using command down end if end tell

Then add a alias in your *shrc

just like vi ~/.bashrc or zshrc (anything else?)

add it: alias exit="osascript ~/exit.scpt"

And source the ~/.bashrc or reopen your terminal.app

How to capture Enter key press?

Form approach

As scoota269 says, you should use onSubmit instead, cause pressing enter on a textbox will most likey trigger a form submit (if inside a form)

<form action="#" onsubmit="handle">
    <input type="text" name="txt" />
</form>

<script>
    function handle(e){
        e.preventDefault(); // Otherwise the form will be submitted

        alert("FORM WAS SUBMITTED");
    }
</script>

Textbox approach

If you want to have an event on the input-field then you need to make sure your handle() will return false, otherwise the form will get submitted.

<form action="#">
    <input type="text" name="txt" onkeypress="handle(event)" />
</form>

<script>
    function handle(e){
        if(e.keyCode === 13){
            e.preventDefault(); // Ensure it is only this code that runs

            alert("Enter was pressed was presses");
        }
    }
</script>

Load RSA public key from file

Below code works absolutely fine to me and working. This code will read RSA private and public key though java code. You can refer to http://snipplr.com/view/18368/

   import java.io.DataInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.security.KeyFactory;
    import java.security.NoSuchAlgorithmException;
    import java.security.interfaces.RSAPrivateKey;
    import java.security.interfaces.RSAPublicKey;
    import java.security.spec.InvalidKeySpecException;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;

    public class Demo {

        public static final String PRIVATE_KEY="/home/user/private.der";
        public static final String PUBLIC_KEY="/home/user/public.der";

        public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
            //get the private key
            File file = new File(PRIVATE_KEY);
            FileInputStream fis = new FileInputStream(file);
            DataInputStream dis = new DataInputStream(fis);

            byte[] keyBytes = new byte[(int) file.length()];
            dis.readFully(keyBytes);
            dis.close();

            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory kf = KeyFactory.getInstance("RSA");
            RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(spec);
            System.out.println("Exponent :" + privKey.getPrivateExponent());
            System.out.println("Modulus" + privKey.getModulus());

            //get the public key
            File file1 = new File(PUBLIC_KEY);
            FileInputStream fis1 = new FileInputStream(file1);
            DataInputStream dis1 = new DataInputStream(fis1);
            byte[] keyBytes1 = new byte[(int) file1.length()];
            dis1.readFully(keyBytes1);
            dis1.close();

            X509EncodedKeySpec spec1 = new X509EncodedKeySpec(keyBytes1);
            KeyFactory kf1 = KeyFactory.getInstance("RSA");
            RSAPublicKey pubKey = (RSAPublicKey) kf1.generatePublic(spec1);

            System.out.println("Exponent :" + pubKey.getPublicExponent());
            System.out.println("Modulus" + pubKey.getModulus());
        }
    }

Why is Tkinter Entry's get function returning nothing?

A simple example without classes:

from tkinter import *    
master = Tk()

# Create this method before you create the entry
def return_entry(en):
    """Gets and prints the content of the entry"""
    content = entry.get()
    print(content)  

Label(master, text="Input: ").grid(row=0, sticky=W)

entry = Entry(master)
entry.grid(row=0, column=1)

# Connect the entry with the return button
entry.bind('<Return>', return_entry) 

mainloop()

How to publish a Web Service from Visual Studio into IIS?

If using Visual Studio 2010 you can right-click on the project for the service, and select properties. Then select the Web tab. Under the Servers section you can configure the URL. There is also a button to create the virtual directory.

What exactly is the 'react-scripts start' command?

"start" is a name of a script, in npm you run scripts like this npm run scriptName, npm start is also a short for npm run start

As for "react-scripts" this is a script related specifically to create-react-app

Android studio, gradle and NDK

I have used ndk.dir=/usr/shareData/android-ndk-r11b // path of ndk

in local.properties file in android studio project. and add this line :
android.useDeprecatedNdk=true

in gradle.properties file in android studio project.

More information here: http://tools.android.com/tech-docs/android-ndk-preview

batch file - counting number of files in folder and storing in a variable

The fastest code for counting files with ANY attributes in folder %FOLDER% and its subfolders is the following. The code is for script in a command script (batch) file.

@for /f %%a in ('2^>nul dir "%FOLDER%" /a-d/b/-o/-p/s^|find /v /c ""') do set n=%%a
@echo Total files: %n%.

Add two numbers and display result in textbox with Javascript

You made a simple mistake. Don't worry.... Simply use getElementById instead getElementsById

true

var first_number = parseInt(document.getElementById("Text1").value);

False

var first_number = parseInt(document.getElementsById("Text1").value);

Thanks ...

How to initialize var?

var just tells the compiler to infer the type you wanted at compile time...it cannot infer from null (though there are cases it could).

So, no you are not allowed to do this.

When you say "some empty value"...if you mean:

var s = string.Empty;
//
var s = "";

Then yes, you may do that, but not null.

LINQ select in C# dictionary

var res = exitDictionary
            .Select(p => p.Value).Cast<Dictionary<string, object>>()
            .SelectMany(d => d)
            .Where(p => p.Key == "fieldname1")
            .Select(p => p.Value).Cast<List<Dictionary<string,string>>>()
            .SelectMany(l => l)
            .SelectMany(d=> d)
            .Where(p => p.Key == "valueTitle")
            .Select(p => p.Value)
            .ToList();

This also works, and easy to understand.

mcrypt is deprecated, what is the alternative?

You can use phpseclib pollyfill package. You can not use open ssl or libsodium for encrypt/decrypt with rijndael 256. Another issue, you don't need replacement any code.

Changing the space between each item in Bootstrap navbar

I would suggest you just evenly space them as shown in this answer here

.navbar ul {
  list-style-type: none;
  padding: 0;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  flex-wrap: nowrap; /* assumes you only want one row */
}

Allow anything through CORS Policy

Try configuration at /config/application.rb:

config.middleware.insert_before 0, "Rack::Cors" do
  allow do
    origins '*'
    resource '*', :headers => :any, :methods => [:get, :post, :options, :delete, :put, :patch], credentials: true
  end
end

How to disable HTML links

I would do something like

$('td').find('a').each(function(){
 $(this).addClass('disabled-link');
});

$('.disabled-link').on('click', false);

something like this should work. You add a class for links you want to have disabled and then you return false when someone click them. To enable them just remove the class.

Maven error in eclipse (pom.xml) : Failure to transfer org.apache.maven.plugins:maven-surefire-plugin:pom:2.12.4

In my case it was a failed import to eclipse. I had to delete the project from eclipse (without deleting form the filesystem of course) and reimport it. After that the error was gone immediately.

Update query with PDO and MySQL

This has nothing to do with using PDO, it's just that you are confusing INSERT and UPDATE.

Here's the difference:

  • INSERT creates a new row. I'm guessing that you really want to create a new row.
  • UPDATE changes the values in an existing row, but if this is what you're doing you probably should use a WHERE clause to restrict the change to a specific row, because the default is that it applies to every row.

So this will probably do what you want:

$sql = "INSERT INTO `access_users`   
  (`contact_first_name`,`contact_surname`,`contact_email`,`telephone`) 
  VALUES (:firstname, :surname, :email, :telephone);
  ";

Note that I've also changed the order of columns; the order of your columns must match the order of values in your VALUES clause.

MySQL also supports an alternative syntax for INSERT:

$sql = "INSERT INTO `access_users`   
  SET `contact_first_name` = :firstname,
    `contact_surname` = :surname,
    `contact_email` = :email,
    `telephone` = :telephone
  ";

This alternative syntax looks a bit more like an UPDATE statement, but it creates a new row like INSERT. The advantage is that it's easier to match up the columns to the correct parameters.

C# Help reading foreign characters using StreamReader

Try a different encoding such as Encoding.UTF8. You can also try letting StreamReader find the encoding itself:

    StreamReader reader = new StreamReader(inputFilePath, System.Text.Encoding.UTF8, true)

Edit: Just saw your update. Try letting StreamReader do the guessing.

How to test if a double is an integer

you could try in this way: get the integer value of the double, subtract this from the original double value, define a rounding range and tests if the absolute number of the new double value(without the integer part) is larger or smaller than your defined range. if it is smaller you can intend it it is an integer value. Example:

public final double testRange = 0.2;

public static boolean doubleIsInteger(double d){
    int i = (int)d;
    double abs = Math.abs(d-i);
    return abs <= testRange;
}

If you assign to d the value 33.15 the method return true. To have better results you can assign lower values to testRange (as 0.0002) at your discretion.

Why should I use a pointer rather than the object itself?

There are many excellent answers to this question, including the important use cases of forward declarations, polymorphism etc. but I feel a part of the "soul" of your question is not answered - namely what the different syntaxes mean across Java and C++.

Let's examine the situation comparing the two languages:

Java:

Object object1 = new Object(); //A new object is allocated by Java
Object object2 = new Object(); //Another new object is allocated by Java

object1 = object2; 
//object1 now points to the object originally allocated for object2
//The object originally allocated for object1 is now "dead" - nothing points to it, so it
//will be reclaimed by the Garbage Collector.
//If either object1 or object2 is changed, the change will be reflected to the other

The closest equivalent to this, is:

C++:

Object * object1 = new Object(); //A new object is allocated on the heap
Object * object2 = new Object(); //Another new object is allocated on the heap
delete object1;
//Since C++ does not have a garbage collector, if we don't do that, the next line would 
//cause a "memory leak", i.e. a piece of claimed memory that the app cannot use 
//and that we have no way to reclaim...

object1 = object2; //Same as Java, object1 points to object2.

Let's see the alternative C++ way:

Object object1; //A new object is allocated on the STACK
Object object2; //Another new object is allocated on the STACK
object1 = object2;//!!!! This is different! The CONTENTS of object2 are COPIED onto object1,
//using the "copy assignment operator", the definition of operator =.
//But, the two objects are still different. Change one, the other remains unchanged.
//Also, the objects get automatically destroyed once the function returns...

The best way to think of it is that -- more or less -- Java (implicitly) handles pointers to objects, while C++ may handle either pointers to objects, or the objects themselves. There are exceptions to this -- for example, if you declare Java "primitive" types, they are actual values that are copied, and not pointers. So,

Java:

int object1; //An integer is allocated on the stack.
int object2; //Another integer is allocated on the stack.
object1 = object2; //The value of object2 is copied to object1.

That said, using pointers is NOT necessarily either the correct or the wrong way to handle things; however other answers have covered that satisfactorily. The general idea though is that in C++ you have much more control on the lifetime of the objects, and on where they will live.

Take home point -- the Object * object = new Object() construct is actually what is closest to typical Java (or C# for that matter) semantics.

Getting each individual digit from a whole integer

RGB values fall nicely on bit boundaries; decimal digits don't. I don't think there's an easy way to do this using bitwise operators at all. You'd need to use decimal operators like modulo 10 (% 10).

Select current element in jQuery

I think by combining .children() with $(this) will return the children of the selected item only

consider the following:

$("div li").click(function() {
$(this).children().css('background','red');
});

this will change the background of the clicked li only

Run all SQL files in a directory

@echo off
cd C:\Program Files (x86)\MySQL\MySQL Workbench 6.0 CE

for %%a in (D:\abc\*.sql) do (
echo %%a
mysql --host=ip --port=3306 --user=uid--password=ped < %%a
)

Step1: above lines copy into note pad save it as bat.

step2: In d drive abc folder in all Sql files in queries executed in sql server.

step3: Give your ip, user id and password.

python-dev installation error: ImportError: No module named apt_pkg

I see everyone saying how to fix it with strange copying etc, but no one really said why the problem occurs.

So let me explain, for those of you who like me don't want to mess with system files only because someone on SO told them so.


The problem is that:

  • many system scripts have python3 shebang hardcoded into them. You can check it yourself:
~$ grep -R "\#\!/usr/bin/python3" /usr/lib/*

/usr/lib/cnf-update-db:#!/usr/bin/python3
/usr/lib/command-not-found:#!/usr/bin/python3
/usr/lib/cups/filter/pstotiff:#!/usr/bin/python3
/usr/lib/cups/filter/rastertosag-gdi:#!/usr/bin/python3 -u
grep: /usr/lib/cups/backend/cups-brf: Permission denied
/usr/lib/cups/backend/hpfax:#!/usr/bin/python3
/usr/lib/language-selector/ls-dbus-backend:#!/usr/bin/python3
/usr/lib/python3/dist-packages/language_support_pkgs.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/softwareproperties/MirrorTest.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/installdriver.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/openprinting.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/xmldriverprefs.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/smburi.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/ppds.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/debug.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/DistUpgrade/dist-upgrade.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/CommandNotFound/db/creator.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/CommandNotFound/db/db.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/Quirks/quirkreader.py:#!/usr/bin/python3
grep: /usr/lib/ssl/private: Permission denied
/usr/lib/system-service/system-service-d:#!/usr/bin/python3
/usr/lib/ubuntu-release-upgrader/check-new-release-gtk:#!/usr/bin/python3
/usr/lib/ubuntu-release-upgrader/do-partial-upgrade:#!/usr/bin/python3
/usr/lib/ubuntu-release-upgrader/check-new-release:#!/usr/bin/python3
/usr/lib/update-notifier/package-data-downloader:#!/usr/bin/python3
/usr/lib/update-notifier/backend_helper.py:#!/usr/bin/python3
/usr/lib/update-notifier/apt_check.py:#!/usr/bin/python3
/usr/lib/update-notifier/apt-check:#!/usr/bin/python3

  • python apt package python-apt/python3-apt is a system package, so it's for default system python

Thus, the scripts will always get the version currently linked to python3, but fail because the apt package is not present.


General solution: NEVER change default python3 link. Ever. This also applies to python link - if an app was written in Python2 with some old syntax elements that don't work in Python3, the app will not work.

[My terminal broke that way because I use Terminator, which is apparently written in Python2.7 not compatible with Python3.]


Solutions presented here either suggest copying/linking the apt package files or changing python3 link.

Let's analyse both:

  1. Copying/linking the apt package

This shouldn't be a problem because from around Python3.4 all python scripts work on newer versions as well.

So far. But it may break in the future - if you keep your system long enough.

  1. Changing python3 link back

This is a great solution because we can get back to "never ever changing the link"


"But I like having to type just python!" - I like it too! That's how I got to this problem in the first place!

  1. In general, you should avoid manually changing system links - use update-alternatives instead to link different versions. This applies to any app with many versions. This will still break those system scripts (because it does change the link), but you can switch back and forth easily, without worrying whether you put link and dest in the right order or made a typo.

  2. Consider using other name than python/python3 for your link or alias.

  3. Or add your own python/python3 link to PATH (just like virtual environments do), without changing system links.

"Cannot update paths and switch to branch at the same time"

If you have a typo in your branchname you'll get this same error.

What exactly does += do in python?

+= is just a shortcut for writing

number = 4
number = number + 1

So instead you would write

numbers = 4
numbers += 1

Both ways are correct but example two helps you write a little less code

How to read line by line of a text area HTML tag

Try this.

var lines = $('textarea').val().split('\n');
for(var i = 0;i < lines.length;i++){
    //code here using lines[i] which will give you each line
}

Missing Maven dependencies in Eclipse project

Below solution worked for me -
1- Go to project directory
2- run mvn eclipse:eclipse (Hope mvn is added in your path)
3- run mvn clean install

Refresh your project in Eclipse and check.

SQL Server PRINT SELECT (Print a select query result)?

Try this query

DECLARE @PrintVarchar nvarchar(max) = (Select Sum(Amount) From Expense)
PRINT 'Varchar format =' + @PrintVarchar

DECLARE @PrintInt int = (Select Sum(Amount) From Expense)
PRINT @PrintInt

What does the "yield" keyword do?

Yield

>>> def create_generator():
...    my_list = range(3)
...    for i in my_list:
...        yield i*i
...
>>> my_generator = create_generator() # create a generator
>>> print(my_generator) # my_generator is an object!
<generator object create_generator at 0xb7555c34>
>>> for i in my_generator:
...     print(i)
0
1
4

In short, you can see that the loop does not stop and continues to function even after the object or variable is sent (unlike return where the loop stops after execution).

Fastest way to set all values of an array?

   /**
     * Assigns the specified char value to each element of the specified array
     * of chars.
     *
     * @param a the array to be filled
     * @param val the value to be stored in all elements of the array
     */
    public static void fill(char[] a, char val) {
        for (int i = 0, len = a.length; i < len; i++)
            a[i] = val;
    }

That's the way Arrays.fill does it.

(I suppose you could drop into JNI and use memset.)

How to check encoding of a CSV file

Use chardet https://github.com/chardet/chardet (documentation is short and easy to read).

Install python, then pip install chardet, at last use the command line command.

I tested under GB2312 and it's pretty accurate. (Make sure you have at least a few characters, sample with only 1 character may fail easily).

file is not reliable as you can see.

enter image description here

How to add screenshot to READMEs in github repository?

Add image in repository from upload file option then in README file

![Alt text]("enter image url of repositoryhere") 

How to serialize a JObject without the formatting?

Call JObject's ToString(Formatting.None) method.

Alternatively if you pass the object to the JsonConvert.SerializeObject method it will return the JSON without formatting.

Documentation: Write JSON text with JToken.ToString

How can I create a dynamic button click event on a dynamic button?

Button button = new Button();
button.Click += (s,e) => { your code; };
//button.Click += new EventHandler(button_Click);
container.Controls.Add(button);

//protected void button_Click (object sender, EventArgs e) { }

Ring Buffer in Java

Since Java 1.6, there is ArrayDeque, which implements Queue and seems to be faster and more memory efficient than a LinkedList and doesn't have the thread synchronization overhead of the ArrayBlockingQueue: from the API docs: "This class is likely to be faster than Stack when used as a stack, and faster than LinkedList when used as a queue."

final Queue<Object> q = new ArrayDeque<Object>();
q.add(new Object()); //insert element
q.poll(); //remove element

jquery Ajax call - data parameters are not being passed to MVC Controller action

You need add -> contentType: "application/json; charset=utf-8",

<script type="text/javascript">
    $(document).ready( function() {
      $('#btnTest').click( function() {
        $.ajax({
          type: "POST", 
          url: "/Login/Test",
          data: { ListID: '1', ItemName: 'test' },
          dataType: "json",
          contentType: "application/json; charset=utf-8",
          success: function(response) { alert(response); },
          error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
        });
      });
    });
</script>

What is Turing Complete?

Can a relational database input latitudes and longitudes of places and roads, and compute the shortest path between them - no. This is one problem that shows SQL is not Turing complete.

But C++ can do it, and can do any problem. Thus it is.

Why is Android Studio reporting "URI is not registered"?

Another suggestion, which was the solution for me: I got the error in the line

<resources xmlns:ns1="http://schemas.android.com/tools" xmlns:ns2="urn:oasis:names:tc:xliff:document:1.2">

in the values.xml file that was automatically generated during the build process.

It was solved by adding the android prefix in the styles.xml file.

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="textColorPrimary">@color/textColorPrimary</item>
        <item name="colorBackground">@color/colorPrimaryDark</item>
    </style>

had to be changed to

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:textColorPrimary">@color/textColorPrimary</item>
        <item name="android:colorBackground">@color/colorPrimaryDark</item>
    </style>

Returning a value even if no result

You can use COALESCE

SELECT COALESCE(SUM(column),0)
FROM   table

What is the time complexity of indexing, inserting and removing from common data structures?

Information on this topic is now available on Wikipedia at: Search data structure

+----------------------+----------+------------+----------+--------------+
|                      |  Insert  |   Delete   |  Search  | Space Usage  |
+----------------------+----------+------------+----------+--------------+
| Unsorted array       | O(1)     | O(1)       | O(n)     | O(n)         |
| Value-indexed array  | O(1)     | O(1)       | O(1)     | O(n)         |
| Sorted array         | O(n)     | O(n)       | O(log n) | O(n)         |
| Unsorted linked list | O(1)*    | O(1)*      | O(n)     | O(n)         |
| Sorted linked list   | O(n)*    | O(1)*      | O(n)     | O(n)         |
| Balanced binary tree | O(log n) | O(log n)   | O(log n) | O(n)         |
| Heap                 | O(log n) | O(log n)** | O(n)     | O(n)         |
| Hash table           | O(1)     | O(1)       | O(1)     | O(n)         |
+----------------------+----------+------------+----------+--------------+

 * The cost to add or delete an element into a known location in the list 
   (i.e. if you have an iterator to the location) is O(1). If you don't 
   know the location, then you need to traverse the list to the location
   of deletion/insertion, which takes O(n) time. 

** The deletion cost is O(log n) for the minimum or maximum, O(n) for an
   arbitrary element.

How to turn off magic quotes on shared hosting?

BaileyP's answer is already pretty good, but I would use this condition instead:

if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc() === 1){
  $_POST = array_map( 'stripslashes', $_POST );
  $_GET = array_map( 'stripslashes', $_GET );
  $_COOKIE = array_map( 'stripslashes', $_COOKIE );
}

It is more defensive.

How to loop through a checkboxlist and to find what's checked and not checked?

Use the CheckBoxList's GetItemChecked or GetItemCheckState method to find out whether an item is checked or not by its index.

Output to the same line overwriting previous output?

Here's my little class that can reprint blocks of text. It properly clears the previous text so you can overwrite your old text with shorter new text without creating a mess.

import re, sys

class Reprinter:
    def __init__(self):
        self.text = ''

    def moveup(self, lines):
        for _ in range(lines):
            sys.stdout.write("\x1b[A")

    def reprint(self, text):
        # Clear previous text by overwritig non-spaces with spaces
        self.moveup(self.text.count("\n"))
        sys.stdout.write(re.sub(r"[^\s]", " ", self.text))

        # Print new text
        lines = min(self.text.count("\n"), text.count("\n"))
        self.moveup(lines)
        sys.stdout.write(text)
        self.text = text

reprinter = Reprinter()

reprinter.reprint("Foobar\nBazbar")
reprinter.reprint("Foo\nbar")

MySQL SELECT last few days?

You could use a combination of the UNIX_TIMESTAMP() function to do that.

SELECT ... FROM ... WHERE UNIX_TIMESTAMP() - UNIX_TIMESTAMP(thefield) < 259200

Unix command to check the filesize

ls -lh file.txt | awk '{ print $5 }'

Jquery Chosen plugin - dynamically populate list by Ajax

Chosen API has changed a lot.

If non of the solution given works for you, you can try this one: https://github.com/goFrendiAsgard/gofrendi.chosen.ajaxify

Here is the function:

// USAGE:
// $('#some_input_id').chosen();
// chosen_ajaxify('some_input_id', 'http://some_url.com/contain/');

// REQUEST WILL BE SENT TO THIS URL: http://some_url.com/contain/some_term

// AND THE EXPECTED RESULT (WHICH IS GOING TO BE POPULATED IN CHOSEN) IS IN JSON FORMAT
// CONTAINING AN ARRAY WHICH EACH ELEMENT HAS "value" AND "caption" KEY. EX:
// [{"value":"1", "caption":"Go Frendi Gunawan"}, {"value":"2", "caption":"Kira Yamato"}]

function chosen_ajaxify(id, ajax_url){
    console.log($('.chosen-search input').autocomplete);
    $('div#' + id + '_chosen .chosen-search input').keyup(function(){
        var keyword = $(this).val();
        var keyword_pattern = new RegExp(keyword, 'gi');
        $('div#' + id + '_chosen ul.chosen-results').empty();
        $("#"+id).empty();
        $.ajax({
            url: ajax_url + keyword,
            dataType: "json",
            success: function(response){
                // map, just as in functional programming :). Other way to say "foreach"
                $.map(response, function(item){
                    $('#'+id).append('<option value="' + item.value + '">' + item.caption + '</option>');
                });
                $("#"+id).trigger("chosen:updated");
                $('div#' + id + '_chosen').removeClass('chosen-container-single-nosearch');
                $('div#' + id + '_chosen .chosen-search input').val(keyword);
                $('div#' + id + '_chosen .chosen-search input').removeAttr('readonly');
                $('div#' + id + '_chosen .chosen-search input').focus();
                // put that underscores
                $('div#' + id + '_chosen .active-result').each(function(){
                    var html = $(this).html();
                    $(this).html(html.replace(keyword_pattern, function(matched){
                        return '<em>' + matched + '</em>';
                    }));
                });
            }
        });
    });
}

Here is your HTML:

<select id="ajax_select"></select>

And here is your javasscript:

// This is also how you usually use chosen
$('#ajax_select').chosen({allow_single_deselect:true, width:"200px", search_contains: true});
// And this one is how you add AJAX capability
chosen_ajaxify('ajax_select', 'server.php?keyword=');

For more information, please refer to https://github.com/goFrendiAsgard/gofrendi.chosen.ajaxify#how-to-use

Getting and removing the first character of a string

Another alternative is to use capturing sub-expressions with the regular expression functions regmatches and regexec.

# the original example
x <- 'hello stackoverflow'

# grab the substrings
myStrings <- regmatches(x, regexec('(^.)(.*)', x))

This returns the entire string, the first character, and the "popped" result in a list of length 1.

myStrings
[[1]]
[1] "hello stackoverflow" "h"                   "ello stackoverflow" 

which is equivalent to list(c(x, substr(x, 1, 1), substr(x, 2, nchar(x)))). That is, it contains the super set of the desired elements as well as the full string.


Adding sapply will allow this method to work for a character vector of length > 1.

# a slightly more interesting example
xx <- c('hello stackoverflow', 'right back', 'at yah')

# grab the substrings
myStrings <- regmatches(x, regexec('(^.)(.*)', xx))

This returns a list with the matched full string as the first element and the matching subexpressions captured by () as the following elements. So in the regular expression '(^.)(.*)', (^.) matches the first character and (.*) matches the remaining characters.

myStrings
[[1]]
[1] "hello stackoverflow" "h"                   "ello stackoverflow" 

[[2]]
[1] "right back" "r"          "ight back" 

[[3]]
[1] "at yah" "a"      "t yah" 

Now, we can use the trusty sapply + [ method to pull out the desired substrings.

myFirstStrings <- sapply(myStrings, "[", 2)
myFirstStrings
[1] "h" "r" "a"
mySecondStrings <- sapply(myStrings, "[", 3)
mySecondStrings
[1] "ello stackoverflow" "ight back"          "t yah"

How to use Java property files?

There are many ways to create and read properties files:

  1. Store the file in the same package.
  2. Recommend .properties extension however you can choose your own.
  3. Use theses classes located at java.util package => Properties, ListResourceBundle, ResourceBundle classes.
  4. To read properties, use iterator or enumerator or direct methods of Properties or java.lang.System class.

ResourceBundle class:

 ResourceBundle rb = ResourceBundle.getBundle("prop"); // prop.properties
 System.out.println(rb.getString("key"));

Properties class:

Properties ps = new Properties();
ps.Load(new java.io.FileInputStream("my.properties"));

Using ALTER to drop a column if it exists in MySQL

There is no language level support for this in MySQL. Here is a work-around involving MySQL information_schema meta-data in 5.0+, but it won't address your issue in 4.0.18.

drop procedure if exists schema_change;

delimiter ';;'
create procedure schema_change() begin

    /* delete columns if they exist */
    if exists (select * from information_schema.columns where table_schema = schema() and table_name = 'table1' and column_name = 'column1') then
        alter table table1 drop column `column1`;
    end if;
    if exists (select * from information_schema.columns where table_schema = schema() and table_name = 'table1' and column_name = 'column2') then
        alter table table1 drop column `column2`;
    end if;

    /* add columns */
    alter table table1 add column `column1` varchar(255) NULL;
    alter table table1 add column `column2` varchar(255) NULL;

end;;

delimiter ';'
call schema_change();

drop procedure if exists schema_change;

I wrote some more detailed information in a blog post.

Error: invalid operands of types ‘const char [35]’ and ‘const char [2]’ to binary ‘operator+’

In this particular case, an even simpler fix would be to just get rid of the "+" all together because AGE is a string literal and what comes before and after are also string literals. You could write line 3 as:

str += "Do you feel " AGE " years old?";

This is because most C/C++ compilers will concatenate string literals automatically. The above is equivalent to:

str += "Do you feel " "42" " years old?";

which the compiler will convert to:

str += "Do you feel 42 years old?";

Write bytes to file

The simplest way would be to convert your hexadecimal string to a byte array and use the File.WriteAllBytes method.

Using the StringToByteArray() method from this question, you'd do something like this:

string hexString = "0CFE9E69271557822FE715A8B3E564BE";

File.WriteAllBytes("output.dat", StringToByteArray(hexString));

The StringToByteArray method is included below:

public static byte[] StringToByteArray(string hex) {
    return Enumerable.Range(0, hex.Length)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                     .ToArray();
}

Check if key exists and iterate the JSON array using Python

I wrote a tiny function for this purpose. Feel free to repurpose,

def is_json_key_present(json, key):
    try:
        buf = json[key]
    except KeyError:
        return False

    return True

git with IntelliJ IDEA: Could not read from remote repository

Nothing helped me. Then I saw that the name of the project on the computer is different from the name on the git repository.

So I solved the problem.

Why are arrays of references illegal?

Given int& arr[] = {a,b,c,8};, what is sizeof(*arr) ?

Everywhere else, a reference is treated as being simply the thing itself, so sizeof(*arr) should simply be sizeof(int). But this would make array pointer arithmetic on this array wrong (assuming that references are not the same widths is ints). To eliminate the ambiguity, it's forbidden.

Using Math.round to round to one decimal place?

If you need this and similar operations more often, it may be more convenient to find the right library instead of implementing it yourself.

Here are one-liners solving your question from Apache Commons Math using Precision, Colt using Functions, and Weka using Utils:

double value = 540.512 / 1978.8 * 100;
// Apache commons math
double rounded1 = Precision.round(value, 1);
double rounded2 = Precision.round(value, 1, BigDecimal.ROUND_HALF_UP);
// Colt
double rounded3 = Functions.round(0.1).apply(value)
// Weka
double rounded4 = Utils.roundDouble(value, 1)

Maven dependencies:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-math3</artifactId>
    <version>3.5</version>
</dependency>

<dependency>
    <groupId>colt</groupId>
    <artifactId>colt</artifactId>
    <version>1.2.0</version>
</dependency>

<dependency>
    <groupId>nz.ac.waikato.cms.weka</groupId>
    <artifactId>weka-stable</artifactId>
    <version>3.6.12</version>
</dependency>

Detailed 500 error message, ASP + IIS 7.5

TLDR:First determine where in the pipeline you're getting the error from (scroll looking for screenshots of something that resembles your error), make changes to get something new, repeat.

First determine what error message you are actually seeing.

If you are seeing the file located here...

%SystemDrive%\inetpub\custerr\\500.htm

...which generally looks like this:

IIS Default 500 error

...then you know you are seeing the currently configured error page in **IIS ** and you do NOT need to change the ASP.net customErrors setting, asp error detail setting, or "show friendly http errors" browser setting.

You may want to look at the above referenced path instead of trusting my screenshot just in case somebody changed it.

"Yes, I see the above described error..."

In this case, you are seeing the setting of <httpErrors> or in IIS Manager it's Error Pages --> Edit Feature Settings. The default for this is errorMode=DetailedLocalOnly at the server node level (as opposed to the site level) which means that while you will see this configured error page while remote, you should be able to log on locally to the server and see the full error which should look something like this:

Detailed HTTP Error

You should have everything that you need at that point to fix the current error.

"But I don't see the detailed error even browsing on the server"

That leaves a couple of possibilities.

  1. The browser you are using on the server is configured to use a proxy in its connection settings so it is not being seen as "local".
  2. You're not actually browsing to the site you think you are browsing to - this commonly happens when there's a load balancer involved. Do a ping check to see if dns gives you an IP on the server or somewhere else.
  3. You're site's httpErrors settings is set for "Custom" only. Change it to "DetailedLocalOnly". However, if you have a configuration error, this may not work since the site level httpErrors is also a configuration item. In that case proceed to #4
  4. The default for httpErrors for all sites is set for "Custom". In this case you need to click on the top level server node in IIS Manager (and not a particular site) and change the httpErrors settings there to DetailedLocalOnly. If this is an internal server and you're not worried about divulging sensitive information, you could also set it to "Detailed" which will allow you to see the error from clients other than the server.
  5. You're missing a module on the server like UrlRewrite (this one bites me a lot, and it often gives the generic message regardless of the httpErrors settings).

"Logging on to the server is not an option for me"

Change your site's httpErrors to "Detailed" so you can see it remotely. But if it doesn't work your error might already be a config error, see #3 immediately above. So you might be stuck with #4 or #5 and you're going to need somebody from your server team.

"I'm not seeing the error page described above. I'm seeing something different"

If you see this...

enter image description here

...and you expect to see something like this...

enter image description here

...then you need to change "Send errors to browser" to true in IIS Manager, under Site --> IIS --> ASP --> Debugging Properties

If you see this...

ie friendly errors 1

or this...

ie friendly errors 2

...you need to disable friendly errors in your browser or use fiddler's webview to look at the actual response vs what your browser chooses to show you.

If you see this...

Custom errors enabled

...then custom errors is working but you don't have a custom error page (of course at this point were talking about .net and not classic asp). You need to change your customErrors tag in your web.config to RemoteOnly to view on the server, or Off to view remotely.

If you see something that is styled like your site, then custom errors is likely On or RemoteOnly and it's displaying the custom page (Views->Shared->Error.cshtml in MVC for example). That said, it is unlikely but possible that somebody changed the pages in IIS for httpErrors so see the first section on that.

How to create empty data frame with column names specified in R?

Just create a data.frame with 0 length variables

eg

nodata <- data.frame(x= numeric(0), y= integer(0), z = character(0))
str(nodata)

## 'data.frame':    0 obs. of  3 variables:
##  $ x: num 
##  $ y: int 
##  $ z: Factor w/ 0 levels: 

or to create a data.frame with 5 columns named a,b,c,d,e

nodata <- as.data.frame(setNames(replicate(5,numeric(0), simplify = F), letters[1:5]))

symfony 2 twig limit the length of the text and put three dots

You can limit in following way. First is starting index and second is number of characters.

**{{ results['text'][4:2] }}**

Cannot find name 'require' after upgrading to Angular4

Finally I got solution for this, check my App module file :

import { BrowserModule } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MaterialModule } from '@angular/material';
import 'hammerjs';
import { ChartModule } from 'angular2-highcharts';
import * as highcharts from 'highcharts';
import { HighchartsStatic } from 'angular2-highcharts/dist/HighchartsService';

import { AppRouting } from './app.routing';
import { AppComponent } from './app.component';

declare var require: any;


export function highchartsFactory() {
      const hc = require('highcharts');
      const dd = require('highcharts/modules/drilldown');
      dd(hc);

      return hc;
}

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    AppRouting,
    BrowserAnimationsModule,
    MaterialModule,
    ChartModule
  ],
  providers: [{
      provide: HighchartsStatic,
      useFactory: highchartsFactory
    }],
  bootstrap: [AppComponent]
})
export class AppModule { }

Notice declare var require: any; in the above code.

Restarting cron after changing crontab file?

try this one for centos 7 : service crond reload

How to get Selected Text from select2 when using <input>

I finally figured it out doing this:

var $your-original-element = $('.your-original-element');
var data = $your-original-element.select2('data')[0]['text'];
alert(data);

if you also want the value:

var value = $your-original-element.select2('data')[0]['id'];
alert(value);

PHP upload image

<?php

$filename=$_FILES['file']['name'];
$filetype=$_FILES['file']['type'];
if($filetype=='image/jpeg' or $filetype=='image/png' or $filetype=='image/gif')
{
move_uploaded_file($_FILES['file']['tmp_name'],'dir_name/'.$filename);
$filepath="dir_name`enter code here`/".$filename;
}

?> 

How to validate an email address in JavaScript

Most of the answers here are not linter friendly, it's a mess! Some of them are also out-dated! After a lot of time spending, I decided to use an external library named email-validator, install it easily by npm for example and import/require it in your own project:

https://www.npmjs.com/package/email-validator

//NodeJs
const validator = require("email-validator");
validator.validate("[email protected]"); // true

//TypeScript/JavaScript
import * as EmailValidator from 'email-validator';
EmailValidator.validate("[email protected]"); // true

How to resolve conflicts in EGit

As it's an issue we face more than often, below are the steps to resolve it.

  1. Open the Git perspective. In the Git Repository view, go to on Branches ? Local ? master and right click ? Merge...

  2. It should auto select Remote Tracking ? *origin/master. Press Merge.

  3. Launch stage view in Eclipse.

  4. Double click the files which initially showed conflict

  5. In the conflict merge view, by selecting the left arrow for all the non-conflict + conflict changes from left to right, you can resolve all the conflicts.

  6. Save the merged file.

  7. Do a Team ? pull from Eclipse again.

You are all set :)

How to upload file using Selenium WebDriver in Java

If you have a text box to type the file path, just use sendkeys to input the file path and click on submit button. If there is no text box to type the file path and only able to click on browse button and to select the file from windows popup, you can use AutoIt tool, see the step below to use AutoIt for the same,

  1. Download and Install Autoit tool from http://www.autoitscript.com/site/autoit/

  2. Open Programs -> Autoit tool -> SciTE Script Editor.

  3. Paste the following code in Autoit editor and save it as “filename.exe “(eg: new.exe)

    Then compile and build the file to make it exe. (Tools ? Compile)

Autoit Code:

WinWaitActive("File Upload"); Name of the file upload window (Windows Popup Name: File Upload)    
Send("logo.jpg"); File name    
Send("{ENTER}")

Then Compile and Build from Tools menu of the Autoit tool -> SciTE Script Editor.

Paste the below Java code in Eclipse editor and save

Java Code:

driver.findElement(By.id("uploadbutton")).click; // open the Upload window using selenium    
Thread.sleep("20000"); // wait for page load    
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + "C:\\Documents and Settings\\new.exe"); // Give  path where the exe is saved.

How to split string and push in array using jquery

var string = 'a,b,c,d',
    strx   = string.split(',');
    array  = [];

array = array.concat(strx);
// ["a","b","c","d"]

How to pass credentials to httpwebrequest for accessing SharePoint Library

You could also use:

request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; 

Converting from a string to boolean in Python?

If you have control over the entity that's returning true/false, one option is to have it return 1/0 instead of true/false, then:

boolean_response = bool(int(response))

The extra cast to int handles responses from a network, which are always string.

Update 2021: "which are always string" -- this is a naive observation. It depends on the serialization protocol used by the library. Default serialization of high-level libraries (the ones used by most web devs) is typically to convert to string before being serialized to bytes. And then on the other side, it's deserialized from bytes to string, so you've lost any type information.

How to write string literals in python without having to escape them?

You will find Python's string literal documentation here:

http://docs.python.org/tutorial/introduction.html#strings

and here:

http://docs.python.org/reference/lexical_analysis.html#literals

The simplest example would be using the 'r' prefix:

ss = r'Hello\nWorld'
print(ss)
Hello\nWorld

How can I build XML in C#?

new XElement("Foo",
       from s in nameValuePairList
       select
             new XElement("Bar",
                  new XAttribute("SomeAttr", "SomeAttrValue"),
                          new XElement("Name", s.Name),
                          new XElement("Value", s.Value)
                         )
            );

Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`

Check: key = undef !!!

You got also the warn message:

Each child in a list should have a unique "key" prop.

if your code is complete right, but if on

<MyComponent key={someValue} />

someValue is undefined!!! Please check this first. You can save hours.

How to make a HTML Page in A4 paper size page(s)?

PPI and DPI make absolutely no difference to how a document will print off a browser. the printer takes no information on screen dot pitch or the DPI of the images etc. if you are printing images they would print at a size similar in proportion to how they are displayed on screen. the print processor of the browser would increase the DPI of the images from something rather low like 72dpi to whatever DPI the rest of the document is. say the image displays as half a page wide, then its about 4" wide physically. the pixel width of the image would be approx 300px to display correctly in the browser. by the time it prints at a nominal 300DPI, the processor has added pixels and the image will grow to around 1200px which at 300 DPI is 4".

when it comes to vector or non pixel based elements like text, the printer chooses its own DPI from the driver which doesnt relate to screen dot pitch or browser width etc. if the browser is 3000px wide, the print processor will wrap text as appropriate.

heres what makes it hard about creating print displays: each browser and printer will interpret text sizes (pt, em, px) and spacing in its own way. depending on what printer, browser and maybe even OS you use, you will get a different amount of lines and characters per page. so even if you test on your computer using your browser and printer and figure out that you can display the text in a box at 640x900px and its perfect on print, the next guy who tries to print will possibly get it printing differently. there really is no way to force each printer and browser to get it identical each time.

forget pixels and moreso forget DPI, the only thing you could use pixels for is setting a table width that simulates the width of a printable area on your printer. in that case i found that 640px wide is close.

How to run a method every X seconds

If you are familiar with RxJava, you can use Observable.interval(), which is pretty neat.

Observable.interval(60, TimeUnits.SECONDS)
          .flatMap(new Function<Long, ObservableSource<String>>() {
                @Override
                public ObservableSource<String> apply(@NonNull Long aLong) throws Exception {
                    return getDataObservable(); //Where you pull your data
                }
            });

The downside of this is that you have to architect polling your data in a different way. However, there are a lot of benefits to the Reactive Programming way:

  1. Instead of controlling your data via a callback, you create a stream of data that you subscribe to. This separates the concern of "polling data" logic and "populating UI with your data" logic so that you do not mix your "data source" code and your UI code.
  2. With RxAndroid, you can handle threads in just 2 lines of code.

    Observable.interval(60, TimeUnits.SECONDS)
          .flatMap(...) // polling data code
          .subscribeOn(Schedulers.newThread()) // poll data on a background thread
          .observeOn(AndroidSchedulers.mainThread()) // populate UI on main thread
          .subscribe(...); // your UI code
    

Please check out RxJava. It has a high learning curve but it will make handling asynchronous calls in Android so much easier and cleaner.

How to save as a new file and keep working on the original one in Vim?

The following command will create a copy in a new window. So you can continue see both original file and the new file.

:w {newfilename} | sp #

What are the best use cases for Akka framework

We are using akka with its camel plugin to distribute our analysis and trending processing for twimpact.com. We have to process between 50 and 1000 messages per second. In addition to multi-node processing with camel it is also used to distribute work on a single processor to multiple workers for maximum performance. Works quite well, but requires some understanding of how to handle congestions.

Install Node.js on Ubuntu

Here is the full description to create the first program using the express generator,

Ubuntu's package manager

To install Node.js and npm via apt-get, run these commands:

sudo apt-get update
sudo apt-get install nodejs
sudo ln -s /usr/bin/nodejs /usr/bin/node
sudo apt-get install npm

Express application generator:

$ npm install express-generator -g

Display the command options with the -h option:

$ express -h

  Usage: express [options] [dir]

  Options:

    -h, --help          output usage information
    -V, --version       output the version number
    -e, --ejs           add ejs engine support (defaults to jade)
        --hbs           add handlebars engine support
    -H, --hogan         add hogan.js engine support
    -c, --css <engine>  add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)
        --git           add .gitignore
    -f, --force         force on non-empty directory

For example, the following creates an Express application named myapp in the current working directory:

$ express myapp

   create : myapp
   create : myapp/package.json
   create : myapp/app.js
   create : myapp/public
   create : myapp/public/javascripts
   create : myapp/public/images
   create : myapp/routes
   create : myapp/routes/index.js
   create : myapp/routes/users.js
   create : myapp/public/stylesheets
   create : myapp/public/stylesheets/style.css
   create : myapp/views
   create : myapp/views/index.jade
   create : myapp/views/layout.jade
   create : myapp/views/error.jade
   create : myapp/bin
   create : myapp/bin/www

Then install dependencies:

$ cd myapp
$ npm install

Run the app with this command:

$ DEBUG=myapp:* npm start

Then load http://localhost:3000/ in your browser to access the application.

The generated application has the following directory structure:

+-- app.js
+-- bin
¦   +-- www
+-- package.json
+-- public
¦   +-- images
¦   +-- javascripts
¦   +-- stylesheets
¦       +-- style.css
+-- routes
¦   +-- index.js
¦   +-- users.js
+-- views
    +-- error.jade
    +-- index.jade
    +-- layout.jade

7 directories, 9 files

django templates: include and extends

Added for reference to future people who find this via google: You might want to look at the {% overextend %} tag provided by the mezzanine library for cases like this.

NGINX: upstream timed out (110: Connection timed out) while reading response header from upstream

For proxy_upstream timeout, I tried the above setting but these didn't work.

Setting resolver_timeout worked for me, knowing it was taking 30s to produce the upstream timeout message. E.g. me.atwibble.com could not be resolved (110: Operation timed out).

http://nginx.org/en/docs/http/ngx_http_core_module.html#resolver_timeout

Renaming Columns in an SQL SELECT Statement

select column1 as xyz,
      column2 as pqr,
.....

from TableName;

Uncaught SyntaxError: Unexpected token u in JSON at position 0

Your app is attempting to parse the undefined JSON web token. Such malfunction may occur due to the wrong usage of the local storage. Try to clear your local storage.

Example for Google Chrome:

  1. F12
  2. Application
  3. Local Storage
  4. Clear All

convert base64 to image in javascript/jquery

This is not exactly the OP's scenario but an answer to those of some of the commenters. It is a solution based on Cordova and Angular 1, which should be adaptable to other frameworks like jQuery. It gives you a Blob from Base64 data which you can store somewhere and reference it from client side javascript / html.

It also answers the original question on how to get an image (file) from the Base 64 data:

The important part is the Base 64 - Binary conversion:

function base64toBlob(base64Data, contentType) {
    contentType = contentType || '';
    var sliceSize = 1024;
    var byteCharacters = atob(base64Data);
    var bytesLength = byteCharacters.length;
    var slicesCount = Math.ceil(bytesLength / sliceSize);
    var byteArrays = new Array(slicesCount);

    for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
        var begin = sliceIndex * sliceSize;
        var end = Math.min(begin + sliceSize, bytesLength);

        var bytes = new Array(end - begin);
        for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
            bytes[i] = byteCharacters[offset].charCodeAt(0);
        }
        byteArrays[sliceIndex] = new Uint8Array(bytes);
    }
    return new Blob(byteArrays, { type: contentType });
}

Slicing is required to avoid out of memory errors.

Works with jpg and pdf files (at least that's what I tested). Should work with other mimetypes/contenttypes too. Check the browsers and their versions you aim for, they need to support Uint8Array, Blob and atob.

Here's the code to write the file to the device's local storage with Cordova / Android:

...
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dirEntry) {

                    // Setup filename and assume a jpg file
                    var filename = attachment.id + "-" + (attachment.fileName ? attachment.fileName : 'image') + "." + (attachment.fileType ? attachment.fileType : "jpg");
                    dirEntry.getFile(filename, { create: true, exclusive: false }, function(fileEntry) {
                        // attachment.document holds the base 64 data at this moment
                        var binary = base64toBlob(attachment.document, attachment.mimetype);
                        writeFile(fileEntry, binary).then(function() {
                            // Store file url for later reference, base 64 data is no longer required
                            attachment.document = fileEntry.nativeURL;

                        }, function(error) {
                            WL.Logger.error("Error writing local file: " + error);
                            reject(error.code);
                        });

                    }, function(errorCreateFile) {
                        WL.Logger.error("Error creating local file: " + JSON.stringify(errorCreateFile));
                        reject(errorCreateFile.code);
                    });

                }, function(errorCreateFS) {
                    WL.Logger.error("Error getting filesystem: " + errorCreateFS);
                    reject(errorCreateFS.code);
                });
...

Writing the file itself:

function writeFile(fileEntry, dataObj) {
    return $q(function(resolve, reject) {
        // Create a FileWriter object for our FileEntry (log.txt).
        fileEntry.createWriter(function(fileWriter) {

            fileWriter.onwriteend = function() {
                WL.Logger.debug(LOG_PREFIX + "Successful file write...");
                resolve();
            };

            fileWriter.onerror = function(e) {
                WL.Logger.error(LOG_PREFIX + "Failed file write: " + e.toString());
                reject(e);
            };

            // If data object is not passed in,
            // create a new Blob instead.
            if (!dataObj) {
                dataObj = new Blob(['missing data'], { type: 'text/plain' });
            }

            fileWriter.write(dataObj);
        });
    })
}

I am using the latest Cordova (6.5.0) and Plugins versions:

I hope this sets everyone here in the right direction.

Appending HTML string to the DOM

The right way is using insertAdjacentHTML. In Firefox earlier than 8, you can fall back to using Range.createContextualFragment if your str contains no script tags.

If your str contains script tags, you need to remove script elements from the fragment returned by createContextualFragment before inserting the fragment. Otherwise, the scripts will run. (insertAdjacentHTML marks scripts unexecutable.)

Force browser to refresh css, javascript, etc

You can turn off caching with Firefox's web developer toolbar.

How do I restrict my EditText input to numerical (possibly decimal and signed) input?

The best way to do that programmatically is using the next method:

public static DigitsKeyListener getInstance (boolean sign, boolean decimal) 

Returns a DigitsKeyListener that accepts the digits 0 through 9, plus the minus sign (only at the beginning) and/or decimal point (only one per field) if specified.

This solve the problem about the many '.' in EditText

editText.setKeyListener(DigitsKeyListener.getInstance(true,true)); // decimals and positive/negative numbers. 

editText.setKeyListener(DigitsKeyListener.getInstance(false,true)); // positive decimals numbers. 

editText.setKeyListener(DigitsKeyListener.getInstance(false,false)); // positive integer numbers.

editText.setKeyListener(DigitsKeyListener.getInstance(true,false)); // positive/negative integer numbers.

Add new row to dataframe, at specific row-index, not appended?

The .before argument in dplyr::add_row can be used to specify the row.

dplyr::add_row(
  cars,
  speed = 0,
  dist = 0,
  .before = 3
)
#>    speed dist
#> 1      4    2
#> 2      4   10
#> 3      0    0
#> 4      7    4
#> 5      7   22
#> 6      8   16
#> ...

event.preventDefault() vs. return false

From my experience, there is at least one clear advantage when using event.preventDefault() over using return false. Suppose you are capturing the click event on an anchor tag, otherwise which it would be a big problem if the user were to be navigated away from the current page. If your click handler uses return false to prevent browser navigation, it opens the possibility that the interpreter will not reach the return statement and the browser will proceed to execute the anchor tag's default behavior.

$('a').click(function (e) {
  // custom handling here

  // oops...runtime error...where oh where will the href take me?

  return false;
});

The benefit to using event.preventDefault() is that you can add this as the first line in the handler, thereby guaranteeing that the anchor's default behavior will not fire, regardless if the last line of the function is not reached (eg. runtime error).

$('a').click(function (e) {
  e.preventDefault();

  // custom handling here

  // oops...runtime error, but at least the user isn't navigated away.
});

Which regular expression operator means 'Don't' match this character?

There's two ways to say "don't match": character ranges, and zero-width negative lookahead/lookbehind.

The former: don't match a, b, c or 0: [^a-c0]

The latter: match any three-letter string except foo and bar:

(?!foo|bar).{3}

or

.{3}(?<!foo|bar)

Also, a correction for you: *, ? and + do not actually match anything. They are repetition operators, and always follow a matching operator. Thus, a+ means match one or more of a, [a-c0]+ means match one or more of a, b, c or 0, while [^a-c0]+ would match one or more of anything that wasn't a, b, c or 0.

SSIS Convert Between Unicode and Non-Unicode Error

On the above example I kept losing the values, I think that delaying the Validation will allow the new data types to be saved as part of the meta data.

On the connection Manager for 'Excel Connection Manager' set the Delay Validation to False from the Properties.

Then on the data flow Destination task for Excel set the ValidationExternalMetaData to False, again from the properties.

This will now allow you to right click on the Excel Destination Task and go to Advanced Editor for Excel Destination --> far right tab - Input and Output Properties. In the External Columns folder section you will be able to now change the Data Types and Length values of the problematic columns and this can now be saved.

Good Luck!

"configuration file /etc/nginx/nginx.conf test failed": How do I know why this happened?

sudo nginx -t should test all files and return errors and warnings locations

SQL Server - INNER JOIN WITH DISTINCT

add "distinct" after "select".

select distinct a.FirstName, a.LastName, v.District , v.LastName
from AddTbl a 
inner join ValTbl v  where a.LastName = v.LastName  order by Firstname

VBScript to send email without running Outlook

You can send email without Outlook in VBScript using the CDO.Message object. You will need to know the address of your SMTP server to use this:

Set MyEmail=CreateObject("CDO.Message")

MyEmail.Subject="Subject"
MyEmail.From="[email protected]"
MyEmail.To="[email protected]"
MyEmail.TextBody="Testing one two three."

MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing")=2

'SMTP Server
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.server.com"

'SMTP Port
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25 

MyEmail.Configuration.Fields.Update
MyEmail.Send

set MyEmail=nothing

If your SMTP server requires a username and password then paste these lines in above the MyEmail.Configuration.Fields.Update line:

'SMTP Auth (For Windows Auth set this to 2)
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate")=1
'Username
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername")="username" 
'Password
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword")="password"

More information on using CDO to send email with VBScript can be found on the link below: http://www.paulsadowski.com/wsh/cdo.htm

Remove an entire column from a data.frame in R

With this you can remove the column and store variable into another variable.

df = subset(data, select = -c(genome) )

TypeScript - Append HTML to container element in Angular 2

There is a better solution to this answer that is more Angular based.

  1. Save your string in a variable in the .ts file

    MyStrings = ["one","two","three"]

  2. In the html file use *ngFor.

    <div class="one" *ngFor="let string of MyStrings; let i = index"> <div class="two">{{string}}</div> </div>

  3. if you want to dynamically insert the div element, just push more strings into the MyStrings array

    myFunction(nextString){ this.MyString.push(nextString) }

this way every time you click the button containing the myFunction(nextString) you effectively add another class="two" div which acts the same way as inserting it into the DOM with pure javascript.

How does Go update third-party packages?

To specify versions, or commits:

go get -u [email protected]

go get -u otherpackage@git-sha

See https://github.com/golang/go/wiki/Modules#daily-workflow

How to make/get a multi size .ico file?

This can be done for free using GIMP.

It uses the ability of GIMP to have each layer a different size.

I created the following layers sized correctly.

  • 256x256 will be saved as 32bpp 8bit alpha
  • 48x48 will be saved as 32bpp 8bit alpha
  • 48x48 will be saved as 8bpp 1bit alpha
  • 32x32 will be saved as 32bpp 8bit alpha
  • 32x32 will be saved as 8bpp 1bit alpha
  • 32x32 will be saved as 4bpp 1bit alpha
  • 16x16 will be saved as 32bpp 8bit alpha
  • 16x16 will be saved as 8bpp 1bit alpha
  • 16x16 will be saved as 4bpp 1bit alpha

Notes

  • You may need to check other resources to confirm to yourself that this is a sensible list of resolutions and colour depths.
  • Make sure you use transparency round the outside of your image, and anti-aliased edges. You should see the grey checkerboard effect round the outside of your layers to indicate they are transparent
  • The 16x16 icons will need to be heavily edited by hand using a 1 pixel wide pencil and the eyedropper tool to make them look any good.
  • Do not change colour depth / Mode in GIMP. Leave it as RGB
  • You change the colour depths when you save as an .ico - GIMP pops up a special dialog box for changing the colour settings for each layer

jquery - Check for file extension before uploading

        function yourfunctionName() {
            var yourFileName = $("#yourinputfieldis").val();

            var yourFileExtension = yourFileName .replace(/^.*\./, '');
            switch (yourFileExtension ) {
                case 'pdf':
                case 'jpg':
                case 'doc':
                    $("#formId").submit();// your condition what you want to do
                    break;
                default:
                    alert('your File extension is wrong.');
                    this.value = '';
            }    
        }

Provide password to ssh command inside bash script, Without the usage of public keys and Expect

AFAIK there is no possibility beside from using keys or expect if you are using the command line version ssh. But there are library bindings for the most programming languages like C, python, php, ... . You could write a program in such a language. This way it would be possible to pass the password automatically. But note this is of course a security problem as the password will be stored in plain text in that program

Remove a marker from a GoogleMap

If you use Kotlin language you just add this code:

Create global variables of GoogleMap and Marker types.

I use variable marker to make variable marker value can change directly

private lateinit var map: GoogleMap
private lateinit var marker: Marker

And I use this function/method to add the marker on my map:

private fun placeMarkerOnMap(location: LatLng) {
    val markerOptions = MarkerOptions().position(location)
    val titleStr = getAddress(location)
    markerOptions.title(titleStr)
    marker = map.addMarker(markerOptions)
}

After I create the function I place this code on the onMapReady() to remove the marker and create a new one:

map.setOnMapClickListener { location ->
        map.clear()
        marker.remove()
        placeMarkerOnMap(location)
    }

It's bonus if you want to display the address location when you click the marker add this code to hide and show the marker address but you need a method to get the address location. I got the code from this post: How to get complete address from latitude and longitude?

map.setOnMarkerClickListener {marker ->
        if (marker.isInfoWindowShown){
            marker.hideInfoWindow()
        }else{
            marker.showInfoWindow()
        }
        true
    }

R Plotting confidence bands with ggplot

require(ggplot2)
require(nlme)

set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)

mp <- within(mp,
         {
             wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
             wow <- rnorm(N)*wav+rnorm(N)*wav^3
         })

m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))

Get fitted values (the same as m01$fitted)

fit <- predict(m01)

Normally we could use something like predict(...,se.fit=TRUE) to get the confidence intervals on the prediction, but gls doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :

V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))

Put together a "prediction frame":

predframe <- with(mp,data.frame(year,wav,
                                wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))

Now plot with geom_ribbon

(p1 <- ggplot(mp, aes(year, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

year vs wow

It's easier to see that we got the right answer if we plot against wav rather than year:

(p2 <- ggplot(mp, aes(wav, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

wav vs wow

It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly() fits -- see ?makepredictcall.

jump to line X in nano editor

I am using Linux raspi 4.19.118+ #1311 via ssh Powershell on Win 10 Pro 1909 with German keyboard. nano shortcut Goto Line with "Crtl + Shift + -" was not working Solution: Step 1 - Do Current Position with "Crtl + C" Step 2 - Goto Line with "Crtl + Shift + -" IS working!

I dont know what effects it. But now its working without step 1!

EF Migrations: Rollback last applied migration?

In EntityFrameworkCore:

Update-Database 20161012160749_AddedOrderToCourse

where 20161012160749_AddedOrderToCourse is a name of migration you want to rollback to.

How to call a Web Service Method?

The current way to do this is by using the "Add Service Reference" command. If you specify "TestUploaderWebService" as the service reference name, that will generate the type TestUploaderWebService.Service1. That class will have a method named GetFileListOnWebServer, which will return an array of strings (you can change that to be a list of strings if you like). You would use it like this:

string[] files = null;
TestUploaderWebService.Service1 proxy = null;
bool success = false;
try
{
    proxy = new TestUploaderWebService.Service1();
    files = proxy.GetFileListOnWebServer();
    proxy.Close();
    success = true;
}
finally
{
    if (!success)
    {
        proxy.Abort();
    }
}

P.S. Tell your instructor to look at "Microsoft: ASMX Web Services are a “Legacy Technology”", and ask why he's teaching out of date technology.

Converting Varchar Value to Integer/Decimal Value in SQL Server

You can use it without casting such as:

select sum(`stuff`) as mySum from test;

Or cast it to decimal:

select sum(cast(`stuff` as decimal(4,2))) as mySum from test;

SQLFiddle

EDIT

For SQL Server, you can use:

select sum(cast(stuff as decimal(5,2))) as mySum from test;

SQLFiddle

Change project name on Android Studio

Just go to res>values>strings.xml. One line says Somethig-your name

<string name="app_name">Somethig-your name</string>

Just replace your original name to

 <string name="app_name">Your Name</string>

Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs

I tried this with Visual Studio 2013 Express, using a pointer instead of an index, which sped up the process a bit. I suspect this is because the addressing is offset + register, instead of offset + register + (register<<3). C++ code.

   uint64_t* bfrend = buffer+(size/8);
   uint64_t* bfrptr;

// ...

   {
      startP = chrono::system_clock::now();
      count = 0;
      for (unsigned k = 0; k < 10000; k++){
         // Tight unrolled loop with uint64_t
         for (bfrptr = buffer; bfrptr < bfrend;){
            count += __popcnt64(*bfrptr++);
            count += __popcnt64(*bfrptr++);
            count += __popcnt64(*bfrptr++);
            count += __popcnt64(*bfrptr++);
         }
      }
      endP = chrono::system_clock::now();
      duration = chrono::duration_cast<std::chrono::nanoseconds>(endP-startP).count();
      cout << "uint64_t\t"  << count << '\t' << (duration/1.0E9) << " sec \t"
           << (10000.0*size)/(duration) << " GB/s" << endl;
   }

assembly code: r10 = bfrptr, r15 = bfrend, rsi = count, rdi = buffer, r13 = k :

$LL5@main:
        mov     r10, rdi
        cmp     rdi, r15
        jae     SHORT $LN4@main
        npad    4
$LL2@main:
        mov     rax, QWORD PTR [r10+24]
        mov     rcx, QWORD PTR [r10+16]
        mov     r8, QWORD PTR [r10+8]
        mov     r9, QWORD PTR [r10]
        popcnt  rdx, rax
        popcnt  rax, rcx
        add     rdx, rax
        popcnt  rax, r8
        add     r10, 32
        add     rdx, rax
        popcnt  rax, r9
        add     rsi, rax
        add     rsi, rdx
        cmp     r10, r15
        jb      SHORT $LL2@main
$LN4@main:
        dec     r13
        jne     SHORT $LL5@main

Read input stream twice

Depending on where the InputStream is coming from, you might not be able to reset it. You can check if mark() and reset() are supported using markSupported().

If it is, you can call reset() on the InputStream to return to the beginning. If not, you need to read the InputStream from the source again.

Rails 4: before_filter vs. before_action

before_filter/before_action: means anything to be executed before any action executes.

Both are same. they are just alias for each other as their behavior is same.

T-SQL CASE Clause: How to specify WHEN NULL

Found a solution to this. Just ISNULL the CASE statement:

ISNULL(CASE x WHEN x THEN x ELSE x END, '') AS 'BLAH'

Multiple lines of text in UILabel

In IB, set number of lines to 0 (allows unlimited lines)

When typing within the text field using IB, use "alt-return" to insert a return and go to the next line (or you can copy in text already separated out by lines).

How to check if an integer is within a range of numbers in PHP?

You can use filter_var

filter_var(
    $yourInteger, 
    FILTER_VALIDATE_INT, 
    array(
        'options' => array(
            'min_range' => $min, 
            'max_range' => $max
        )
    )
);

This will also allow you to specify whether you want to allow octal and hex notation of integers. Note that the function is type-safe. 5.5 is not an integer but a float and will not validate.

Detailed tutorial about filtering data with PHP:

What is SuppressWarnings ("unchecked") in Java?

One trick is to create an interface that extends a generic base interface...

public interface LoadFutures extends Map<UUID, Future<LoadResult>> {}

Then you can check it with instanceof before the cast...

Object obj = context.getAttribute(FUTURES);
if (!(obj instanceof LoadFutures)) {
    String format = "Servlet context attribute \"%s\" is not of type "
            + "LoadFutures. Its type is %s.";
    String msg = String.format(format, FUTURES, obj.getClass());
    throw new RuntimeException(msg);
}
return (LoadFutures) obj;

Is this a good way to clone an object in ES6?

if you don't want to use json.parse(json.stringify(object)) you could create recursively key-value copies:

function copy(item){
  let result = null;
  if(!item) return result;
  if(Array.isArray(item)){
    result = [];
    item.forEach(element=>{
      result.push(copy(element));
    });
  }
  else if(item instanceof Object && !(item instanceof Function)){ 
    result = {};
    for(let key in item){
      if(key){
        result[key] = copy(item[key]);
      }
    }
  }
  return result || item;
}

But the best way is to create a class that can return a clone of it self

class MyClass{
    data = null;
    constructor(values){ this.data = values }
    toString(){ console.log("MyClass: "+this.data.toString(;) }
    remove(id){ this.data = data.filter(d=>d.id!==id) }
    clone(){ return new MyClass(this.data) }
}

Javascript to sort contents of select element

Inspired by @Terre Porter's answer, I think this one is very simple to implement (using jQuery)

var $options = jQuery("#my-dropdownlist-id > option"); 
// or jQuery("#my-dropdownlist-id").find("option")

$options.sort(function(a, b) {
    return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
})

But, for Alpha/Numeric dropdown lists :

Inspired by : https://stackoverflow.com/a/4340339/1598891

var $options = jQuery(dropDownList).find("option");

var reAlpha = /[^a-zA-Z]/g;
var reNumeric = /[^0-9]/g;
$options.sort(function AlphaNumericSort($a,$b) {
    var a = $a.text;
    var b = $b.text;
    var aAlpha = a.replace(reAlpha, "");
    var bAlpha = b.replace(reAlpha, "");
    if(aAlpha === bAlpha) {
        var aNumeric = parseInt(a.replace(reNumeric, ""), 10);
        var bNumeric = parseInt(b.replace(reNumeric, ""), 10);
        return aNumeric === bNumeric ? 0 : aNumeric > bNumeric ? 1 : -1;
    } else {
        return aAlpha > bAlpha ? 1 : -1;
    }
})

Hope it will help

First example Second example

Embed youtube videos that play in fullscreen automatically

This was pretty well answered over here: How to make a YouTube embedded video a full page width one?

If you add '?rel=0&autoplay=1' to the end of the url in the embed code (like this)

<iframe id="video" src="//www.youtube.com/embed/5iiPC-VGFLU?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>

of the video it should play on load. Here's a demo over at jsfiddle.

VARCHAR to DECIMAL

You are going to have to truncate the values yourself as strings before you put them into that column.

Otherwise, if you want more decimal places, you will need to change your declaration of the decimal column.

TypeError: sequence item 0: expected string, int found

string.join connects elements inside list of strings, not ints.

Use this generator expression instead :

values = ','.join(str(v) for v in value_list)

How to read the value of a private field from a different class in Java?

You can use Manifold's @JailBreak for direct, type-safe Java reflection:

@JailBreak Foo foo = new Foo();
foo.stuffIWant = "123;

public class Foo {
    private String stuffIWant;
}

@JailBreak unlocks the foo local variable in the compiler for direct access to all the members in Foo's hierarchy.

Similarly you can use the jailbreak() extension method for one-off use:

foo.jailbreak().stuffIWant = "123";

Through the jailbreak() method you can access any member in Foo's hierarchy.

In both cases the compiler resolves the field access for you type-safely, as if a public field, while Manifold generates efficient reflection code for you under the hood.

Discover more about Manifold.